Skip to content

Commit eeec8b9

Browse files
authored
refactor: simplify list outputs (#109)
A future PR may add the ability to specify a custom format.
1 parent 0bfb078 commit eeec8b9

File tree

9 files changed

+19
-95
lines changed

9 files changed

+19
-95
lines changed

docs/git-draft.1.adoc

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -78,10 +78,6 @@ The template will be created automatically if it did not already exist.
7878
--help::
7979
Show help message and exit.
8080

81-
-j::
82-
--json::
83-
Use JSON output.
84-
8581
-E::
8682
--list-events::
8783
Display all events corresponding to a draft.

poetry.lock

Lines changed: 1 addition & 31 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

pyproject.toml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ dependencies = [
1010
"docopt-ng (>=0.9,<0.10)",
1111
"jinja2 (>=3.1.5,<4)",
1212
"msgspec (>=0.19.0,<0.20.0)",
13-
"prettytable (>=3.15.1,<4)",
1413
"xdg-base-dirs (>=6.0.2,<7)",
1514
"yaspin (>=3.1.0,<4)",
1615
]

src/git_draft/__main__.py

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
PromptMetadata,
2121
TemplatedPrompt,
2222
find_prompt_metadata,
23-
templates_table,
23+
list_templates,
2424
)
2525
from .store import Store
2626

@@ -94,12 +94,6 @@ def callback(
9494
help="edit prompt or template",
9595
action="store_true",
9696
)
97-
parser.add_option(
98-
"-j",
99-
"--json",
100-
help="use JSON for table output",
101-
action="store_true",
102-
)
10397

10498
parser.add_option(
10599
"--no-accept",
@@ -218,8 +212,8 @@ async def run() -> None: # noqa: PLR0912 PLR0915
218212
drafter.quit_folio()
219213
case "list-events":
220214
draft_id = args[0] if args else None
221-
for elem in drafter.list_draft_events(draft_id):
222-
print(elem)
215+
for line in drafter.list_draft_events(draft_id):
216+
print(line)
223217
case "show-template":
224218
if len(args) != 1:
225219
raise ValueError("Expected exactly one argument")
@@ -235,8 +229,8 @@ async def run() -> None: # noqa: PLR0912 PLR0915
235229
raise ValueError(f"No template named {name!r}")
236230
print(meta.source())
237231
case "list-templates":
238-
table = templates_table()
239-
print(table.to_json() if opts.json else table)
232+
for line in list_templates():
233+
print(line)
240234
case _:
241235
raise UnreachableError()
242236

src/git_draft/common.py

Lines changed: 1 addition & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,10 @@
99
import logging
1010
import os
1111
from pathlib import Path
12-
import sqlite3
1312
import textwrap
1413
import tomllib
15-
from typing import Any, ClassVar, Self
14+
from typing import Any, Self
1615

17-
import prettytable
1816
import xdg_base_dirs
1917

2018

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

120118
def now() -> datetime:
121119
return datetime.now().astimezone()
122-
123-
124-
class Table:
125-
"""Pretty-printable table"""
126-
127-
_kwargs: ClassVar[Mapping[str, Any]] = dict(border=False) # Shared options
128-
129-
def __init__(self, data: prettytable.PrettyTable) -> None:
130-
self.data = data
131-
self.data.align = "l"
132-
133-
def __bool__(self) -> bool:
134-
return len(self.data.rows) > 0
135-
136-
def __str__(self) -> str:
137-
return str(self.data) if self else ""
138-
139-
def to_json(self) -> str:
140-
return self.data.get_json_string(header=False)
141-
142-
@classmethod
143-
def empty(cls) -> Self:
144-
return cls(prettytable.PrettyTable([], **cls._kwargs))
145-
146-
@classmethod
147-
def from_cursor(cls, cursor: sqlite3.Cursor) -> Self:
148-
table = prettytable.from_db_cursor(cursor, **cls._kwargs)
149-
assert table
150-
return cls(table)

src/git_draft/drafter.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
from __future__ import annotations
44

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

455-
def list_draft_events(self, draft_ref: str | None = None) -> Sequence[str]:
455+
def list_draft_events(self, draft_ref: str | None = None) -> Iterator[str]:
456456
if draft_ref:
457457
folio_id, seqno = _parse_draft_ref(draft_ref)
458458
else:
459459
folio = _active_folio(self._repo)
460460
folio_id = folio.id
461461
seqno = None
462-
elems = []
463462
with self._store.cursor() as cursor:
464463
rows = cursor.execute(
465464
sql("list-action-events"),
@@ -470,8 +469,7 @@ def list_draft_events(self, draft_ref: str | None = None) -> Sequence[str]:
470469
occurred_at, class_name, data = row
471470
event = decoders[class_name].decode(data)
472471
description = _format_event(event)
473-
elems.append(f"{occurred_at}\t{class_name}\t{description}")
474-
return elems
472+
yield "\t".join([occurred_at, class_name, description])
475473

476474

477475
@dataclasses.dataclass(frozen=True)

src/git_draft/prompt.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
from __future__ import annotations
44

5-
from collections.abc import Mapping, Sequence
5+
from collections.abc import Iterator, Mapping, Sequence
66
import dataclasses
77
import enum
88
import functools
@@ -15,7 +15,7 @@
1515
import jinja2
1616

1717
from .bots import Worktree
18-
from .common import Config, Table, package_root
18+
from .common import Config, package_root
1919
from .worktrees import EmptyWorktree
2020

2121

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

212212

213-
def templates_table(*, include_local: bool = True) -> Table:
213+
def list_templates(*, include_local: bool = True) -> Iterator[str]:
214214
env = _jinja_environment(include_local=include_local)
215215
worktree = EmptyWorktree()
216-
table = Table.empty()
217-
table.data.field_names = ["name", "local", "description"]
218216
for rel_path in env.list_templates(extensions=[_extension]):
219217
if any(p.startswith(".") for p in rel_path.split(os.sep)):
220218
continue
221219
name, _ext = os.path.splitext(rel_path)
222220
prompt = _load_prompt(env, name, worktree)
223221
metadata = prompt.metadata
224222
local = "y" if metadata.is_local() else "n"
225-
table.data.add_row([name, local, metadata.description or ""])
226-
return table
223+
yield "\t".join([name, local, metadata.description or ""])

tests/git_draft/drafter_test.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -192,5 +192,5 @@ async def test_latest_draft_prompt_no_active_branch(self) -> None:
192192
async def test_list_draft_events(self) -> None:
193193
bot = _SimpleBot({"prompt": lambda goal: goal.prompt})
194194
await self._drafter.generate_draft("prompt1", bot, "theirs")
195-
elems = self._drafter.list_draft_events()
196-
assert len(elems) == 1
195+
lines = list(self._drafter.list_draft_events())
196+
assert len(lines) == 1

tests/git_draft/prompt_test.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,5 +41,6 @@ def test_missing(self) -> None:
4141
assert sut.find_prompt_metadata("foo") is None
4242

4343

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

0 commit comments

Comments
 (0)