|
| 1 | +"""CLI entry point for claude-backup.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import sys |
| 6 | +from pathlib import Path |
| 7 | + |
| 8 | +import click |
| 9 | + |
| 10 | +from . import __version__ |
| 11 | +from .exporter import export_session |
| 12 | +from .scanner import ProjectInfo, get_claude_home, scan_projects |
| 13 | + |
| 14 | + |
| 15 | +@click.group(help="Export Claude Code session history to Markdown.") |
| 16 | +@click.version_option(__version__, prog_name="claude-backup") |
| 17 | +@click.option( |
| 18 | + "--claude-home", |
| 19 | + type=click.Path(path_type=Path), |
| 20 | + default=None, |
| 21 | + help="Override the Claude projects root (default: ~/.claude/projects).", |
| 22 | +) |
| 23 | +@click.pass_context |
| 24 | +def main(ctx: click.Context, claude_home: Path | None) -> None: |
| 25 | + ctx.ensure_object(dict) |
| 26 | + ctx.obj["claude_home"] = claude_home |
| 27 | + |
| 28 | + |
| 29 | +@main.command("list", help="List all discovered sessions.") |
| 30 | +@click.pass_context |
| 31 | +def list_cmd(ctx: click.Context) -> None: |
| 32 | + projects = _safe_scan(ctx.obj.get("claude_home")) |
| 33 | + rows = _flatten_sessions(projects) |
| 34 | + |
| 35 | + if not rows: |
| 36 | + click.echo("No sessions found.") |
| 37 | + return |
| 38 | + |
| 39 | + headers = ["Project", "Session ID", "First Prompt", "Msg Count", "Created", "Git Branch"] |
| 40 | + table_rows = [ |
| 41 | + [ |
| 42 | + r.project, |
| 43 | + r.session_id, |
| 44 | + _truncate(r.first_prompt, 40), |
| 45 | + str(r.message_count), |
| 46 | + r.created or "-", |
| 47 | + r.git_branch or "-", |
| 48 | + ] |
| 49 | + for r in rows |
| 50 | + ] |
| 51 | + click.echo(_format_table(headers, table_rows)) |
| 52 | + |
| 53 | + |
| 54 | +@main.command("export", help="Export a single session by ID.") |
| 55 | +@click.argument("session_id") |
| 56 | +@click.option( |
| 57 | + "--output", |
| 58 | + "-o", |
| 59 | + type=click.Path(path_type=Path), |
| 60 | + default=Path("./backups"), |
| 61 | + help="Output directory (default: ./backups/).", |
| 62 | +) |
| 63 | +@click.pass_context |
| 64 | +def export_cmd(ctx: click.Context, session_id: str, output: Path) -> None: |
| 65 | + projects = _safe_scan(ctx.obj.get("claude_home")) |
| 66 | + target = None |
| 67 | + for project in projects: |
| 68 | + for session in project.sessions: |
| 69 | + if session.session_id == session_id: |
| 70 | + target = session |
| 71 | + break |
| 72 | + if target: |
| 73 | + break |
| 74 | + |
| 75 | + if target is None: |
| 76 | + click.echo(f"Session not found: {session_id}", err=True) |
| 77 | + sys.exit(2) |
| 78 | + |
| 79 | + if target.jsonl_path is None or not target.jsonl_path.exists(): |
| 80 | + click.echo( |
| 81 | + f"Session {session_id} has no JSONL file on disk.", err=True |
| 82 | + ) |
| 83 | + sys.exit(2) |
| 84 | + |
| 85 | + out = export_session(target, output) |
| 86 | + click.echo(f"Exported: {out}") |
| 87 | + |
| 88 | + |
| 89 | +@main.command("export-all", help="Export every discovered session.") |
| 90 | +@click.option( |
| 91 | + "--output", |
| 92 | + "-o", |
| 93 | + type=click.Path(path_type=Path), |
| 94 | + default=Path("./backups"), |
| 95 | + help="Output directory (default: ./backups/).", |
| 96 | +) |
| 97 | +@click.pass_context |
| 98 | +def export_all_cmd(ctx: click.Context, output: Path) -> None: |
| 99 | + projects = _safe_scan(ctx.obj.get("claude_home")) |
| 100 | + exported = 0 |
| 101 | + skipped = 0 |
| 102 | + |
| 103 | + for project in projects: |
| 104 | + project_out = output / project.name |
| 105 | + for session in project.sessions: |
| 106 | + if session.jsonl_path is None or not session.jsonl_path.exists(): |
| 107 | + click.echo( |
| 108 | + f"Skip {project.name}/{session.session_id}: no JSONL file", |
| 109 | + err=True, |
| 110 | + ) |
| 111 | + skipped += 1 |
| 112 | + continue |
| 113 | + try: |
| 114 | + path = export_session(session, project_out) |
| 115 | + click.echo(f"Exported: {path}") |
| 116 | + exported += 1 |
| 117 | + except Exception as e: # pragma: no cover - defensive |
| 118 | + click.echo( |
| 119 | + f"Failed {project.name}/{session.session_id}: {e}", err=True |
| 120 | + ) |
| 121 | + skipped += 1 |
| 122 | + |
| 123 | + click.echo(f"\nDone. Exported: {exported}, skipped: {skipped}") |
| 124 | + |
| 125 | + |
| 126 | +def _safe_scan(claude_home: Path | None) -> list[ProjectInfo]: |
| 127 | + try: |
| 128 | + return scan_projects(claude_home) |
| 129 | + except FileNotFoundError: |
| 130 | + root = get_claude_home(claude_home) |
| 131 | + click.echo( |
| 132 | + f"Error: Claude projects directory not found at {root}.\n" |
| 133 | + f"Have you used Claude Code on this machine?", |
| 134 | + err=True, |
| 135 | + ) |
| 136 | + sys.exit(1) |
| 137 | + except NotADirectoryError as e: |
| 138 | + click.echo(f"Error: {e}", err=True) |
| 139 | + sys.exit(1) |
| 140 | + |
| 141 | + |
| 142 | +def _flatten_sessions(projects): |
| 143 | + rows = [] |
| 144 | + for project in projects: |
| 145 | + for session in project.sessions: |
| 146 | + rows.append(session) |
| 147 | + return rows |
| 148 | + |
| 149 | + |
| 150 | +def _truncate(text: str, length: int) -> str: |
| 151 | + if not text: |
| 152 | + return "-" |
| 153 | + text = text.replace("\n", " ").strip() |
| 154 | + if len(text) <= length: |
| 155 | + return text |
| 156 | + return text[: length - 1] + "…" |
| 157 | + |
| 158 | + |
| 159 | +def _format_table(headers: list[str], rows: list[list[str]]) -> str: |
| 160 | + widths = [len(h) for h in headers] |
| 161 | + for row in rows: |
| 162 | + for i, cell in enumerate(row): |
| 163 | + widths[i] = max(widths[i], len(cell)) |
| 164 | + |
| 165 | + def line(cells: list[str]) -> str: |
| 166 | + return " ".join(cell.ljust(widths[i]) for i, cell in enumerate(cells)) |
| 167 | + |
| 168 | + sep = " ".join("-" * w for w in widths) |
| 169 | + return "\n".join([line(headers), sep, *[line(r) for r in rows]]) |
| 170 | + |
| 171 | + |
| 172 | +if __name__ == "__main__": |
| 173 | + main() |
0 commit comments