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/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """A read-only terminal viewer for a local Git repository."""
2
+
3
+ from .app import VidiApp
4
+
5
+ __all__ = ["VidiApp"]
vidi/__main__.py ADDED
@@ -0,0 +1,7 @@
1
+ """Module execution entrypoint."""
2
+
3
+ from .cli import main
4
+
5
+
6
+ if __name__ == "__main__":
7
+ main()
vidi/app.py ADDED
@@ -0,0 +1,267 @@
1
+ """Application entrypoint."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+
7
+ from textual.app import App, SystemCommand
8
+ from textual.binding import Binding
9
+ from textual.screen import Screen
10
+
11
+ from . import config
12
+ from .models import RepoContext, RepoScanSnapshot
13
+ from .repository import RepoService
14
+ from .screens import HelpScreen, MainScreen
15
+ from .screens.language_settings import LanguageSettingsScreen
16
+ from .theme import APP_THEME_NAME, app_themes
17
+
18
+
19
+ class VidiApp(App[None]):
20
+ """Thin app shell."""
21
+
22
+ REPO_SCAN_MIN_SECONDS = 10.0
23
+ REPO_SCAN_DEFAULT_SECONDS = 20.0
24
+ REPO_SCAN_MAX_SECONDS = 120.0
25
+
26
+ BINDINGS = [
27
+ Binding("q", "quit", "Quit"),
28
+ Binding("question_mark", "show_help", "Help"),
29
+ ]
30
+
31
+ def __init__(self, context: RepoContext, service: RepoService) -> None:
32
+ super().__init__()
33
+ self.context = context
34
+ self.service = service
35
+ self._repo_scan_snapshot = self._snapshot_of(context)
36
+ self._repo_scan_in_flight = False
37
+ self._repo_scan_task: asyncio.Task[None] | None = None
38
+ self._initial_context_task: asyncio.Task[None] | None = None
39
+ # When True the graph previews a day as you move and selects it on Enter.
40
+ self.graph_browse = config.load_graph_browse()
41
+ # When True the app themes use the terminal's default background.
42
+ self.transparent_background = config.load_transparent_background()
43
+ # Whether long lines wrap in the file view and in diffs.
44
+ self.wrap_file_view = config.load_wrap_file_view()
45
+ self.wrap_diffs = config.load_wrap_diffs()
46
+
47
+ def _snapshot_of(self, context: RepoContext) -> RepoScanSnapshot:
48
+ return RepoScanSnapshot(
49
+ branch_heads=context.branch_heads,
50
+ current_branch=context.current_branch,
51
+ repo_commit_count=context.repo_commit_count,
52
+ scanned_file_count=self.service.scanned_file_count(context),
53
+ )
54
+
55
+ def on_mount(self) -> None:
56
+ # Register the app themes and restore the saved one, or the default.
57
+ self._theme_source = self.current_theme # Textual default, derives vidi
58
+ for theme in app_themes(self._theme_source, transparent=self.transparent_background):
59
+ self.register_theme(theme)
60
+ saved = config.load_theme()
61
+ self.theme = saved if saved in self.available_themes else APP_THEME_NAME
62
+ self._apply_transparency()
63
+ self.watch(self, "theme", self._persist_theme, init=False)
64
+ self.title = self.context.project_name
65
+ self.push_screen(MainScreen(self.context, self.service))
66
+ if not self.context.language_stats or not self.context.files_by_language:
67
+ self._initial_context_task = asyncio.create_task(self._warm_initial_context())
68
+ self._schedule_next_repo_scan(self.REPO_SCAN_DEFAULT_SECONDS)
69
+
70
+ def _persist_theme(self, theme_name: str) -> None:
71
+ config.save_theme(theme_name)
72
+
73
+ def get_system_commands(self, screen: Screen):
74
+ yield from super().get_system_commands(screen)
75
+ yield SystemCommand(
76
+ "Reset theme to default",
77
+ "Switch back to the vidi theme",
78
+ self._command_reset_theme,
79
+ )
80
+ graph_label = (
81
+ "Graph: commit table follows as you move"
82
+ if self.graph_browse
83
+ else "Graph: commit table follows on Enter"
84
+ )
85
+ yield SystemCommand(
86
+ graph_label,
87
+ "Toggle whether moving over the graph moves the commit-table selection "
88
+ "immediately or only when you press Enter",
89
+ self._command_toggle_graph_browse,
90
+ )
91
+ transparent_label = (
92
+ "Opaque background"
93
+ if self.transparent_background
94
+ else "Transparent background"
95
+ )
96
+ yield SystemCommand(
97
+ transparent_label,
98
+ "Toggle whether the app paints its own background or lets the "
99
+ "terminal (and its transparency) show through",
100
+ self._command_toggle_transparent,
101
+ )
102
+ file_wrap_label = (
103
+ "Stop wrapping lines in file view"
104
+ if self.wrap_file_view
105
+ else "Wrap lines in file view"
106
+ )
107
+ yield SystemCommand(
108
+ file_wrap_label,
109
+ "Toggle whether long lines in the file view wrap or scroll sideways",
110
+ self._command_toggle_wrap_file_view,
111
+ )
112
+ diff_wrap_label = (
113
+ "Stop wrapping lines in diffs" if self.wrap_diffs else "Wrap lines in diffs"
114
+ )
115
+ yield SystemCommand(
116
+ diff_wrap_label,
117
+ "Toggle whether long lines in diffs and patches wrap or scroll sideways",
118
+ self._command_toggle_wrap_diffs,
119
+ )
120
+ yield SystemCommand(
121
+ "Language settings",
122
+ "Choose how languages are measured and what the scan skips",
123
+ self._command_language_settings,
124
+ )
125
+
126
+ def _command_reset_theme(self) -> None:
127
+ self.theme = APP_THEME_NAME
128
+
129
+ def _command_language_settings(self) -> None:
130
+ self.push_screen(
131
+ LanguageSettingsScreen(
132
+ self.service.language_mode,
133
+ sorted(self.service.exclude_languages),
134
+ sorted(self.service.extra_ignored_dirs),
135
+ ),
136
+ self._apply_language_settings,
137
+ )
138
+
139
+ def _apply_language_settings(self, result: dict | None) -> None:
140
+ if not result:
141
+ return
142
+ self.service.update_language_settings(
143
+ result["language_mode"],
144
+ set(result["exclude_languages"]),
145
+ set(result["ignore_dirs"]),
146
+ )
147
+ config.save_language_settings(
148
+ result["language_mode"],
149
+ result["exclude_languages"],
150
+ result["ignore_dirs"],
151
+ )
152
+ screen = self.screen
153
+ if isinstance(screen, MainScreen):
154
+ screen.reload_language_panel()
155
+
156
+ def _command_toggle_graph_browse(self) -> None:
157
+ self.graph_browse = not self.graph_browse
158
+ config.save_graph_browse(self.graph_browse)
159
+
160
+ def _command_toggle_wrap_file_view(self) -> None:
161
+ self.wrap_file_view = not self.wrap_file_view
162
+ config.save_wrap_file_view(self.wrap_file_view)
163
+ self._apply_wrap_settings()
164
+
165
+ def _command_toggle_wrap_diffs(self) -> None:
166
+ self.wrap_diffs = not self.wrap_diffs
167
+ config.save_wrap_diffs(self.wrap_diffs)
168
+ self._apply_wrap_settings()
169
+
170
+ def _apply_wrap_settings(self) -> None:
171
+ for screen in list(self.screen_stack):
172
+ handler = getattr(screen, "apply_wrap_settings", None)
173
+ if callable(handler):
174
+ handler()
175
+
176
+ def _command_toggle_transparent(self) -> None:
177
+ self.transparent_background = not self.transparent_background
178
+ config.save_transparent_background(self.transparent_background)
179
+ # Rebuild the app themes for the new background and re-apply the current one.
180
+ for theme in app_themes(self._theme_source, transparent=self.transparent_background):
181
+ self.register_theme(theme)
182
+ self.theme = self.current_theme.name
183
+ self._apply_transparency()
184
+ # Re-registered themes don't reach computed backgrounds without a CSS refresh.
185
+ self.refresh_css()
186
+
187
+ def _apply_transparency(self) -> None:
188
+ # ansi_default only stays transparent in native-ANSI mode.
189
+ self.ansi_color = True if self.transparent_background else None
190
+
191
+ def on_unmount(self) -> None:
192
+ if self._repo_scan_task is not None:
193
+ self._repo_scan_task.cancel()
194
+ self._repo_scan_task = None
195
+ if self._initial_context_task is not None:
196
+ self._initial_context_task.cancel()
197
+ self._initial_context_task = None
198
+
199
+ def _schedule_next_repo_scan(self, delay_seconds: float) -> None:
200
+ self.set_timer(delay_seconds, self._trigger_repo_scan)
201
+
202
+ def _next_repo_scan_delay(self, duration_seconds: float) -> float:
203
+ return min(
204
+ self.REPO_SCAN_MAX_SECONDS,
205
+ max(self.REPO_SCAN_MIN_SECONDS, duration_seconds * 30.0),
206
+ )
207
+
208
+ def _trigger_repo_scan(self) -> None:
209
+ if self._repo_scan_in_flight:
210
+ self._schedule_next_repo_scan(self.REPO_SCAN_MIN_SECONDS)
211
+ return
212
+ self._repo_scan_task = asyncio.create_task(self._scan_repo_state())
213
+
214
+ def _apply_refreshed_context(
215
+ self,
216
+ previous_context: RepoContext,
217
+ new_context: RepoContext,
218
+ previous_snapshot: RepoScanSnapshot,
219
+ new_snapshot: RepoScanSnapshot,
220
+ ) -> None:
221
+ self.context = new_context
222
+ self._repo_scan_snapshot = new_snapshot
223
+ for screen in list(self.screen_stack):
224
+ handler = getattr(screen, "handle_repo_context_refresh", None)
225
+ if callable(handler):
226
+ handler(previous_context, new_context, previous_snapshot, new_snapshot)
227
+
228
+ async def _warm_initial_context(self) -> None:
229
+ try:
230
+ previous_context = self.context
231
+ previous_snapshot = self._repo_scan_snapshot
232
+ new_context = await asyncio.to_thread(self.service.refresh_context)
233
+ self._apply_refreshed_context(
234
+ previous_context,
235
+ new_context,
236
+ previous_snapshot,
237
+ self._snapshot_of(new_context),
238
+ )
239
+ finally:
240
+ self._initial_context_task = None
241
+
242
+ async def _scan_repo_state(self) -> None:
243
+ self._repo_scan_in_flight = True
244
+ duration = self.REPO_SCAN_DEFAULT_SECONDS
245
+ try:
246
+ snapshot, duration = await asyncio.to_thread(self.service.scan_repo_state)
247
+ previous_snapshot = self._repo_scan_snapshot
248
+ self._repo_scan_snapshot = snapshot
249
+ if snapshot != previous_snapshot:
250
+ self.service.invalidate_cached_git_data()
251
+ previous_context = self.context
252
+ new_context = await asyncio.to_thread(self.service.refresh_context)
253
+ self._apply_refreshed_context(
254
+ previous_context,
255
+ new_context,
256
+ previous_snapshot,
257
+ snapshot,
258
+ )
259
+ finally:
260
+ self._repo_scan_in_flight = False
261
+ self._repo_scan_task = None
262
+ self._schedule_next_repo_scan(self._next_repo_scan_delay(duration))
263
+
264
+ def action_show_help(self) -> None:
265
+ if isinstance(self.screen, HelpScreen):
266
+ return
267
+ self.push_screen(HelpScreen())
vidi/cli.py ADDED
@@ -0,0 +1,119 @@
1
+ """CLI entrypoint."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import os
7
+ import subprocess
8
+ import sys
9
+ import textwrap
10
+ from importlib.metadata import PackageNotFoundError, version
11
+
12
+ from . import config
13
+ from .app import VidiApp
14
+ from .repository import build_initial_repo_context
15
+ from .screens.help import SHORTCUTS
16
+
17
+
18
+ def package_version() -> str:
19
+ """The installed version in the package metadata from pyproject.toml."""
20
+ try:
21
+ return version("git-vidi")
22
+ except PackageNotFoundError:
23
+ return "unknown"
24
+
25
+
26
+ NAMES = "The same program runs as vidi, git view and git vidi."
27
+
28
+
29
+ def keys_reference(width: int = 79) -> str:
30
+ """Every key section of the in-app help as plain text."""
31
+ key_width = max(len(key) for _, keys in SHORTCUTS for key, _ in keys)
32
+ indent = " " * (4 + key_width + 2)
33
+ lines = ["keys:"]
34
+ for section, keys in SHORTCUTS:
35
+ lines.append(f" {section}:")
36
+ for key, description in keys:
37
+ lines += textwrap.wrap(
38
+ description,
39
+ width,
40
+ initial_indent=f" {key:<{key_width}} ",
41
+ subsequent_indent=indent,
42
+ )
43
+ lines.append("")
44
+ lines.append("Press ? in the app for the same keys.")
45
+ lines.append(NAMES)
46
+ return "\n".join(lines)
47
+
48
+
49
+ def build_parser(prog: str | None = None) -> argparse.ArgumentParser:
50
+ """Description for the command line `-h` and the man page."""
51
+ parser = argparse.ArgumentParser(
52
+ prog=prog,
53
+ description="browse a local git repository in the terminal",
54
+ epilog=keys_reference(),
55
+ formatter_class=argparse.RawDescriptionHelpFormatter,
56
+ )
57
+ parser.add_argument(
58
+ "--version",
59
+ action="version",
60
+ version=f"vidi {package_version()}",
61
+ )
62
+ parser.add_argument(
63
+ "repo_dir",
64
+ nargs="?",
65
+ default=".",
66
+ help="Path inside a local git repository (defaults to the current folder)",
67
+ )
68
+ return parser
69
+
70
+
71
+ def parse_args() -> argparse.Namespace:
72
+ return build_parser().parse_args()
73
+
74
+
75
+ def resolve_repo_dir(path: str) -> str:
76
+ """Return the top folder of the work tree that contains `path`.
77
+
78
+ Works from any subfolder and worktrees and submodules.
79
+ Raises ValueError with a message to print.
80
+ """
81
+ path = os.path.abspath(path)
82
+ if not os.path.isdir(path):
83
+ raise ValueError(f"directory does not exist: {path}")
84
+ try:
85
+ output = subprocess.check_output(
86
+ ["git", "-C", path, "rev-parse", "--show-toplevel"],
87
+ stderr=subprocess.DEVNULL,
88
+ )
89
+ except (OSError, subprocess.CalledProcessError):
90
+ output = b""
91
+ # Git prints the path as the file system stores it and with forward slashes on Windows.
92
+ top = os.fsdecode(output).strip()
93
+ if not top:
94
+ raise ValueError(f"not inside a git work tree: {path}")
95
+ return os.path.normpath(top)
96
+
97
+
98
+ def main() -> None:
99
+ args = parse_args()
100
+ try:
101
+ repo_dir = resolve_repo_dir(args.repo_dir)
102
+ except ValueError as exc:
103
+ print(f"Error: {exc}")
104
+ sys.exit(1)
105
+
106
+ settings = config.load_language_settings()
107
+
108
+ try:
109
+ context, service = build_initial_repo_context(
110
+ repo_dir=repo_dir,
111
+ language_mode=settings["language_mode"],
112
+ exclude_languages=set(settings["exclude_languages"]),
113
+ extra_ignored_dirs=set(settings["ignore_dirs"]),
114
+ )
115
+ except RuntimeError as exc:
116
+ print(f"Error: {exc}")
117
+ sys.exit(1)
118
+
119
+ VidiApp(context, service).run()
vidi/config.py ADDED
@@ -0,0 +1,119 @@
1
+ """User preferences, persisted to a small JSON file under the config dir."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ from collections.abc import Mapping
8
+ from pathlib import Path
9
+
10
+
11
+ def _config_dir(environ: Mapping[str, str], windows: bool) -> Path:
12
+ """The folder for the settings file."""
13
+ if environ.get("XDG_CONFIG_HOME"):
14
+ return Path(environ["XDG_CONFIG_HOME"]) / "vidi"
15
+ if windows and environ.get("APPDATA"):
16
+ return Path(environ["APPDATA"]) / "vidi"
17
+ return Path.home() / ".config" / "vidi"
18
+
19
+
20
+ CONFIG_DIR = _config_dir(os.environ, os.name == "nt")
21
+ CONFIG_PATH = CONFIG_DIR / "config.json"
22
+
23
+
24
+ def _load() -> dict:
25
+ try:
26
+ data = json.loads(CONFIG_PATH.read_text(encoding="utf-8"))
27
+ except (OSError, ValueError):
28
+ return {}
29
+ return data if isinstance(data, dict) else {}
30
+
31
+
32
+ def _set_many(values: dict[str, object]) -> None:
33
+ """Persist preferences, ignoring write failures."""
34
+ try:
35
+ prefs = _load()
36
+ prefs.update(values)
37
+ CONFIG_DIR.mkdir(parents=True, exist_ok=True)
38
+ CONFIG_PATH.write_text(json.dumps(prefs, indent=2) + "\n", encoding="utf-8")
39
+ except OSError:
40
+ pass
41
+
42
+
43
+ def _set(key: str, value: object) -> None:
44
+ _set_many({key: value})
45
+
46
+
47
+ def load_theme() -> str | None:
48
+ """The persisted theme name, or None if nothing was saved."""
49
+ value = _load().get("theme")
50
+ return value if isinstance(value, str) else None
51
+
52
+
53
+ def save_theme(name: str) -> None:
54
+ _set("theme", name)
55
+
56
+
57
+ def load_graph_browse() -> bool:
58
+ """Whether the graph waits for Enter to select a day."""
59
+ return bool(_load().get("graph_browse", False))
60
+
61
+
62
+ def save_graph_browse(value: bool) -> None:
63
+ _set("graph_browse", bool(value))
64
+
65
+
66
+ def load_transparent_background() -> bool:
67
+ """Whether the app uses the terminal's background."""
68
+ return bool(_load().get("transparent_background", False))
69
+
70
+
71
+ def save_transparent_background(value: bool) -> None:
72
+ _set("transparent_background", bool(value))
73
+
74
+
75
+ def load_wrap_file_view() -> bool:
76
+ """Whether the file view wraps long lines."""
77
+ return bool(_load().get("wrap_file_view", False))
78
+
79
+
80
+ def save_wrap_file_view(value: bool) -> None:
81
+ _set("wrap_file_view", bool(value))
82
+
83
+
84
+ def load_wrap_diffs() -> bool:
85
+ """Whether diffs and patches wrap long lines."""
86
+ return bool(_load().get("wrap_diffs", True))
87
+
88
+
89
+ def save_wrap_diffs(value: bool) -> None:
90
+ _set("wrap_diffs", bool(value))
91
+
92
+
93
+ def _str_list(value: object) -> list[str]:
94
+ if not isinstance(value, list):
95
+ return []
96
+ return [item for item in value if isinstance(item, str) and item]
97
+
98
+
99
+ def load_language_settings() -> dict:
100
+ """The persisted language-scan settings, falling back to sensible defaults."""
101
+ prefs = _load()
102
+ mode = prefs.get("language_mode")
103
+ return {
104
+ "language_mode": mode if mode in ("bytes", "files") else "bytes",
105
+ "exclude_languages": _str_list(prefs.get("exclude_languages")),
106
+ "ignore_dirs": _str_list(prefs.get("ignore_dirs")),
107
+ }
108
+
109
+
110
+ def save_language_settings(
111
+ language_mode: str, exclude_languages: list[str], ignore_dirs: list[str]
112
+ ) -> None:
113
+ _set_many(
114
+ {
115
+ "language_mode": language_mode if language_mode in ("bytes", "files") else "bytes",
116
+ "exclude_languages": list(exclude_languages),
117
+ "ignore_dirs": list(ignore_dirs),
118
+ }
119
+ )