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
3 changes: 3 additions & 0 deletions README.ko.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 # 기록 모두 지우기
Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 8 additions & 1 deletion site/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand All @@ -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).
Expand Down
9 changes: 8 additions & 1 deletion site/ko/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -343,7 +343,7 @@ cdg term [OPTIONS] [COMMAND]

| 옵션 | 뜻 |
| --- | --- |
| `-n`, `--count` | 가져올 최근 명령의 수. 기본값 1. |
| `-n`, `--count` | 가져올 최근 명령의 수 또는 범위 (예: `5`, `3-5`). 기본값 1. |
| `-i`, `--index` | 가장 최근부터 거꾸로 세어 정확히 하나만 고릅니다 (1 = 마지막). |
| `-f`, `--failed` | 종료 코드가 0이 아닌 명령만. |
| `--here` | 현재 폴더 또는 그 아래에서 실행한 명령만. |
Expand All @@ -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)을 참고하세요.
Expand Down
2 changes: 2 additions & 0 deletions site/ko/terminal-capture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 # 기록 모두 지우기
Expand Down
2 changes: 2 additions & 0 deletions site/terminal-capture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
97 changes: 86 additions & 11 deletions src/codigest/commands/term.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import codecs
import os
import re
import sys
import traceback
from contextlib import suppress
Expand All @@ -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

Expand All @@ -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[
Expand Down Expand Up @@ -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 = ""
Expand All @@ -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,
Expand All @@ -103,20 +144,29 @@ 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
"""
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:
Expand Down Expand Up @@ -144,26 +194,51 @@ 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; "
f"cannot reach index {index}."
)
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'}",
)

Expand Down
Loading
Loading