Repository navigation
Expand file tree
/
Copy pathcli.py
More file actions
2689 lines (2444 loc) · 103 KB
/
Copy pathcli.py
File metadata and controls
2689 lines (2444 loc) · 103 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""CLI interface for claude-code-log."""
import faulthandler
import logging
import os
import signal
import sqlite3
import sys
import threading
import time
import traceback
from pathlib import Path
from typing import Any, Callable, Optional
import click
from git import Repo, InvalidGitRepositoryError
from .watch import (
DEFAULT_MAX_LATENCY,
DEFAULT_POLL_INTERVAL,
DEFAULT_QUIET_PERIOD,
)
from .converter import (
RegenerationReport,
convert_jsonl_to,
convert_jsonl_to_html,
ensure_fresh_cache,
generate_single_session_file,
render_normalized_session_file,
render_provider_wholesale,
get_file_extension,
get_index_filename,
process_projects_hierarchy,
)
from .cache import (
CacheManager,
find_session_in_cache,
get_all_cached_projects,
get_cache_db_path,
get_library_version,
is_corrupt_database_error,
)
from .migrations.runner import apply_write_pragmas
from .models import RenderingDepth
from .render_pool import resolve_render_jobs
from .search import (
ENV_INDEX_FIELDS,
ENV_SEARCH_FIELDS,
SEARCH_FIELDS,
)
from .utils import (
DEFAULT_THEME,
THEME_CHOICES,
THEME_ENV_VAR,
normalize_theme,
)
# `--theme` is shared by `convert`, `serve` and `watch`. No Click default and
# no Click `envvar`: `_resolve_theme` applies the precedence itself (flag >
# $CLAUDE_CODE_LOG_THEME > built-in default) so a bad environment value gets
# an error that names the variable rather than a confusing "--theme" one.
THEME_HELP = (
"HTML theme: classic (current look), minimal, or default (the built-in "
f"default, currently {DEFAULT_THEME}). Overrides ${THEME_ENV_VAR}. "
"HTML-only. Themes write the same filenames, so switching theme "
"regenerates every output."
)
def _theme_option(func: Any) -> Any:
return click.option(
"--theme",
type=click.Choice(THEME_CHOICES, case_sensitive=False),
default=None,
help=THEME_HELP,
)(func)
def _resolve_theme(theme: Optional[str]) -> str:
"""Resolve the HTML theme: ``--theme`` > ``$CLAUDE_CODE_LOG_THEME`` > default.
Returns a resolved name (``classic``/``minimal``, never ``default``).
An explicit ``--theme`` (``default`` included) always wins over the
environment; an unknown environment value is an error, not a silent
fallback. An empty variable counts as unset.
"""
if theme is not None:
return normalize_theme(theme)
raw = os.environ.get(THEME_ENV_VAR, "")
if not raw.strip():
return DEFAULT_THEME
try:
return normalize_theme(raw)
except ValueError:
raise click.UsageError(
f"{THEME_ENV_VAR}={raw!r} is not a valid theme; choose one of: "
f"classic (current look), minimal, or default (the built-in "
f"default, currently {DEFAULT_THEME})."
) from None
# Output values that mean "stream the rendered document to stdout" (issue
# #223): write the document to stdout, always regenerate, never consult or
# write the cache, never open a browser, and keep status text off stdout
# (it goes to stderr) so the stream carries only the rendered document.
_STDOUT_TARGETS = {"-", "/dev/stdout"}
def _is_stdout_target(output: "Optional[Path]") -> bool:
"""Whether ``--output`` requests a stdout stream (``-`` or /dev/stdout)."""
return output is not None and str(output) in _STDOUT_TARGETS
def _render_to_stdout(
input_path: Path, render_to_temp: "Callable[[Path], Path]"
) -> None:
"""Render to a throwaway temp file, then stream it to stdout (issue #223).
The temp file lets the full conversion pipeline run unchanged; we then
copy its raw bytes to stdout and discard the temp dir. ``render_to_temp``
receives the temp directory and returns the written file path. The
rendered document is the only thing written to stdout; a confirmation
goes to stderr so the stream stays clean for piping.
"""
import contextlib
import io
import shutil
import tempfile
tmpdir = Path(tempfile.mkdtemp(prefix="ccl-stream-"))
# Capture anything the render prints to stdout (e.g. the per-file
# "Processing ..." progress, which generate_single_session_file emits
# without a silent switch) so it can't pollute the document stream;
# forward it to stderr instead.
captured = io.StringIO()
try:
with contextlib.redirect_stdout(captured):
written = render_to_temp(tmpdir)
# Read/write RAW BYTES: the document is UTF-8 (transcripts are
# emoji-heavy), but stdout's text encoding follows the locale and may
# not be UTF-8 — decoding then re-encoding via sys.stdout.write would
# mangle or raise on those characters. Pass the bytes through verbatim.
content = Path(written).read_bytes()
finally:
shutil.rmtree(tmpdir, ignore_errors=True)
progress = captured.getvalue()
if progress:
click.echo(progress, nl=False, err=True)
stdout_buffer = getattr(sys.stdout, "buffer", None)
if stdout_buffer is not None:
stdout_buffer.write(content)
stdout_buffer.flush()
else:
# Fallback (e.g. a text-only stdout shim): decode best-effort.
sys.stdout.write(content.decode("utf-8", errors="replace"))
click.echo(f"Successfully converted {input_path} to stdout", err=True)
def _render_provider_input_file(
provider_name: str,
input_path: Path,
output: "Optional[Path]",
output_format: str,
image_export_mode: "Optional[str]",
depth: RenderingDepth,
compact: bool,
no_timestamps: bool,
no_recaps: bool,
open_browser: bool,
theme: str = DEFAULT_THEME,
) -> None:
"""Render a single provider session file handed in as an INPUT_PATH.
Shared by the explicit ``--provider <p> <file>`` path and the no-flag
auto-detected-rollout path. Fails LOUDLY if a provider claimed the file but
it yields no renderable messages, so a rollout can never fall through to a
near-empty page (the silent-empty gap).
"""
from .providers import discover_providers
from .utils import output_path_is_file
# A directory INPUT_PATH is a mini sessions root and is routed to the
# wholesale walker by the dispatcher before it reaches here, so this helper
# only ever sees a single rollout file.
selected = discover_providers().get_provider(provider_name)
if selected is None:
raise click.UsageError(f"Unknown provider: {provider_name}")
messages = list(selected.load_session_from_path(input_path))
if not messages:
raise click.UsageError(
f"{input_path} was detected as a {provider_name} session but produced "
"no renderable messages; it may be truncated or malformed."
)
# generate_session filters entries by sessionId, so the render key MUST be
# the session's own id (the thread id carried on the entries), not the
# filename stem — a mismatch silently drops every message (the empty-page bug).
session_key = messages[0].sessionId or input_path.stem
title = f"{provider_name.title()}: {session_key}"
def render(destination: Path) -> Path:
return render_normalized_session_file(
messages,
session_key,
destination,
output_format,
title,
image_export_mode,
depth,
compact,
no_timestamps,
no_recaps,
theme=theme,
)
extension = get_file_extension(output_format)
if _is_stdout_target(output):
_render_to_stdout(
input_path,
lambda tmpdir: render(tmpdir / f"session.{extension}"),
)
return
filename = f"session-{session_key}.{extension}"
if output is None:
destination = Path.cwd() / filename
elif output_path_is_file(output):
destination = output
else:
destination = output / filename
output_path = render(destination)
click.echo(f"Successfully rendered {provider_name} session to {output_path}")
if open_browser:
click.launch(str(output_path))
def _resolve_provider_output_root(provider_name: str, output: "Optional[Path]") -> Path:
"""Resolve where a provider wholesale run writes its project hierarchy.
An explicit ``-o DIR`` wins (a file-shaped ``-o`` is rejected — wholesale
writes many files). Otherwise the default is ``<provider_home>/claude-code-log/``
(DECIDED #4: the sessions tree stays pristine, so output never lands inside
it). If the provider has no discoverable home, there is nowhere to default
to — fail loudly asking for ``-o``.
"""
from .providers import discover_providers
from .utils import output_path_is_file
if output is not None:
if output_path_is_file(output):
raise click.UsageError(
f"provider wholesale rendering writes many files; pass -o as a "
f"directory, not a file ({output})."
)
return output
provider = discover_providers().get_provider(provider_name)
data_dir = provider.get_data_dir() if provider is not None else None
if data_dir is None:
raise click.UsageError(
f"no {provider_name} home found to place output; pass -o DIR to "
"choose an output directory."
)
return data_dir / "claude-code-log"
def _run_provider_wholesale(
provider_name: str,
sessions_root: "Optional[Path]",
output: "Optional[Path]",
output_format: str,
image_export_mode: "Optional[str]",
depth: RenderingDepth,
compact: bool,
no_timestamps: bool,
no_recaps: bool,
write_combined: bool,
write_individual: bool,
from_date: "Optional[str]",
to_date: "Optional[str]",
no_cache: bool,
clear_cache: bool,
clear_output: bool,
open_browser: bool,
expand_paths: bool,
filter_path: "Optional[str]",
theme: str = DEFAULT_THEME,
) -> None:
"""Render a whole provider sessions tree into a project hierarchy.
``sessions_root`` None walks the provider's own data dir; a directory
(an INPUT_PATH dir, or ``--projects-dir``) selects a mini sessions root.
``--clear-cache`` / ``--clear-output`` are scoped to the provider output
root so the pristine sessions tree is never touched (DECIDED #4). Mirroring
the Claude path, they clear-and-exit on their own, but when a date filter is
also given they clear then fall through to REGENERATE the filtered view
(else ``--clear-output --from-date`` would leave an empty directory).
"""
output_root = _resolve_provider_output_root(provider_name, output)
dated = from_date is not None or to_date is not None
if clear_cache:
_clear_provider_cache(output_root)
if not dated:
return
if clear_output:
_clear_provider_output(output_root, output_format)
if not dated:
return
index_path = render_provider_wholesale(
provider_name,
sessions_root,
output_root,
from_date=from_date,
to_date=to_date,
output_format=output_format,
image_export_mode=image_export_mode,
depth=depth,
compact=compact,
no_timestamps=no_timestamps,
no_recaps=no_recaps,
theme=theme,
write_combined=write_combined,
write_individual=write_individual,
use_cache=not no_cache,
expand_paths=expand_paths,
filter_path=filter_path,
silent=False,
)
if open_browser:
click.launch(str(index_path))
def _clear_provider_cache(output_root: Path) -> None:
"""Delete the provider wholesale cache DB (and its WAL/SHM sidecars) under
the output root. Never touches the sessions tree — the DB lives beside the
generated output, not inside the sources."""
from .cache import get_cache_db_path
db = get_cache_db_path(output_root)
removed = False
for path in (db, db.with_name(db.name + "-wal"), db.with_name(db.name + "-shm")):
if path.exists():
try:
path.unlink()
removed = True
except OSError as exc:
click.echo(f" Warning: failed to delete {path}: {exc}")
click.echo(
f"Cleared provider cache database: {db}"
if removed
else f"No provider cache database at {db}."
)
def _clear_provider_output(output_root: Path, output_format: str) -> None:
"""Remove generated output files under the provider output root only.
Scoped by known generated filenames (index + per-project
``combined_transcripts*`` / ``session-*``), so unrelated files — and every
file in the sessions tree, which lives elsewhere — are left untouched."""
file_ext = get_file_extension(output_format)
removed = 0
if output_root.is_dir():
index_file = output_root / get_index_filename(output_format)
if index_file.exists():
index_file.unlink()
removed += 1
for project_dir in output_root.iterdir():
if not project_dir.is_dir():
continue
for generated in _list_generated_outputs(project_dir, file_ext):
generated.unlink()
removed += 1
click.echo(
f"Cleared {removed} generated {file_ext.upper()} file(s) under {output_root}."
)
def _install_stack_dump_signal() -> None:
"""Make ``kill -USR1 <pid>`` print the live Python stack to stderr.
Useful for diagnosing apparent hangs without killing the process —
py-spy needs root on macOS, but this only needs the signal. SIGUSR1
is POSIX-only; on Windows we silently skip.
"""
sigusr1 = getattr(signal, "SIGUSR1", None)
if sigusr1 is None:
return
try:
faulthandler.register(sigusr1, all_threads=True, chain=False) # ty: ignore[possibly-missing-attribute]
except (RuntimeError, ValueError, OSError):
# E.g. signal already taken, no-tty environments, or platforms
# where faulthandler.register raises. Diagnostics shouldn't
# break the CLI — silently skip.
pass
def get_default_projects_dir() -> Path:
"""Get the default Claude projects directory path."""
return Path.home() / ".claude" / "projects"
def _discover_projects(
projects_dir: Path,
) -> tuple[list[Path], set[Path]]:
"""Discover active and archived projects in the projects directory.
Returns:
Tuple of (all_project_dirs, archived_projects_set)
"""
# Find active projects (directories with JSONL files)
project_dirs = [
d for d in projects_dir.iterdir() if d.is_dir() and list(d.glob("*.jsonl"))
]
# Find archived projects (in cache but without JSONL files)
archived_projects: set[Path] = set()
cached_projects = get_all_cached_projects(projects_dir)
active_project_paths = {str(p) for p in project_dirs}
for project_path_str, is_archived in cached_projects:
if is_archived and project_path_str not in active_project_paths:
archived_path = Path(project_path_str)
archived_projects.add(archived_path)
project_dirs.append(archived_path)
return project_dirs, archived_projects
def _launch_tui_with_cache_check(
project_path: Path, is_archived: bool = False, theme: str = DEFAULT_THEME
) -> Optional[str]:
"""Launch TUI with proper cache checking and user feedback."""
click.echo("Checking cache and loading session data...")
# Check if we need to rebuild cache
cache_manager = CacheManager(project_path, get_library_version())
project_cache = cache_manager.get_cached_project_data()
if is_archived:
# Archived projects have no JSONL files, just load from cache
if project_cache and project_cache.sessions:
click.echo(
f"[ARCHIVED] Found {len(project_cache.sessions)} sessions in cache. Launching TUI..."
)
else:
click.echo("Error: No cached sessions found for archived project", err=True)
return None
else:
jsonl_files = list(project_path.glob("*.jsonl"))
modified_files = cache_manager.get_modified_files(jsonl_files)
if not (project_cache and project_cache.sessions and not modified_files):
# Need to rebuild cache
if modified_files:
click.echo(
f"Found {len(modified_files)} modified files, rebuilding cache..."
)
else:
click.echo("Building session cache...")
# Pre-build the cache before launching TUI (no HTML generation)
try:
ensure_fresh_cache(project_path, cache_manager, silent=True)
click.echo("Cache ready! Launching TUI...")
except Exception as e:
click.echo(f"Error building cache: {e}", err=True)
return None
else:
click.echo(
f"Cache up to date. Found {len(project_cache.sessions)} sessions. Launching TUI..."
)
# Small delay to let user see the message before TUI clears screen
import time
time.sleep(0.5)
from .tui import run_session_browser
result = run_session_browser(project_path, is_archived=is_archived, theme=theme)
return result
def convert_project_path_to_claude_dir(
input_path: Path, base_projects_dir: Optional[Path] = None
) -> Path:
"""Convert a project path to the corresponding directory in ~/.claude/projects/.
Args:
input_path: The project path to convert
base_projects_dir: Optional base directory for Claude projects.
Defaults to ~/.claude/projects/
"""
# Get the real path to resolve any symlinks
real_path = input_path.resolve()
# Convert the path to the expected format: replace slashes with hyphens
path_parts = list(real_path.parts)
# Handle platform-specific root components
if path_parts[0] == "/":
# Unix: Remove leading slash, then prepend with dash
# e.g., ['/', 'Users', 'test'] -> ['Users', 'test'] -> '-Users-test'
path_parts = path_parts[1:]
claude_project_name = "-" + "-".join(path_parts)
elif len(path_parts) > 0 and len(path_parts[0]) >= 2 and path_parts[0][1:2] == ":":
# Windows: Strip backslash and colon from drive letter, keep empty string for double dash
# e.g., ['E:\\', 'Workspace', 'src'] -> ['E', '', 'Workspace', 'src'] -> 'E--Workspace-src'
path_parts[0] = path_parts[0].rstrip("\\").rstrip(":")
path_parts.insert(
1, ""
) # Insert empty string to create double dash after drive letter
claude_project_name = "-".join(path_parts)
else:
# Fallback for other cases
claude_project_name = "-" + "-".join(path_parts)
# Construct the path in the projects directory
projects_dir = base_projects_dir or get_default_projects_dir()
claude_projects_dir = projects_dir / claude_project_name
return claude_projects_dir
def find_projects_by_cwd(
projects_dir: Path, current_cwd: Optional[str] = None
) -> list[Path]:
"""Find Claude projects that match the current working directory.
Uses three-tier priority matching:
1. Exact match to current working directory
2. Git repository root match
3. Relative path matching
"""
if current_cwd is None:
current_cwd = os.getcwd()
# Normalize the current working directory
current_cwd_path = Path(current_cwd).resolve()
# Check all project directories
if not projects_dir.exists():
return []
# Get all valid project directories
project_dirs = [
d for d in projects_dir.iterdir() if d.is_dir() and list(d.glob("*.jsonl"))
]
# Tier 1: Check for exact match to current working directory
exact_matches = _find_exact_matches(project_dirs, current_cwd_path, projects_dir)
if exact_matches:
return exact_matches
# Tier 2: Check if we're inside a git repo and match to repo root
git_root_matches = _find_git_root_matches(
project_dirs, current_cwd_path, projects_dir
)
if git_root_matches:
return git_root_matches
# Tier 3: Fall back to relative path matching
return _find_relative_matches(project_dirs, current_cwd_path)
def _find_exact_matches(
project_dirs: list[Path], current_cwd_path: Path, base_projects_dir: Path
) -> list[Path]:
"""Find projects with exact working directory matches using path-based matching."""
expected_project_dir = convert_project_path_to_claude_dir(
current_cwd_path, base_projects_dir
)
for project_dir in project_dirs:
if project_dir == expected_project_dir:
return [project_dir]
return []
def _find_git_root_matches(
project_dirs: list[Path], current_cwd_path: Path, base_projects_dir: Path
) -> list[Path]:
"""Find projects that match the git repository root using path-based matching."""
try:
# Check if we're inside a git repository
repo = Repo(current_cwd_path, search_parent_directories=True)
git_root_path = Path(repo.git_dir).parent.resolve()
# Find projects that match the git root
return _find_exact_matches(project_dirs, git_root_path, base_projects_dir)
except InvalidGitRepositoryError:
# Not in a git repository
return []
except Exception:
# Other git-related errors
return []
def _find_relative_matches(
project_dirs: list[Path], current_cwd_path: Path
) -> list[Path]:
"""Find projects using relative path matching (original behavior)."""
relative_matches: list[Path] = []
for project_dir in project_dirs:
try:
# Load cache to check for working directories
cache_manager = CacheManager(project_dir, get_library_version())
working_directories = cache_manager.get_working_directories()
# Build cache if needed
if not working_directories:
jsonl_files = list(project_dir.glob("*.jsonl"))
if jsonl_files:
try:
convert_jsonl_to_html(project_dir, silent=True)
working_directories = cache_manager.get_working_directories()
except Exception as e:
logging.warning(
f"Failed to build cache for project {project_dir.name}: {e}"
)
if working_directories:
# Check for relative matches
for cwd in working_directories:
cwd_path = Path(cwd).resolve()
if current_cwd_path.is_relative_to(cwd_path):
relative_matches.append(project_dir)
break
else:
# Fall back to path name matching if no cache data
project_name = project_dir.name
reconstructed_path = None
if project_name.startswith("-"):
# Unix path: -Users-test-workspace
path_parts = project_name[1:].split("-")
if path_parts:
reconstructed_path = Path("/") / Path(*path_parts)
elif len(project_name) >= 1 and not project_name.startswith("-"):
# Windows path: C--Users-test or E--Workspace-src
path_parts = project_name.split("-")
if (
len(path_parts) >= 2
and len(path_parts[0]) == 1
and path_parts[1] == ""
):
# Drive letter detected (e.g., ['C', '', 'Users', ...])
drive = path_parts[0] + ":\\"
remaining_parts = [
p for p in path_parts[2:] if p
] # Skip drive and empty string
if remaining_parts:
reconstructed_path = Path(drive) / Path(*remaining_parts)
else:
reconstructed_path = Path(drive)
if reconstructed_path and (
current_cwd_path == reconstructed_path
or current_cwd_path.is_relative_to(reconstructed_path)
or reconstructed_path.is_relative_to(current_cwd_path)
):
relative_matches.append(project_dir)
except Exception:
continue
return relative_matches
def _clear_caches(input_path: Path, all_projects: bool) -> None:
"""Clear cache directories for the specified path."""
try:
library_version = get_library_version()
if all_projects:
# Clear cache for all project directories
click.echo("Clearing caches for all projects...")
# Delete the SQLite cache database (respects CLAUDE_CODE_LOG_CACHE_PATH env var)
cache_db = get_cache_db_path(input_path)
if cache_db.exists():
try:
cache_db.unlink()
click.echo(f" Deleted SQLite cache database: {cache_db}")
except Exception as e:
click.echo(f" Warning: Failed to delete cache database: {e}")
# Also clean up old JSON cache directories (migration cleanup)
project_dirs = [
d
for d in input_path.iterdir()
if d.is_dir() and list(d.glob("*.jsonl"))
]
for project_dir in project_dirs:
try:
# Clean up old JSON cache directory if it exists
old_cache_dir = project_dir / "cache"
if old_cache_dir.exists():
import shutil
shutil.rmtree(old_cache_dir)
click.echo(f" Cleared old JSON cache for {project_dir.name}")
except Exception as e:
click.echo(
f" Warning: Failed to clear old cache for {project_dir.name}: {e}"
)
elif input_path.is_dir():
# Clear cache for single directory
click.echo(f"Clearing cache for {input_path}...")
cache_manager = CacheManager(input_path, library_version)
cache_manager.clear_cache()
# Also clean up old JSON cache directory if it exists
old_cache_dir = input_path / "cache"
if old_cache_dir.exists():
import shutil
shutil.rmtree(old_cache_dir)
click.echo(" Cleared old JSON cache directory")
else:
# Single file - no cache to clear
click.echo("Cache clearing not applicable for single files.")
except Exception as e:
click.echo(f"Warning: Failed to clear cache: {e}")
def _list_generated_outputs(directory: Path, file_ext: str) -> list[Path]:
"""Return only files this tool generates, not every file with the extension.
Safe for JSON in particular, where the project directory may contain
unrelated user `.json` files that must not be deleted.
"""
if file_ext == "json":
return [
*directory.glob("combined_transcripts*.json"),
*directory.glob("session-*.json"),
]
return list(directory.glob(f"*.{file_ext}"))
def _clear_output_files(
input_path: Path, all_projects: bool, output_format: str
) -> None:
"""Clear generated output files (HTML/Markdown/JSON) for the specified path."""
file_ext = get_file_extension(output_format)
ext_upper = file_ext.upper()
try:
if all_projects:
# Clear output files for all project directories
click.echo(f"Clearing {ext_upper} files for all projects...")
project_dirs = [
d
for d in input_path.iterdir()
if d.is_dir() and list(d.glob("*.jsonl"))
]
total_removed = 0
for project_dir in project_dirs:
try:
# Remove output files in project directory
output_files = _list_generated_outputs(project_dir, file_ext)
for output_file in output_files:
output_file.unlink()
total_removed += 1
if output_files:
click.echo(
f" Removed {len(output_files)} {ext_upper} files from {project_dir.name}"
)
except Exception as e:
click.echo(
f" Warning: Failed to clear {ext_upper} files for {project_dir.name}: {e}"
)
# Also remove top-level index file (shared helper keeps this in
# sync with the generator, which uses a different name for JSON).
index_filename = get_index_filename(output_format)
index_file = input_path / index_filename
if index_file.exists():
index_file.unlink()
total_removed += 1
click.echo(f" Removed top-level {index_filename}")
if total_removed > 0:
click.echo(f"Total: Removed {total_removed} {ext_upper} files")
else:
click.echo(f"No {ext_upper} files found to remove")
elif input_path.is_dir():
# Clear output files for single directory
click.echo(f"Clearing {ext_upper} files for {input_path}...")
output_files = _list_generated_outputs(input_path, file_ext)
for output_file in output_files:
output_file.unlink()
if output_files:
click.echo(f"Removed {len(output_files)} {ext_upper} files")
else:
click.echo(f"No {ext_upper} files found to remove")
else:
# Single file - remove corresponding output file
output_file = input_path.with_suffix(f".{file_ext}")
if output_file.exists():
output_file.unlink()
click.echo(f"Removed {output_file}")
else:
click.echo(f"No corresponding {ext_upper} file found to remove")
except Exception as e:
click.echo(f"Warning: Failed to clear {ext_upper} files: {e}")
# Placeholders accepted by ``--git-link`` templates. Mirrors
# ``resolve_sha`` in claude_code_log.git_remote — keep in sync.
_GIT_LINK_ALLOWED_PLACEHOLDERS = frozenset({"host", "path", "sha"})
def _validate_git_link_template(template: str) -> None:
"""Validate a ``--git-link`` template eagerly; raise ``click.UsageError`` on issues.
Two checks:
1. ``{sha}`` must be present (it's the only mandatory field —
the resolver's whole job is to substitute the commit SHA).
2. All placeholders must be in ``_GIT_LINK_ALLOWED_PLACEHOLDERS``.
Catches typos like ``{hsot}`` before they reach
``template.format()`` (which would raise ``KeyError`` at
render time). The resolver has a try/except guarding the
env-var-only path; this validator is the loud-error path for
CLI users.
Uses ``string.Formatter().parse()`` rather than regex so the
same parser Python uses for ``str.format`` decides what counts
as a placeholder.
"""
import string
parsed_fields = [
field
for _, field, _, _ in string.Formatter().parse(template)
if field is not None
]
if "" in parsed_fields:
raise click.UsageError(
"--git-link template uses an anonymous positional placeholder ({}). "
"Use a named placeholder ({host}, {path}, or {sha}) instead "
f"(got: {template!r})."
)
fields = set(parsed_fields)
unknown = fields - _GIT_LINK_ALLOWED_PLACEHOLDERS
if unknown:
raise click.UsageError(
f"--git-link template uses unknown placeholder(s): "
f"{', '.join('{' + f + '}' for f in sorted(unknown))}. "
f"Allowed: {{host}}, {{path}}, {{sha}}."
)
if "sha" not in fields:
raise click.UsageError(
"--git-link template must contain a {sha} placeholder "
f"(got: {template!r}). Example: "
"'https://{host}/{path}/-/commit/{sha}'."
)
class DefaultCommandGroup(click.Group):
"""A group that falls back to a default subcommand.
The CLI was a single flat command for its whole life, so
``claude-code-log``, ``claude-code-log some/file.jsonl`` and
``claude-code-log --from-date yesterday`` all have to keep working
unchanged. Anything whose first argument isn't a registered subcommand
is therefore rewritten as ``<default_command> <args...>``.
A path that collides with a subcommand name can be forced through with
``--``: ``claude-code-log -- serve``.
"""
default_command = "convert"
def parse_args(self, ctx: click.Context, args: list[str]) -> list[str]:
if args and args[0] == "--":
# Explicit escape hatch: everything after `--` is the default
# command's arguments, even if it looks like a subcommand name.
args = [self.default_command] + args[1:]
elif not args or args[0] not in self.commands:
# No args at all, an INPUT_PATH, or an option like --help /
# --version / --from-date: all belong to the default command.
# Sending --help there is deliberate — it keeps the familiar
# full option list, and `convert`'s epilog advertises the
# subcommands (see _default_command_epilog).
args = [self.default_command] + args
return super().parse_args(ctx, args)
def _subcommand_epilog(group: click.Group) -> str:
"""Build the default command's epilog from what's actually registered.
The group's own help is unreachable (``parse_args`` always rewrites to a
subcommand), so the subcommand list has to appear in the default
command's ``--help`` or subcommands would be undiscoverable. Deriving it
from ``group.commands`` keeps it from advertising commands that don't
exist. Called at the bottom of the module, once everything is registered.
"""
others = [
(name, cmd)
for name, cmd in sorted(group.commands.items())
if name != DefaultCommandGroup.default_command
]
if not others:
return ""
width = max(len(name) for name, _ in others)
# The leading \b stops Click's formatter rewrapping the block, so the
# command list keeps its alignment.
lines = ["\b", "Subcommands:"]
lines += [
f" {name:<{width}} {(cmd.short_help or cmd.help or '').splitlines()[0]}"
for name, cmd in others
]
lines += [
"",
"Run 'claude-code-log <subcommand> --help' for its options. Any "
"other invocation runs the conversion described above.",
]
return "\n".join(lines)
@click.group(cls=DefaultCommandGroup)
@click.version_option(version=get_library_version(), prog_name="claude-code-log")
def main() -> None:
"""Convert Claude transcript JSONL files to HTML or Markdown."""
@main.command(name="convert")
@click.version_option(version=get_library_version(), prog_name="claude-code-log")
@click.argument("input_path", type=click.Path(path_type=Path), required=False)
@click.option(
"-o",
"--output",
type=click.Path(path_type=Path),
help=(
"Output destination. Use '-' (or /dev/stdout) to stream the "
"rendered document to stdout (status goes to stderr) for piping. "
"With a recognised file suffix (.html/.md/.markdown/.json) treated "
"as a single output file; otherwise treated as a directory root "
"(and now also honoured for --all-projects, where outputs land at "
"<output>/<project>/...). Pair with --expand-paths to project "
"back to the real on-disk tree."
),
)
@click.option(
"--expand-paths",
is_flag=True,
help=(
"When set with --output and --all-projects, expand each "
"project's flat encoded dir name (e.g. '-home-joe-project-A') "
"back to its real path under <output>/. Resolves the encoded "
"name via the cache's recorded `cwd`, falling back to a peek "
"of the first JSONL when the cache is empty. Useful for "
"projecting transcripts into Obsidian-style Markdown vaults."
),
)
@click.option(
"--filter-path",
type=str,
default=None,
help=(
"Restrict --all-projects to projects matching a path prefix. "
"With --expand-paths, the prefix is matched against the "
"expanded real path AND truncated from the destination "
"(`/home/joe/project/A` with --filter-path /home/joe lands at "
"<output>/project/A/). Without --expand-paths, matches the "
"flat encoded dir name (e.g. '-home-joe' selects projects "
"starting with '-home-joe-')."
),
)
@click.option(
"--open-browser",
is_flag=True,
help="Open the generated HTML file in the default browser",
)
@click.option(
"--from-date",
type=str,
help='Filter messages from this date/time (e.g., "2 hours ago", "yesterday", "2025-06-08")',
)
@click.option(
"--to-date",
type=str,
help='Filter messages up to this date/time (e.g., "1 hour ago", "today", "2025-06-08 15:00")',
)
@click.option(
"--all-projects",
is_flag=True,
help="Process all projects in ~/.claude/projects/ hierarchy and create linked HTML files",