diff --git a/README.ko.md b/README.ko.md index 3bbe870..81a2395 100644 --- a/README.ko.md +++ b/README.ko.md @@ -430,10 +430,13 @@ Markdown은 이를 렌더링하는 채팅용, JSON은 스크립트용입니다. cdg cap "npm run build | tail -20" # 파이프가 있으면 따옴표로 감싸기 cdg term # 마지막 명령과 출력 cdg term -n 3 # 최근 3개 +cdg term -n 3-5 # 3~5번째 전 명령 (오래된 것부터) cdg term -f # 마지막으로 실패한 명령 cdg term --context # 복사 내용에 실행 PC 이름과 셸 정보 추가 cdg term --here -n 3 # 이 프로젝트에서 실행한 최근 3개 cdg term -i 2 # 두 번 전에 실행한 명령 하나만 +cdg term -n 10 -l # 최근 10개를 출력 없이 목록으로 +cdg term -l --format json # 목록을 JSON으로 (index, time, exit_code, cwd, command) cdg term -n 3 --format json # 최근 3개를 JSON으로 (markdown도 가능) cdg term path # 기록 파일 위치 (CODIGEST_HOME으로 바꿀 수 있음) cdg term clear # 기록 모두 지우기 diff --git a/README.md b/README.md index 33fcb4e..240af6c 100644 --- a/README.md +++ b/README.md @@ -458,10 +458,13 @@ your machine, so `cap` and `term` work in any directory. cdg cap "npm run build | tail -20" # quote pipelines cdg term # last command and its output cdg term -n 3 # last 3 +cdg term -n 3-5 # commands 3 to 5 back, oldest first cdg term -f # last failed one cdg term --context # add the PC hostname and shell to the copied context (opt-in) cdg term --here -n 3 # last 3 run in this project cdg term -i 2 # only the command from 2 runs ago +cdg term -n 10 -l # list the last 10 commands, without their output +cdg term -l --format json # list as JSON (index, time, exit_code, cwd, command) cdg term -n 3 --format json # the last 3 as JSON (markdown also works) cdg term path # where captures are stored (override with CODIGEST_HOME) cdg term clear # delete all captures diff --git a/site/commands.md b/site/commands.md index 6b8e9c5..7140577 100644 --- a/site/commands.md +++ b/site/commands.md @@ -343,7 +343,7 @@ Without a subcommand it prints the most recent captures. When nothing was captur | Option | Meaning | | --- | --- | -| `-n`, `--count` | Number of recent commands to include. Default 1. | +| `-n`, `--count` | Number or range of recent commands to include (e.g. `5` or `3-5`). Default 1. | | `-i`, `--index` | Pick exactly one command, counting back from the latest (1 = last). | | `-f`, `--failed` | Only commands that exited non-zero. | | `--here` | Only commands run in the current directory or below. | @@ -357,12 +357,19 @@ Without a subcommand it prints the most recent captures. When nothing was captur ```bash cdg term # last command and its output cdg term -n 3 # last 3 +cdg term -n 3-5 # commands 3 to 5 back, oldest first cdg term -f # last failed one cdg term --here -n 3 # last 3 run in this project cdg term -i 2 # only the command from 2 runs ago +cdg term -n 10 -l # list the last 10 commands, without their output +cdg term -l --format json # list as JSON (index, time, exit_code, cwd, command) cdg term --context # add hostname and shell ``` +#### Python-only: `--list`, `-l` + +The Python package can list the selected commands instead of their output: one line per command with the index from the latest (matching what `-i` picks under the same filters), time, exit code, short working directory and a note when the output was not captured. `--format json` outputs those rows as JSON (`index`, `time`, `exit_code`, `cwd`, `command`). It always prints and never copies, so `-i` or `-n A-B` can pick afterwards. The prebuilt binary (the Rust build) does not have it. + #### `--raw`, only in the binary {#term-raw} The prebuilt binary (the Rust build) has one more option here: `term --raw` prints the stored output of one command without tags. The Python package does not have it. See [Rust Port](/rust-port). diff --git a/site/ko/commands.md b/site/ko/commands.md index cf824b8..c333dd9 100644 --- a/site/ko/commands.md +++ b/site/ko/commands.md @@ -343,7 +343,7 @@ cdg term [OPTIONS] [COMMAND] | 옵션 | 뜻 | | --- | --- | -| `-n`, `--count` | 가져올 최근 명령의 수. 기본값 1. | +| `-n`, `--count` | 가져올 최근 명령의 수 또는 범위 (예: `5`, `3-5`). 기본값 1. | | `-i`, `--index` | 가장 최근부터 거꾸로 세어 정확히 하나만 고릅니다 (1 = 마지막). | | `-f`, `--failed` | 종료 코드가 0이 아닌 명령만. | | `--here` | 현재 폴더 또는 그 아래에서 실행한 명령만. | @@ -357,12 +357,19 @@ cdg term [OPTIONS] [COMMAND] ```bash cdg term # 마지막 명령과 출력 cdg term -n 3 # 최근 3개 +cdg term -n 3-5 # 3~5번째 전 명령 (오래된 것부터) cdg term -f # 마지막으로 실패한 명령 cdg term --here -n 3 # 이 프로젝트에서 실행한 최근 3개 cdg term -i 2 # 두 번 전에 실행한 명령 하나만 +cdg term -n 10 -l # 최근 10개를 출력 없이 목록으로 +cdg term -l --format json # 목록을 JSON으로 (index, time, exit_code, cwd, command) cdg term --context # PC 이름과 셸 정보 추가 ``` +#### Python-only: `--list`, `-l` + +Python 패키지는 출력 대신 선택한 명령을 목록으로 보여 줍니다. 한 줄에 명령 하나씩, 같은 필터에서 `-i`가 고르는 것과 같은 인덱스, 시각, 종료 코드, 짧은 작업 폴더, 출력이 기록되지 않았을 때의 표시가 붙습니다. `--format json`을 쓰면 목록을 JSON(`index`, `time`, `exit_code`, `cwd`, `command`)으로 내보냅니다. 항상 출력하고 클립보드에는 복사하지 않으므로, 목록을 본 뒤 `-i`나 `-n A-B`로 고를 수 있습니다. 빌드된 바이너리(Rust 빌드)에는 없습니다. + #### `--raw`, 바이너리에만 있음 {#term-raw} 빌드된 바이너리(Rust 빌드)에는 여기에 옵션이 하나 더 있습니다. `term --raw`는 명령 하나의 저장된 출력을 태그 없이 출력합니다. Python 패키지에는 없습니다. [Rust 포팅](/ko/rust-port)을 참고하세요. diff --git a/site/ko/terminal-capture.md b/site/ko/terminal-capture.md index faf65e8..5cab96f 100644 --- a/site/ko/terminal-capture.md +++ b/site/ko/terminal-capture.md @@ -18,9 +18,11 @@ cdg cap "npm run build | tail -20" # 파이프가 있으면 따옴표로 감싸 ```bash cdg term # 마지막 명령과 출력 cdg term -n 3 # 최근 3개 +cdg term -n 3-5 # 3~5번째 전 명령 (오래된 것부터) cdg term -f # 마지막으로 실패한 명령 cdg term --here -n 3 # 이 프로젝트에서 실행한 최근 3개 cdg term -i 2 # 두 번 전에 실행한 명령 하나만 +cdg term -n 10 -l # 최근 10개를 출력 없이 목록으로 cdg term --context # 복사 내용에 실행 PC 이름과 셸 정보 추가 (선택) cdg term path # 기록 파일 위치 (CODIGEST_HOME으로 바꿀 수 있음) cdg term clear # 기록 모두 지우기 diff --git a/site/terminal-capture.md b/site/terminal-capture.md index 7ab09f8..8cdced9 100644 --- a/site/terminal-capture.md +++ b/site/terminal-capture.md @@ -18,9 +18,11 @@ The output looks exactly as it would without `cap`. The exit code is passed thro ```bash cdg term # last command and its output cdg term -n 3 # last 3 +cdg term -n 3-5 # commands 3 to 5 back, oldest first cdg term -f # last failed one cdg term --here -n 3 # last 3 run in this project cdg term -i 2 # only the command from 2 runs ago +cdg term -n 10 -l # list the last 10 commands, without their output cdg term --context # add the PC hostname and shell to the copied context (opt-in) cdg term path # where captures are stored (override with CODIGEST_HOME) cdg term clear # delete all captures diff --git a/src/codigest/commands/term.py b/src/codigest/commands/term.py index a6c28af..c327b6a 100644 --- a/src/codigest/commands/term.py +++ b/src/codigest/commands/term.py @@ -4,6 +4,7 @@ import codecs import os +import re import sys import traceback from contextlib import suppress @@ -12,6 +13,7 @@ from typing import Annotated import typer +from click.core import ParameterSource from rich.console import Console from rich.markup import escape @@ -27,8 +29,12 @@ app = typer.Typer() CountOption = Annotated[ - int, - typer.Option("-n", "--count", min=1, help="Number of recent commands to include"), + str, + typer.Option( + "-n", + "--count", + help="Number or range of recent commands to include (e.g. 5 or 3-5)", + ), ] IndexOption = Annotated[ @@ -64,12 +70,46 @@ ), ] +ListOption = Annotated[ + bool, + typer.Option( + "-l", + "--list", + help="List the selected commands without their output (all unless -n; never copies)", + ), +] + + +_COUNT_RE = re.compile(r"^\s*(\d+)(?:\s*-\s*(\d+))?\s*$") -def _summarize(handler: OutputHandler, entries: list[termstore.Entry]) -> None: + +def _parse_count(raw: str) -> tuple[int, int, bool]: + """Parses `N` or `A-B` into `(lo, hi, is_range)`, 1-based counting back from latest.""" + m = _COUNT_RE.fullmatch(raw) + if not m: + raise typer.BadParameter( + f"invalid count or range {raw!r}; expected a positive integer (e.g. 5) or range (e.g. 3-5)", + param_hint="'-n' / '--count'", + ) + a = int(m.group(1)) + b = int(m.group(2)) if m.group(2) is not None else None + if a < 1 or (b is not None and b < 1): + raise typer.BadParameter( + "count and range indices must be at least 1", + param_hint="'-n' / '--count'", + ) + if b is None: + return 1, a, False + return min(a, b), max(a, b), True + + +def _summarize( + handler: OutputHandler, entries: list[termstore.Entry], *, start_index: int = 1 +) -> None: log = handler.log_console total = len(entries) for offset, entry in enumerate(entries): - index = total - offset + index = start_index + total - 1 - offset match entry.exit_code: case None: status = "" @@ -84,11 +124,12 @@ def _summarize(handler: OutputHandler, entries: list[termstore.Entry]) -> None: @app.callback(invoke_without_command=True) def handle( ctx: typer.Context, - count: CountOption = 1, + count: CountOption = "1", index: IndexOption = None, failed: FailedOption = False, here: HereOption = False, history_only: HistoryOnlyOption = False, + list_mode: ListOption = False, context: ContextOption = False, format: FormatOption = Format.XML, copy: CopyOption = None, @@ -103,8 +144,11 @@ def handle( \b cdg term # the last command cdg term -n 3 # the last 3 commands + cdg term -n 3-5 # commands 3 to 5 back, oldest first cdg term -i 3 # only the command from 3 runs ago cdg term -f # the last failed command + cdg term -n 10 -l # list the last 10 commands, without their output + cdg term -l --format json # list as JSON (index, time, exit_code, cwd, command) cdg term --context # include host + shell when copying for AI cdg term --here -n 3 # the last 3 commands run in this project cdg term --format json # for scripts; markdown for a chat @@ -112,11 +156,17 @@ def handle( if ctx.invoked_subcommand: return + lo, hi, is_range = _parse_count(count) handler = OutputHandler(stdout=stdout, copy=copy, output=output) log = handler.log_console - # -i N needs N entries loaded so the Nth-from-last exists. - depth = index or count + # --list without -n shows everything that matches; -n still narrows it. + list_all = ( + list_mode and index is None and ctx.get_parameter_source("count") is ParameterSource.DEFAULT + ) + + # -i N needs N entries loaded so the Nth-from-last exists; a range needs `hi`. + depth = index or (termstore.MAX_ENTRIES if list_all else hi) entries: list[termstore.Entry] = [] if not history_only: @@ -144,7 +194,7 @@ def handle( log.print(f"[yellow]No captured commands match ({what}).[/yellow]") raise typer.Exit(code=1) - if index: + if index is not None: if index > len(entries): log.print( f"[red][Error][/red] Only {len(entries)} entries available; " @@ -152,18 +202,43 @@ def handle( ) raise typer.Exit(code=1) selected = [entries[-index]] + start_index = index if list_mode else 1 + elif list_all: + selected = entries + start_index = 1 + elif is_range: + if lo > len(entries): + log.print( + f"[red][Error][/red] Only {len(entries)} entries available; " + f"cannot reach range {lo}-{hi}." + ) + raise typer.Exit(code=1) + selected = entries[max(0, len(entries) - hi) : len(entries) - (lo - 1)] + start_index = lo else: - selected = entries[-count:] + selected = entries[-hi:] + start_index = 1 + + if list_mode: + # A list is for scanning and picking an index, so it always prints and never + # replaces the clipboard with something that only resembles the command. + list_render = termstore.render_list_json if format is Format.JSON else termstore.render_list + content = list_render(selected, include_context=context, start_index=start_index) + OutputHandler(stdout=True, copy=False, output=output).handle_output( + content, + item_name=f"{len(selected)} terminal entr{'y' if len(selected) == 1 else 'ies'}", + ) + return render = { Format.XML: termstore.render, Format.MARKDOWN: termstore.render_markdown, Format.JSON: termstore.render_json, }[format] - content = render(selected, include_context=context) + content = render(selected, include_context=context, start_index=start_index) handler.handle_output( content, - summary=lambda: _summarize(handler, selected), + summary=lambda: _summarize(handler, selected, start_index=start_index), item_name=f"{len(selected)} terminal entr{'y' if len(selected) == 1 else 'ies'}", ) diff --git a/src/codigest/core/termstore.py b/src/codigest/core/termstore.py index a56ec4e..fce7e08 100644 --- a/src/codigest/core/termstore.py +++ b/src/codigest/core/termstore.py @@ -20,7 +20,7 @@ import socket import sys from dataclasses import asdict, dataclass, fields -from datetime import datetime +from datetime import date, datetime from pathlib import Path from typing import Any, Self @@ -226,7 +226,50 @@ def _fmt_duration(ms: int) -> str: return f"{ms / 1000:.1f}s" -def render(entries: list[Entry], *, include_context: bool = False) -> str: +def _entry_index(total: int, offset: int, start_index: int) -> int: + return start_index + (total - 1 - offset) + + +def _format_time(started_at: str, *, today: date | None = None) -> str: + if not started_at: + return "" + try: + dt = datetime.fromisoformat(started_at) + except ValueError: + return "" + ref_today = today or (datetime.now(dt.tzinfo).date() if dt.tzinfo else date.today()) + if dt.date() == ref_today: + return dt.strftime("%H:%M") + return dt.strftime("%Y-%m-%d %H:%M") + + +def _short_cwd(cwd: str) -> str: + if not cwd: + return "" + clean = cwd.replace("\\", "/") + if clean == "/": + return "/" + if re.fullmatch(r"[A-Za-z]:/?", clean): + return f"{clean[0]}:/" + clean = clean.rstrip("/") + home = str(Path.home()).replace("\\", "/").rstrip("/") + norm = str.casefold if os.name == "nt" else str + if len(home) > 1: + if norm(clean) == norm(home): + return "~" + if norm(clean).startswith(norm(home) + "/"): + rel = clean[len(home) + 1 :] + parts = [p for p in rel.split("/") if p] + if len(parts) <= 2: + return "~/" + "/".join(parts) + return "~/.../" + "/".join(parts[-2:]) + parts = [p for p in clean.split("/") if p] + if len(parts) <= 2: + return clean + return ".../" + "/".join(parts[-2:]) + + +def render(entries: list[Entry], *, include_context: bool = False, start_index: int = 1) -> str: """ Renders entries as an XML block. `index` is 1-based counting backwards: index="1" is the most recent command, index="3" is three commands ago. @@ -237,7 +280,7 @@ def render(entries: list[Entry], *, include_context: bool = False) -> str: blocks = [] total = len(entries) for offset, entry in enumerate(entries): - index = total - offset + index = _entry_index(total, offset, start_index) attrs = [ f'index="{index}"', f'command="{html.escape(entry.command)}"', @@ -271,7 +314,9 @@ def render(entries: list[Entry], *, include_context: bool = False) -> str: return "\n" + "\n".join(blocks) + "\n" -def render_markdown(entries: list[Entry], *, include_context: bool = False) -> str: +def render_markdown( + entries: list[Entry], *, include_context: bool = False, start_index: int = 1 +) -> str: """A heading per command, its details as a list, and the command with its output in one console block, the way it looked in the terminal.""" blocks = [] @@ -289,7 +334,7 @@ def render_markdown(entries: list[Entry], *, include_context: bool = False) -> s if not entry.captured: details.append(("output", "not stored (read from shell history)")) details.append(("note", entry.note)) - lines = [f"## Command {total - offset}{status}", ""] + lines = [f"## Command {_entry_index(total, offset, start_index)}{status}", ""] lines += [f"- {name}: {value}" for name, value in details if value] if len(lines) > 2: lines.append("") @@ -302,13 +347,71 @@ def render_markdown(entries: list[Entry], *, include_context: bool = False) -> s return "\n\n".join(blocks) -def render_json(entries: list[Entry], *, include_context: bool = False) -> str: +def render_list( + entries: list[Entry], + *, + include_context: bool = False, + start_index: int = 1, + today: date | None = None, +) -> str: + """ + One line per entry for `cdg term --list`: `index`, time, exit code, short cwd, + the command, and whether output was stored. `index` matches `-i` under the same + filters. Meant for a terminal, not for an LLM. + """ + total = len(entries) + lines = [] + for offset, entry in enumerate(entries): + index = _entry_index(total, offset, start_index) + command = " ".join(entry.command.splitlines()) + when = _format_time(entry.started_at, today=today) + status = f"exit {entry.exit_code}" if entry.exit_code is not None else "" + where = _short_cwd(entry.cwd) + meta = " ".join(part for part in (when, status, where) if part) + marker = "" if entry.captured else " (no output)" + context = "" + if include_context: + details = " on ".join(v for v in (entry.shell, entry.hostname) if v) + context = f" [{details}]" if details else "" + row = f"{index}. {meta} {command}" if meta else f"{index}. {command}" + lines.append(f"{row}{marker}{context}") + return "\n".join(lines) + + +def render_list_json( + entries: list[Entry], + *, + include_context: bool = False, + start_index: int = 1, + today: date | None = None, +) -> str: + """JSON array of list rows, newest last, matching `render_list` indices.""" + total = len(entries) + items = [] + for offset, entry in enumerate(entries): + item: dict[str, Any] = { + "index": _entry_index(total, offset, start_index), + "time": _format_time(entry.started_at, today=today), + "exit_code": entry.exit_code, + "cwd": entry.cwd, + "command": entry.command, + } + if include_context: + item["hostname"] = entry.hostname + item["shell"] = entry.shell + items.append(item) + return json.dumps(items, indent=2, ensure_ascii=False) + + +def render_json( + entries: list[Entry], *, include_context: bool = False, start_index: int = 1 +) -> str: """A JSON array, newest last, each item with its `index` counting back from the latest.""" total = len(entries) items = [] for offset, entry in enumerate(entries): item = { - "index": total - offset, + "index": _entry_index(total, offset, start_index), "command": entry.command, "exit_code": entry.exit_code, "cwd": entry.cwd, diff --git a/tests/test_formats.py b/tests/test_formats.py index 9d88f1d..c8a7a5e 100644 --- a/tests/test_formats.py +++ b/tests/test_formats.py @@ -1,4 +1,6 @@ import json +from datetime import date +from pathlib import Path from typer.testing import CliRunner @@ -60,6 +62,61 @@ def test_term_markdown_notes_what_was_not_captured(): ) +def test_term_list_is_one_line_per_command_indexed_from_the_latest(): + assert termstore.render_list(history(), today=date(2026, 1, 1)).splitlines() == [ + "2. 10:00 exit 1 /w pytest -q", + "1. 10:00 exit 0 /w echo hi", + ] + assert termstore.render_list(history(), today=date(2026, 1, 2)).splitlines() == [ + "2. 2026-01-01 10:00 exit 1 /w pytest -q", + "1. 2026-01-01 10:00 exit 0 /w echo hi", + ] + + +def test_term_list_shortens_cwd_and_marks_no_output(): + home = Path.home() + entries = [ + Entry( + command="ls\n-la", + captured=False, + cwd=str(home / "a" / "b" / "c"), + shell="bash", + hostname="PC", + ), + Entry(command="pwd", exit_code=0, cwd="/work/org/proj"), + Entry(command="whoami", exit_code=0, cwd=str(home / "proj")), + ] + assert termstore.render_list(entries).splitlines() == [ + "3. ~/.../b/c ls -la (no output)", + "2. exit 0 .../org/proj pwd", + "1. exit 0 ~/proj whoami", + ] + assert ( + termstore.render_list(entries[:1], include_context=True) + == "1. ~/.../b/c ls -la (no output) [bash on PC]" + ) + + +def test_term_list_json_has_row_fields_and_respects_start_index(): + items = json.loads(termstore.render_list_json(history(), start_index=3, today=date(2026, 1, 1))) + assert items == [ + { + "index": 4, + "time": "10:00", + "exit_code": 1, + "cwd": "/w", + "command": "pytest -q", + }, + { + "index": 3, + "time": "10:00", + "exit_code": 0, + "cwd": "/w", + "command": "echo hi", + }, + ] + + def test_term_json_is_an_array_indexed_from_the_latest(): items = json.loads(termstore.render_json(history())) assert [i["index"] for i in items] == [2, 1] diff --git a/tests/test_term_list.py b/tests/test_term_list.py new file mode 100644 index 0000000..2028b11 --- /dev/null +++ b/tests/test_term_list.py @@ -0,0 +1,145 @@ +"""`cdg term --list` and `-n` ranges.""" + +import json +import xml.etree.ElementTree as ET +from datetime import datetime + +from typer.testing import CliRunner + +from codigest.commands import term +from codigest.core import output as output_mod +from codigest.core import termstore + + +def _seed(tmp_path, monkeypatch, rows): + monkeypatch.setenv("CODIGEST_HOME", str(tmp_path)) + today = datetime.now().astimezone().replace(hour=9, minute=0, second=0, microsecond=0) + for i, (command, code, cwd) in enumerate(rows): + ts = today.replace(minute=i).isoformat(timespec="seconds") + termstore.append_entry( + termstore.Entry( + command=command, + output=f"out-{command}", + exit_code=code, + cwd=cwd, + started_at=ts, + ) + ) + + +def test_list_prints_metadata_and_never_copies_even_with_copy_flag(tmp_path, monkeypatch): + _seed( + tmp_path, + monkeypatch, + [ + ("pytest -q", 1, "/w"), + ("git status", 0, "/w"), + ], + ) + copied = [] + monkeypatch.setattr(output_mod.pyperclip, "copy", lambda text: copied.append(text)) + + result = CliRunner().invoke(term.app, ["--list", "--copy"]) + + assert result.exit_code == 0, result.output + assert result.stdout.splitlines() == [ + "2. 09:00 exit 1 /w pytest -q", + "1. 09:01 exit 0 /w git status", + ] + assert "out-pytest" not in result.stdout and "out-git" not in result.stdout + assert "Copied" not in result.stdout + assert copied == [] + + +def test_list_index_matches_what_dash_i_picks_under_filters(tmp_path, monkeypatch): + _seed( + tmp_path, + monkeypatch, + [ + ("build", 1, "/w"), + ("test", 0, "/w"), + ("lint", 2, "/w"), + ("deploy", 3, "/w"), + ], + ) + runner = CliRunner() + + listed = runner.invoke(term.app, ["-f", "-n", "2-3", "--list"]) + assert listed.exit_code == 0, listed.output + assert listed.stdout.splitlines() == [ + "3. 09:00 exit 1 /w build", + "2. 09:02 exit 2 /w lint", + ] + + single = runner.invoke(term.app, ["-f", "--index", "2", "--list"]) + assert single.exit_code == 0, single.output + assert single.stdout.strip() == "2. 09:02 exit 2 /w lint" + + picked = runner.invoke(term.app, ["-f", "--index", "2", "--stdout", "--no-copy"]) + assert picked.exit_code == 0, picked.output + assert 'command="lint"' in picked.stdout + + +def test_count_range_forward_and_reversed_picks_commands_oldest_first(tmp_path, monkeypatch): + _seed( + tmp_path, + monkeypatch, + [(f"cmd{n}", 0, "/w") for n in range(1, 7)], + ) + runner = CliRunner() + + fwd = runner.invoke(term.app, ["-n", "3-5", "--stdout", "--no-copy"]) + rev = runner.invoke(term.app, ["-n", "5-3", "--stdout", "--no-copy"]) + assert fwd.exit_code == 0, fwd.output + assert rev.exit_code == 0, rev.output + assert fwd.stdout == rev.stdout + + root = ET.fromstring(fwd.stdout) + cmds = [(el.attrib["index"], el.attrib["command"], el.findtext("output")) for el in root] + assert cmds == [ + ("5", "cmd2", "\nout-cmd2\n"), + ("4", "cmd3", "\nout-cmd3\n"), + ("3", "cmd4", "\nout-cmd4\n"), + ] + + +def test_count_bad_and_unreachable_ranges_fail_clearly(tmp_path, monkeypatch): + _seed(tmp_path, monkeypatch, [("cmd1", 0, "/w"), ("cmd2", 0, "/w")]) + runner = CliRunner() + + for bad in ("0", "0-2", "3-", "abc", "1-2-3"): + res = runner.invoke(term.app, ["-n", bad]) + assert res.exit_code != 0 + assert "Error" in res.output or "Invalid" in res.output + + neg = runner.invoke(term.app, ["-n=-2"]) + assert neg.exit_code != 0 + + oob = runner.invoke(term.app, ["-n", "3-5"]) + assert oob.exit_code != 0 + assert "Only 2 entries available" in oob.output + + +def test_list_format_json_outputs_rows_and_supports_ranges(tmp_path, monkeypatch): + _seed( + tmp_path, + monkeypatch, + [ + ("cmd1", 0, "/a"), + ("cmd2", 1, "/b"), + ("cmd3", 0, "/c"), + ("cmd4", 2, "/d"), + ], + ) + copied = [] + monkeypatch.setattr(output_mod.pyperclip, "copy", lambda text: copied.append(text)) + + res = CliRunner().invoke(term.app, ["--list", "--format", "json", "-n", "2-3"]) + + assert res.exit_code == 0, res.output + rows = json.loads(res.stdout) + assert rows == [ + {"index": 3, "time": "09:01", "exit_code": 1, "cwd": "/b", "command": "cmd2"}, + {"index": 2, "time": "09:02", "exit_code": 0, "cwd": "/c", "command": "cmd3"}, + ] + assert copied == []