git-vidi 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
vidi/data.py ADDED
@@ -0,0 +1,266 @@
1
+ """Data processing helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import collections
6
+ import datetime as dt
7
+
8
+ from .models import CommitFileChange, CommitPatchSection, CommitRecord
9
+ from .utils import truncate_middle, unquote_git_path, utc_now
10
+
11
+
12
+ RANGE_PRESETS = [
13
+ ("All time", "all"),
14
+ ("1 year", "365"),
15
+ ("90 days", "90"),
16
+ ("30 days", "30"),
17
+ ("7 days", "7"),
18
+ ]
19
+
20
+ def filter_commits(
21
+ commits: list[CommitRecord],
22
+ range_value: str,
23
+ selected_year: int | None,
24
+ *,
25
+ now: dt.datetime | None = None,
26
+ ) -> list[CommitRecord]:
27
+ filtered = commits
28
+ if range_value != "all" and filtered:
29
+ days = int(range_value)
30
+ window_end = utc_now() if now is None else now
31
+ cutoff = window_end - dt.timedelta(days=days)
32
+ filtered = [item for item in filtered if item.authored_at >= cutoff]
33
+ if selected_year is not None:
34
+ filtered = [item for item in filtered if item.authored_date.year == selected_year]
35
+ return filtered
36
+
37
+
38
+ def resolve_graph_window(
39
+ range_value: str,
40
+ year: int,
41
+ *,
42
+ now: dt.datetime | None = None,
43
+ ) -> tuple[dt.date, dt.date]:
44
+ year_start = dt.date(year, 1, 1)
45
+ year_end = dt.date(year, 12, 31)
46
+ if range_value == "all":
47
+ return year_start, year_end
48
+
49
+ # The viewer's local date. A naive `now` is taken as local time.
50
+ today = (utc_now() if now is None else now).astimezone().date()
51
+ if year != today.year:
52
+ return year_start, year_end
53
+
54
+ days = int(range_value)
55
+ window_end = min(today, year_end)
56
+ window_start = max(year_start, window_end - dt.timedelta(days=max(days - 1, 0)))
57
+ return window_start, window_end
58
+
59
+
60
+ def build_date_grid(
61
+ commit_counts: collections.Counter[dt.date],
62
+ start: dt.date,
63
+ end: dt.date,
64
+ ) -> tuple[list[list[int | None]], list[str], dt.date]:
65
+ days_to_prev_sunday = (start.weekday() + 1) % 7
66
+ first_sunday = start - dt.timedelta(days=days_to_prev_sunday)
67
+ row_for_end = (end.weekday() + 1) % 7
68
+ last_day = end + dt.timedelta(days=6 - row_for_end)
69
+ total_days = (last_day - first_sunday).days + 1
70
+ num_weeks = (total_days + 6) // 7
71
+ grid: list[list[int | None]] = [[None for _ in range(num_weeks)] for _ in range(7)]
72
+ month_labels = [" " for _ in range(num_weeks)]
73
+ previous_visible_month: int | None = None
74
+
75
+ for col in range(num_weeks):
76
+ week_start = first_sunday + dt.timedelta(days=col * 7)
77
+ visible_days: list[dt.date] = []
78
+ for row in range(7):
79
+ day = week_start + dt.timedelta(days=row)
80
+ if start <= day <= end:
81
+ grid[row][col] = commit_counts.get(day, 0)
82
+ visible_days.append(day)
83
+ if visible_days:
84
+ first_visible_day = visible_days[0]
85
+ if first_visible_day.month != previous_visible_month:
86
+ month_labels[col] = first_visible_day.strftime("%b")
87
+ previous_visible_month = first_visible_day.month
88
+ return grid, month_labels, first_sunday
89
+
90
+
91
+ def parse_patch_sections(patch_text: str) -> tuple[CommitPatchSection, ...]:
92
+ sections: list[CommitPatchSection] = []
93
+ if not patch_text.strip():
94
+ return tuple(sections)
95
+
96
+ current: list[str] = []
97
+ for raw in patch_text.splitlines():
98
+ if raw.startswith("diff --git ") and current:
99
+ sections.append(_build_patch_section(current))
100
+ current = [raw]
101
+ else:
102
+ current.append(raw)
103
+ if current:
104
+ sections.append(_build_patch_section(current))
105
+ return tuple(sections)
106
+
107
+
108
+ def _build_patch_section(lines: list[str]) -> CommitPatchSection:
109
+ old_path = ""
110
+ new_path = ""
111
+ is_binary = any("Binary files " in line for line in lines)
112
+ is_rename = False
113
+
114
+ for line in lines:
115
+ if line.startswith("@@"):
116
+ break
117
+ if line.startswith("rename from "):
118
+ old_path = unquote_git_path(line.removeprefix("rename from "))
119
+ is_rename = True
120
+ elif line.startswith("rename to "):
121
+ new_path = unquote_git_path(line.removeprefix("rename to "))
122
+ is_rename = True
123
+ elif line.startswith("--- "):
124
+ candidate = unquote_git_path(line[4:].rstrip("\t"))
125
+ if candidate != "/dev/null":
126
+ old_path = candidate.removeprefix("a/")
127
+ elif line.startswith("+++ "):
128
+ candidate = unquote_git_path(line[4:].rstrip("\t"))
129
+ if candidate != "/dev/null":
130
+ new_path = candidate.removeprefix("b/")
131
+
132
+ if not old_path or not new_path:
133
+ header = next((line for line in lines if line.startswith("diff --git ")), "")
134
+ header_old, header_new = _diff_header_paths(header.removeprefix("diff --git "))
135
+ if not old_path:
136
+ old_path = header_old
137
+ if not new_path:
138
+ new_path = header_new
139
+
140
+ path = new_path or old_path or "unknown"
141
+ return CommitPatchSection(
142
+ path=path,
143
+ old_path=old_path or path,
144
+ new_path=new_path or path,
145
+ patch="\n".join(lines).rstrip(),
146
+ is_binary=is_binary,
147
+ is_rename=is_rename or ((old_path or path) != (new_path or path)),
148
+ )
149
+
150
+
151
+ def _diff_header_paths(rest: str) -> tuple[str, str]:
152
+ """The old and new paths of a `diff --git` header after its prefix.
153
+
154
+ A header without `---` and `+++` lines names the same file on both sides.
155
+ It is split at its middle space when both halves match.
156
+ """
157
+ middle = len(rest) // 2
158
+ if rest[middle : middle + 1] == " ":
159
+ old = unquote_git_path(rest[:middle]).removeprefix("a/")
160
+ new = unquote_git_path(rest[middle + 1 :]).removeprefix("b/")
161
+ if old == new:
162
+ return old, new
163
+ old, _, new = rest.partition(" ")
164
+ return unquote_git_path(old).removeprefix("a/"), unquote_git_path(new).removeprefix("b/")
165
+
166
+
167
+ def section_for_change(
168
+ sections: tuple[CommitPatchSection, ...],
169
+ index: int,
170
+ change: CommitFileChange,
171
+ ) -> CommitPatchSection | None:
172
+ """Find the patch section for a file change.
173
+
174
+ Prefers the section at the same index and falls back to a path match.
175
+ """
176
+ if 0 <= index < len(sections):
177
+ candidate = sections[index]
178
+ if candidate.path == change.path or candidate.new_path == change.path:
179
+ return candidate
180
+ return next(
181
+ (
182
+ section
183
+ for section in sections
184
+ if section.path == change.path or section.new_path == change.path
185
+ ),
186
+ None,
187
+ )
188
+
189
+
190
+ def _is_binary(change: CommitFileChange) -> bool:
191
+ return change.additions is None or change.deletions is None
192
+
193
+
194
+ def display_label_for_change(
195
+ change: CommitFileChange,
196
+ section: CommitPatchSection | None,
197
+ ) -> str:
198
+ if section and section.is_rename:
199
+ label = f"{section.old_path} -> {section.new_path}"
200
+ else:
201
+ label = change.path
202
+ if _is_binary(change):
203
+ label += " [binary]"
204
+ return label
205
+
206
+
207
+ def compact_label_for_change(
208
+ change: CommitFileChange,
209
+ section: CommitPatchSection | None,
210
+ max_len: int,
211
+ ) -> str:
212
+ full_label = display_label_for_change(change, section)
213
+ if len(full_label) <= max_len:
214
+ return full_label
215
+
216
+ suffix = " [binary]" if _is_binary(change) else ""
217
+ label_budget = max(max_len - len(suffix), 4)
218
+ if section and section.is_rename:
219
+ arrow = " -> "
220
+ side_budget = max((label_budget - len(arrow)) // 2, 4)
221
+ old_label = compact_path_label(section.old_path, side_budget)
222
+ new_budget = max(label_budget - len(arrow) - len(old_label), 4)
223
+ new_label = compact_path_label(section.new_path, new_budget)
224
+ compact = f"{old_label}{arrow}{new_label}"
225
+ if len(compact) > label_budget:
226
+ compact = truncate_middle(compact, label_budget)
227
+ else:
228
+ compact = compact_path_label(change.path, label_budget)
229
+
230
+ return f"{compact}{suffix}"
231
+
232
+
233
+ def _ellipsize_filename(name: str, max_len: int) -> str:
234
+ """Shorten a filename to fit, keeping its start and, when there is room, its
235
+ extension, with a single ellipsis between them."""
236
+ if len(name) <= max_len:
237
+ return name
238
+ if max_len <= 1:
239
+ return "…"
240
+ dot = name.rfind(".")
241
+ ext = name[dot:] if 0 < dot < len(name) - 1 else ""
242
+ if ext and len(ext) + 2 <= max_len:
243
+ return f"{name[:max_len - 1 - len(ext)]}…{ext}"
244
+ return f"{name[:max_len - 1]}…"
245
+
246
+
247
+ def compact_path_label(path: str, max_len: int) -> str:
248
+ if len(path) <= max_len:
249
+ return path
250
+ parts = [part for part in path.split("/") if part]
251
+ if not parts:
252
+ return _ellipsize_filename(path, max_len)
253
+
254
+ filename = parts[-1]
255
+ if len(filename) + 2 > max_len:
256
+ return _ellipsize_filename(filename, max_len)
257
+
258
+ label = filename
259
+ for parent in reversed(parts[:-1]):
260
+ candidate = f"{parent}/{label}"
261
+ if len(candidate) + 2 > max_len:
262
+ break
263
+ label = candidate
264
+ if label == path:
265
+ return label
266
+ return f"…/{label}"
vidi/docs.py ADDED
@@ -0,0 +1,109 @@
1
+ """Build the man pages and the README key tables from the app's own sources.
2
+
3
+ `git view --help` runs `man git-view`. Options come from the argparse parser
4
+ and the key tables from the help screen's SHORTCUTS.
5
+
6
+ Regenerate with `python -m vidi.docs` after changing either.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ from pathlib import Path
13
+
14
+ from .cli import NAMES, build_parser
15
+ from .screens.help import SHORTCUTS
16
+
17
+ ROOT = Path(__file__).resolve().parents[2]
18
+ MAN_DIR = ROOT / "man"
19
+ README = ROOT / "README.md"
20
+ PAGES = ("vidi", "git-view", "git-vidi")
21
+ KEYS_START = "<!-- keys:start -->"
22
+ KEYS_END = "<!-- keys:end -->"
23
+
24
+
25
+ def _escape(text: str) -> str:
26
+ text = text.replace("\\", "\\e").replace("-", "\\-")
27
+ if text.startswith((".", "'")):
28
+ text = "\\&" + text
29
+ return text
30
+
31
+
32
+ def build_manpage(prog: str) -> str:
33
+ parser = build_parser(prog)
34
+ usage = " ".join(parser.format_usage().split()[1:])
35
+ lines = [
36
+ f'.TH {prog.upper()} 1 "" "vidi" "vidi manual"',
37
+ ".SH NAME",
38
+ f"{_escape(', '.join(PAGES))} \\- {_escape(parser.description or '')}",
39
+ ".SH SYNOPSIS",
40
+ f".B {_escape(usage)}",
41
+ ".SH DESCRIPTION",
42
+ _escape(
43
+ "Opens the repository you are in when given no path. "
44
+ "Settings such as the theme and the language "
45
+ "scan are changed inside the app from the command palette (Ctrl+P). " + NAMES
46
+ ),
47
+ ".SH OPTIONS",
48
+ ]
49
+ for action in parser._actions:
50
+ if action.help is argparse.SUPPRESS:
51
+ continue
52
+ name = ", ".join(action.option_strings) or action.metavar or action.dest
53
+ lines += [".TP", f".B {_escape(name)}", _escape(action.help or "")]
54
+ lines += [".SH KEYS", _escape("Press ? in the app to show these keys.")]
55
+ for section, keys in SHORTCUTS:
56
+ lines += [".SS " + _escape(section)]
57
+ for key, description in keys:
58
+ lines += [".TP", f".B {_escape(key)}", _escape(description)]
59
+ lines += [
60
+ ".SH FILES",
61
+ ".TP",
62
+ ".I ~/.config/vidi/config.json",
63
+ _escape("Saved preferences (honors XDG_CONFIG_HOME)."),
64
+ ".SH SEE ALSO",
65
+ ".BR git (1)",
66
+ ]
67
+ return "\n".join(lines) + "\n"
68
+
69
+
70
+ def _markdown_keys(keys: str) -> str:
71
+ """Put each key in backticks, as in "`j` / `k` or `up` / `down`"."""
72
+ groups = []
73
+ for group in keys.split(" or "):
74
+ names = [name if name in ("type", "drag") else f"`{name}`" for name in group.split(" / ")]
75
+ groups.append(" / ".join(names))
76
+ return " or ".join(groups)
77
+
78
+
79
+ def build_readme_keys() -> str:
80
+ lines = [KEYS_START]
81
+ for section, keys in SHORTCUTS:
82
+ lines += ["", f"### {section}", "", "| Key | Action |", "| --- | --- |"]
83
+ lines += [f"| {_markdown_keys(key)} | {description} |" for key, description in keys]
84
+ lines += ["", KEYS_END]
85
+ return "\n".join(lines)
86
+
87
+
88
+ def update_readme(text: str) -> str:
89
+ """The README text with its key tables regenerated between the markers."""
90
+ start = text.index(KEYS_START)
91
+ end = text.index(KEYS_END) + len(KEYS_END)
92
+ return text[:start] + build_readme_keys() + text[end:]
93
+
94
+
95
+ def _write(path: Path, text: str) -> None:
96
+ # The same bytes on every system, without CRLF line endings on Windows.
97
+ with open(path, "w", encoding="utf-8", newline="\n") as handle:
98
+ handle.write(text)
99
+
100
+
101
+ def write_docs() -> None:
102
+ MAN_DIR.mkdir(parents=True, exist_ok=True)
103
+ for prog in PAGES:
104
+ _write(MAN_DIR / f"{prog}.1", build_manpage(prog))
105
+ _write(README, update_readme(README.read_text(encoding="utf-8")))
106
+
107
+
108
+ if __name__ == "__main__":
109
+ write_docs()
vidi/formatting.py ADDED
@@ -0,0 +1,83 @@
1
+ """Shared text-formatting helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from rich.text import Text
6
+
7
+ from .models import RepoContext, ThemePalette
8
+ from .theme import make_change_stat_style, make_style
9
+ from .utils import truncate_middle
10
+
11
+
12
+ def build_commit_identity_line(
13
+ palette: ThemePalette,
14
+ authored_label: str,
15
+ author_name: str,
16
+ *,
17
+ author_max_width: int | None = None,
18
+ ) -> Text:
19
+ text = Text()
20
+ text.append(authored_label, style=make_style(palette.muted))
21
+ text.append(" ", style=make_style(palette.muted))
22
+ text.append(
23
+ truncate_middle(author_name, author_max_width)
24
+ if author_max_width is not None
25
+ else author_name,
26
+ style=make_style(palette.foreground),
27
+ )
28
+ return text
29
+
30
+
31
+ def change_stat_labels(additions: int | None, deletions: int | None) -> tuple[str, str]:
32
+ """The "+adds" and "-dels" labels, with "+-" and "--" for a binary file."""
33
+ return (
34
+ "+-" if additions is None else f"+{additions}",
35
+ "--" if deletions is None else f"-{deletions}",
36
+ )
37
+
38
+
39
+ def append_file_change_summary_line(
40
+ text: Text,
41
+ palette: ThemePalette,
42
+ label: str,
43
+ additions: int | None,
44
+ deletions: int | None,
45
+ ) -> None:
46
+ additions_text, deletions_text = change_stat_labels(additions, deletions)
47
+ text.append(" - ", style=make_style(palette.muted))
48
+ text.append(label, style=make_style(palette.foreground))
49
+ text.append(" ", style=make_style(palette.muted))
50
+ text.append(
51
+ additions_text,
52
+ style=make_change_stat_style(palette, additions, positive=True),
53
+ )
54
+ text.append(" ", style=make_style(palette.muted))
55
+ text.append(
56
+ deletions_text,
57
+ style=make_change_stat_style(palette, deletions, positive=False),
58
+ )
59
+
60
+
61
+ def _count(n: int, singular: str, plural: str | None = None) -> str:
62
+ return f"{n} {singular if n == 1 else (plural or singular + 's')}"
63
+
64
+
65
+ def build_repo_stats_sub_title(
66
+ context: RepoContext,
67
+ scanned_file_count: int,
68
+ branch: str | None = None,
69
+ ahead: int = 0,
70
+ behind: int = 0,
71
+ ) -> str:
72
+ parts: list[str] = []
73
+ if branch:
74
+ marks = ""
75
+ if ahead:
76
+ marks += f" ↑{ahead}"
77
+ if behind:
78
+ marks += f" ↓{behind}"
79
+ parts.append(f"{branch}{marks}")
80
+ parts.append(_count(context.repo_commit_count, "commit"))
81
+ parts.append(_count(len(context.branches), "branch", "branches"))
82
+ parts.append(_count(scanned_file_count, "file"))
83
+ return " · ".join(parts)
vidi/models.py ADDED
@@ -0,0 +1,101 @@
1
+ """Core data models."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime as dt
6
+ from dataclasses import dataclass
7
+ from typing import Any
8
+
9
+ from textual.color import Color
10
+
11
+
12
+ LanguageStat = dict[str, Any]
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class ThemePalette:
17
+ background: Color
18
+ panel: Color
19
+ surface: Color
20
+ foreground: Color
21
+ success: Color
22
+ error: Color
23
+ muted: Color
24
+ border: Color
25
+ primary: Color
26
+ selected_bg: Color
27
+ selected_fg: Color
28
+ overlay: Color
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class CommitRecord:
33
+ commit_hash: str
34
+ authored_at: dt.datetime
35
+ message: str
36
+ author_name: str
37
+ author_email: str
38
+ changed_files: tuple[str, ...]
39
+
40
+ @property
41
+ def authored_date(self) -> dt.date:
42
+ return self.authored_at.date()
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class CommitFileChange:
47
+ path: str
48
+ additions: int | None
49
+ deletions: int | None
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class CommitPatchSection:
54
+ path: str
55
+ old_path: str
56
+ new_path: str
57
+ patch: str
58
+ is_binary: bool
59
+ is_rename: bool
60
+
61
+
62
+ @dataclass(frozen=True)
63
+ class CommitDetail:
64
+ commit_hash: str
65
+ parents: tuple[str, ...]
66
+ author_name: str
67
+ author_email: str
68
+ authored_at: dt.datetime
69
+ subject: str
70
+ body: str
71
+ file_changes: tuple[CommitFileChange, ...]
72
+ patch_sections: tuple[CommitPatchSection, ...]
73
+ patch: str
74
+
75
+
76
+ @dataclass(frozen=True)
77
+ class BranchData:
78
+ branch: str
79
+ commits: list[CommitRecord]
80
+ years: list[int]
81
+
82
+
83
+ @dataclass(frozen=True)
84
+ class RepoContext:
85
+ repo_dir: str
86
+ project_name: str
87
+ repo_commit_count: int
88
+ branches: list[str]
89
+ branch_heads: tuple[tuple[str, str], ...]
90
+ current_branch: str
91
+ language_stats: list[LanguageStat]
92
+ files_by_language: dict[str, list[str]]
93
+ initial_branch_data: BranchData | None = None
94
+
95
+
96
+ @dataclass(frozen=True)
97
+ class RepoScanSnapshot:
98
+ branch_heads: tuple[tuple[str, str], ...]
99
+ current_branch: str
100
+ repo_commit_count: int
101
+ scanned_file_count: int