Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 0 additions & 4 deletions docs/git-draft.1.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,6 @@ The template will be created automatically if it did not already exist.
--help::
Show help message and exit.

-j::
--json::
Use JSON output.

-E::
--list-events::
Display all events corresponding to a draft.
Expand Down
32 changes: 1 addition & 31 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ dependencies = [
"docopt-ng (>=0.9,<0.10)",
"jinja2 (>=3.1.5,<4)",
"msgspec (>=0.19.0,<0.20.0)",
"prettytable (>=3.15.1,<4)",
"xdg-base-dirs (>=6.0.2,<7)",
"yaspin (>=3.1.0,<4)",
]
Expand Down
16 changes: 5 additions & 11 deletions src/git_draft/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
PromptMetadata,
TemplatedPrompt,
find_prompt_metadata,
templates_table,
list_templates,
)
from .store import Store

Expand Down Expand Up @@ -94,12 +94,6 @@ def callback(
help="edit prompt or template",
action="store_true",
)
parser.add_option(
"-j",
"--json",
help="use JSON for table output",
action="store_true",
)

parser.add_option(
"--no-accept",
Expand Down Expand Up @@ -218,8 +212,8 @@ async def run() -> None: # noqa: PLR0912 PLR0915
drafter.quit_folio()
case "list-events":
draft_id = args[0] if args else None
for elem in drafter.list_draft_events(draft_id):
print(elem)
for line in drafter.list_draft_events(draft_id):
print(line)
case "show-template":
if len(args) != 1:
raise ValueError("Expected exactly one argument")
Expand All @@ -235,8 +229,8 @@ async def run() -> None: # noqa: PLR0912 PLR0915
raise ValueError(f"No template named {name!r}")
print(meta.source())
case "list-templates":
table = templates_table()
print(table.to_json() if opts.json else table)
for line in list_templates():
print(line)
case _:
raise UnreachableError()

Expand Down
33 changes: 1 addition & 32 deletions src/git_draft/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,10 @@
import logging
import os
from pathlib import Path
import sqlite3
import textwrap
import tomllib
from typing import Any, ClassVar, Self
from typing import Any, Self

import prettytable
import xdg_base_dirs


Expand Down Expand Up @@ -119,32 +117,3 @@ def qualified_class_name(cls: type) -> str:

def now() -> datetime:
return datetime.now().astimezone()


class Table:
"""Pretty-printable table"""

_kwargs: ClassVar[Mapping[str, Any]] = dict(border=False) # Shared options

def __init__(self, data: prettytable.PrettyTable) -> None:
self.data = data
self.data.align = "l"

def __bool__(self) -> bool:
return len(self.data.rows) > 0

def __str__(self) -> str:
return str(self.data) if self else ""

def to_json(self) -> str:
return self.data.get_json_string(header=False)

@classmethod
def empty(cls) -> Self:
return cls(prettytable.PrettyTable([], **cls._kwargs))

@classmethod
def from_cursor(cls, cursor: sqlite3.Cursor) -> Self:
table = prettytable.from_db_cursor(cursor, **cls._kwargs)
assert table
return cls(table)
8 changes: 3 additions & 5 deletions src/git_draft/drafter.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from __future__ import annotations

from collections.abc import Callable, Sequence
from collections.abc import Callable, Iterator, Sequence
import dataclasses
from datetime import datetime, timedelta
import logging
Expand Down Expand Up @@ -452,14 +452,13 @@ def latest_draft_prompt(self) -> str | None:
prompt = "\n\n".join([prompt, reindent(question, prefix="> ")])
return prompt

def list_draft_events(self, draft_ref: str | None = None) -> Sequence[str]:
def list_draft_events(self, draft_ref: str | None = None) -> Iterator[str]:
if draft_ref:
folio_id, seqno = _parse_draft_ref(draft_ref)
else:
folio = _active_folio(self._repo)
folio_id = folio.id
seqno = None
elems = []
with self._store.cursor() as cursor:
rows = cursor.execute(
sql("list-action-events"),
Expand All @@ -470,8 +469,7 @@ def list_draft_events(self, draft_ref: str | None = None) -> Sequence[str]:
occurred_at, class_name, data = row
event = decoders[class_name].decode(data)
description = _format_event(event)
elems.append(f"{occurred_at}\t{class_name}\t{description}")
return elems
yield "\t".join([occurred_at, class_name, description])


@dataclasses.dataclass(frozen=True)
Expand Down
11 changes: 4 additions & 7 deletions src/git_draft/prompt.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from __future__ import annotations

from collections.abc import Mapping, Sequence
from collections.abc import Iterator, Mapping, Sequence
import dataclasses
import enum
import functools
Expand All @@ -15,7 +15,7 @@
import jinja2

from .bots import Worktree
from .common import Config, Table, package_root
from .common import Config, package_root
from .worktrees import EmptyWorktree


Expand Down Expand Up @@ -210,17 +210,14 @@ def find_prompt_metadata(name: PromptName) -> PromptMetadata | None:
return prompt.metadata


def templates_table(*, include_local: bool = True) -> Table:
def list_templates(*, include_local: bool = True) -> Iterator[str]:
env = _jinja_environment(include_local=include_local)
worktree = EmptyWorktree()
table = Table.empty()
table.data.field_names = ["name", "local", "description"]
for rel_path in env.list_templates(extensions=[_extension]):
if any(p.startswith(".") for p in rel_path.split(os.sep)):
continue
name, _ext = os.path.splitext(rel_path)
prompt = _load_prompt(env, name, worktree)
metadata = prompt.metadata
local = "y" if metadata.is_local() else "n"
table.data.add_row([name, local, metadata.description or ""])
return table
yield "\t".join([name, local, metadata.description or ""])
4 changes: 2 additions & 2 deletions tests/git_draft/drafter_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,5 +192,5 @@ async def test_latest_draft_prompt_no_active_branch(self) -> None:
async def test_list_draft_events(self) -> None:
bot = _SimpleBot({"prompt": lambda goal: goal.prompt})
await self._drafter.generate_draft("prompt1", bot, "theirs")
elems = self._drafter.list_draft_events()
assert len(elems) == 1
lines = list(self._drafter.list_draft_events())
assert len(lines) == 1
5 changes: 3 additions & 2 deletions tests/git_draft/prompt_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,5 +41,6 @@ def test_missing(self) -> None:
assert sut.find_prompt_metadata("foo") is None


def test_templates_table() -> None:
assert sut.templates_table(include_local=False)
def test_list_templates() -> None:
templates = list(sut.list_templates(include_local=False))
assert templates