git-multi-status 0.0.1__tar.gz

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.
@@ -0,0 +1,12 @@
1
+ Metadata-Version: 2.4
2
+ Name: git-multi-status
3
+ Version: 0.0.1
4
+ Summary: Python port of multi-git-status
5
+ Requires-Python: >=3.10
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: rich>=14.0.0
8
+ Requires-Dist: typer>=0.15.2
9
+
10
+ # Git Multi Status
11
+
12
+ List the status of multiple Git repositories in a directory.
@@ -0,0 +1,3 @@
1
+ # Git Multi Status
2
+
3
+ List the status of multiple Git repositories in a directory.
@@ -0,0 +1,28 @@
1
+ [project]
2
+ name = "git-multi-status"
3
+ version = "0.0.1"
4
+ description = "Python port of multi-git-status"
5
+ readme = "README.md"
6
+ requires-python = ">=3.10"
7
+ dependencies = [
8
+ "rich>=14.0.0",
9
+ "typer>=0.15.2",
10
+ ]
11
+
12
+ [project.scripts]
13
+ git-multi-status = "git_multi_status.__main__:app"
14
+
15
+ [tool.ruff]
16
+ line-length = 120
17
+ target-version = "py310"
18
+
19
+ [tool.ruff.lint]
20
+ select = ["F", "E", "W", "I", "PL"]
21
+ ignore = ["E501", "W191", "PLR0913", "PLR0912", "PLR0915"]
22
+
23
+ [tool.ruff.lint.isort]
24
+ known-first-party = ["gronpy"]
25
+
26
+ [tool.ruff.lint.pylint]
27
+ max-returns = 10
28
+ max-branches = 20
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,410 @@
1
+ # MIT license
2
+
3
+ import os
4
+ import subprocess
5
+ import time
6
+ from importlib.metadata import PackageNotFoundError, version
7
+
8
+ import typer
9
+ from rich.console import Console
10
+ from rich.text import Text
11
+ from typing_extensions import Annotated
12
+
13
+ # Create Rich console
14
+ console = Console()
15
+
16
+ app = typer.Typer(
17
+ help="git-multi-status shows uncommitted, untracked and unpushed changes in multiple Git repositories."
18
+ )
19
+ app.debug = False # Default debug state
20
+
21
+
22
+ def debug(*args, **kwargs):
23
+ """Print debug messages if debug mode is enabled"""
24
+ if app.debug:
25
+ console.print(*args, **kwargs)
26
+
27
+
28
+ def debug_callback(ctx: typer.Context, value: bool):
29
+ """Callback to set debug mode on the app instance"""
30
+ app.debug = value
31
+ return value
32
+
33
+
34
+ def run_git_command(git_dir, work_tree, *args):
35
+ """Run a git command and return its output."""
36
+ cmd = ["git"]
37
+ if work_tree:
38
+ cmd.extend(["--work-tree", work_tree])
39
+ if git_dir:
40
+ cmd.extend(["--git-dir", git_dir])
41
+ cmd.extend(args)
42
+
43
+ debug(f"Running git command: {' '.join(cmd)}")
44
+
45
+ try:
46
+ output = subprocess.check_output(cmd, stderr=subprocess.DEVNULL).decode("utf-8").strip()
47
+ debug(f"Command output: {output}")
48
+ return output
49
+ except subprocess.CalledProcessError as e:
50
+ debug(f"Command failed with return code: {e.returncode}")
51
+ return ""
52
+
53
+
54
+ def find_git_repos(start_dir, depth, warn_not_repo):
55
+ """Find all git repositories up to a certain depth. Use 0 for no depth, -1 for unlimited."""
56
+ debug(f"Searching for git repos in: {start_dir}")
57
+ debug(f"Depth: {depth}")
58
+
59
+ git_dirs = []
60
+
61
+ if depth == 0:
62
+ # Only check if the start_dir itself is a git repo
63
+ git_path = os.path.join(start_dir, ".git")
64
+ debug(f"Checking for .git in: {git_path}")
65
+ if os.path.isdir(git_path):
66
+ git_dirs.append(start_dir)
67
+ elif warn_not_repo:
68
+ text = Text()
69
+ text.append(f"{start_dir}: ")
70
+ text.append("Not a git repository", style="yellow")
71
+ console.print(text)
72
+ return git_dirs
73
+
74
+ for root, dirs, _ in os.walk(start_dir, followlinks=True):
75
+ debug(f"Checking directory: {root}")
76
+ debug(f"Subdirectories: {dirs}")
77
+
78
+ if ".git" in dirs:
79
+ git_dirs.append(root)
80
+ elif warn_not_repo:
81
+ text = Text()
82
+ text.append(f"{root}: ")
83
+ text.append("Not a git repository", style="yellow")
84
+ console.print(text)
85
+
86
+ # Calculate current depth
87
+ rel_path = os.path.relpath(root, start_dir)
88
+ current_depth = len(rel_path.split(os.sep)) if rel_path != "." else 0
89
+
90
+ # Stop recursion if we've reached max depth
91
+ if depth > 0 and current_depth >= depth:
92
+ dirs.clear() # This stops os.walk from going deeper
93
+
94
+ return git_dirs
95
+
96
+
97
+ def print_status(proj_dir, cur_branch, status_text, status_style):
98
+ """Print a status message with rich formatting."""
99
+ text = Text()
100
+ text.append(f"{proj_dir}{cur_branch}: ")
101
+ text.append(status_text, style=status_style)
102
+ console.print(text)
103
+
104
+
105
+ def check_repo(
106
+ proj_dir,
107
+ exclude_ok,
108
+ do_fetch,
109
+ throttle,
110
+ flatten,
111
+ show_branch,
112
+ no_push,
113
+ no_pull,
114
+ no_upstream,
115
+ no_uncommitted,
116
+ no_untracked,
117
+ no_stashes,
118
+ ):
119
+ """Check the status of a git repository."""
120
+ git_dir = os.path.join(proj_dir, ".git")
121
+ git_conf = os.path.join(git_dir, "config")
122
+
123
+ # Check if the repo is safe (ownership)
124
+ if os.path.isdir(git_dir):
125
+ try:
126
+ git_dir_owner = os.stat(git_dir).st_uid
127
+ current_user_id = os.getuid()
128
+
129
+ if current_user_id != git_dir_owner:
130
+ text = Text()
131
+ text.append(f"{proj_dir}: ")
132
+ text.append("Unsafe ownership, owned by someone else. Skipping.", style="purple bold")
133
+ console.print(text)
134
+ return False
135
+ except OSError:
136
+ text = Text()
137
+ text.append(f"{proj_dir}: ")
138
+ text.append("Could not check ownership. Skipping.", style="purple bold")
139
+ console.print(text)
140
+ return False
141
+
142
+ # Check git config for this project to see if we should ignore this repo
143
+ try:
144
+ ignore = run_git_command(git_dir, None, "config", "-f", git_conf, "--bool", "mgitstatus.ignore")
145
+ if ignore == "true":
146
+ return True
147
+ except Exception:
148
+ pass
149
+
150
+ # Check if repo is locked
151
+ if os.path.exists(os.path.join(git_dir, "index.lock")):
152
+ text = Text()
153
+ text.append(f"{proj_dir}: ")
154
+ text.append("Locked. Skipping.", style="red bold")
155
+ console.print(text)
156
+ return False
157
+
158
+ # Do a 'git fetch' if requested
159
+ if do_fetch:
160
+ run_git_command(git_dir, os.path.dirname(git_dir), "fetch", "-q")
161
+
162
+ # Refresh the index, or we might get wrong results
163
+ run_git_command(git_dir, os.path.dirname(git_dir), "update-index", "-q", "--refresh")
164
+
165
+ # Get current branch
166
+ cur_branch = ""
167
+ if show_branch:
168
+ branch = run_git_command(git_dir, None, "rev-parse", "--abbrev-ref", "HEAD")
169
+ cur_branch = f" ({branch})"
170
+
171
+ # Find all remote branches that have been checked out
172
+ needs_push_branches = []
173
+ needs_pull_branches = []
174
+ needs_upstream_branches = []
175
+
176
+ # Find all branch refs
177
+ refs_dir = os.path.join(git_dir, "refs", "heads")
178
+ branch_refs = []
179
+
180
+ if os.path.isdir(refs_dir):
181
+ for root, _, files in os.walk(refs_dir):
182
+ for file in files:
183
+ ref_path = os.path.join(root, file)
184
+ rel_path = os.path.relpath(ref_path, refs_dir)
185
+ if os.path.isfile(ref_path):
186
+ branch_refs.append(rel_path)
187
+
188
+ for ref_head in branch_refs:
189
+ # Check if this branch is tracking an upstream
190
+ upstream = run_git_command(
191
+ git_dir, None, "rev-parse", "--abbrev-ref", "--symbolic-full-name", f"{ref_head}@{{u}}"
192
+ )
193
+
194
+ if upstream:
195
+ # Branch is tracking a remote branch
196
+ cnt_ahead_behind = run_git_command(
197
+ git_dir, None, "rev-list", "--left-right", "--count", f"{ref_head}...{upstream}"
198
+ )
199
+ if cnt_ahead_behind:
200
+ cnt_ahead, cnt_behind = cnt_ahead_behind.split()
201
+
202
+ if int(cnt_ahead) > 0:
203
+ needs_push_branches.append(ref_head)
204
+ if int(cnt_behind) > 0:
205
+ needs_pull_branches.append(ref_head)
206
+
207
+ # Check if this branch is a branch off another branch and if it needs to be updated
208
+ rev_local = run_git_command(git_dir, None, "rev-parse", "--verify", ref_head)
209
+ rev_remote = run_git_command(git_dir, None, "rev-parse", "--verify", upstream)
210
+ rev_base = run_git_command(git_dir, None, "merge-base", ref_head, upstream)
211
+
212
+ if rev_local and rev_remote and rev_base:
213
+ if rev_local != rev_remote:
214
+ if rev_local == rev_base:
215
+ needs_pull_branches.append(ref_head)
216
+ if rev_remote == rev_base:
217
+ needs_push_branches.append(ref_head)
218
+ else:
219
+ # Branch does not have an upstream
220
+ needs_upstream_branches.append(ref_head)
221
+
222
+ # Remove duplicates
223
+ needs_push_branches = list(set(needs_push_branches))
224
+ needs_pull_branches = list(set(needs_pull_branches))
225
+ needs_upstream_branches = list(set(needs_upstream_branches))
226
+
227
+ # Find out if there are unstaged, uncommitted or untracked changes
228
+ # The original script used exit codes, but we need to handle this differently in Python
229
+ # For these git commands, an empty output means success (no changes)
230
+ unstaged_output = run_git_command(git_dir, os.path.dirname(git_dir), "diff-index", "HEAD", "--")
231
+ unstaged = 1 if unstaged_output else 0
232
+
233
+ uncommitted_output = run_git_command(git_dir, os.path.dirname(git_dir), "diff-files", "--ignore-submodules", "--")
234
+ uncommitted = 1 if uncommitted_output else 0
235
+
236
+ untracked = run_git_command(git_dir, os.path.dirname(git_dir), "ls-files", "--exclude-standard", "--others")
237
+
238
+ # Get stashes
239
+ old_dir = os.getcwd()
240
+ os.chdir(os.path.dirname(git_dir))
241
+ stashes = run_git_command(git_dir, None, "stash", "list")
242
+ stash_count = len(stashes.splitlines()) if stashes else 0
243
+ os.chdir(old_dir)
244
+
245
+ debug(f"UNSTAGED: {unstaged}")
246
+ debug(f"UNCOMMITTED: {uncommitted}")
247
+ debug(f"UNTRACKED: {untracked}")
248
+ debug(f"STASHES: {stash_count}")
249
+
250
+ # Build up the status string
251
+ is_ok = True
252
+ status_parts = []
253
+
254
+ # Check for needs_push
255
+ if needs_push_branches and not no_push:
256
+ push_status = f"Needs push ({','.join(needs_push_branches)})"
257
+ if flatten:
258
+ print_status(proj_dir, cur_branch, push_status, "yellow bold")
259
+ else:
260
+ status_parts.append((push_status, "yellow bold"))
261
+ is_ok = False
262
+
263
+ # Check for needs_pull
264
+ if needs_pull_branches and not no_pull:
265
+ pull_status = f"Needs pull ({','.join(needs_pull_branches)})"
266
+ if flatten:
267
+ print_status(proj_dir, cur_branch, pull_status, "blue bold")
268
+ else:
269
+ status_parts.append((pull_status, "blue bold"))
270
+ is_ok = False
271
+
272
+ # Check for needs_upstream
273
+ if needs_upstream_branches and not no_upstream:
274
+ upstream_status = f"Needs upstream ({','.join(needs_upstream_branches)})"
275
+ if flatten:
276
+ print_status(proj_dir, cur_branch, upstream_status, "purple bold")
277
+ else:
278
+ status_parts.append((upstream_status, "purple bold"))
279
+ is_ok = False
280
+
281
+ # Check for uncommitted changes
282
+ if (unstaged != 0 or uncommitted != 0) and not no_uncommitted:
283
+ uncommitted_status = "Uncommitted changes"
284
+ if flatten:
285
+ print_status(proj_dir, cur_branch, uncommitted_status, "red bold")
286
+ else:
287
+ status_parts.append((uncommitted_status, "red bold"))
288
+ is_ok = False
289
+
290
+ # Check for untracked files
291
+ if untracked and not no_untracked:
292
+ untracked_status = "Untracked files"
293
+ if flatten:
294
+ print_status(proj_dir, cur_branch, untracked_status, "cyan bold")
295
+ else:
296
+ status_parts.append((untracked_status, "cyan bold"))
297
+ is_ok = False
298
+
299
+ # Check for stashes
300
+ if stash_count and not no_stashes:
301
+ stashes_status = f"{stash_count} stashes"
302
+ if flatten:
303
+ print_status(proj_dir, cur_branch, stashes_status, "yellow bold")
304
+ else:
305
+ status_parts.append((stashes_status, "yellow bold"))
306
+ is_ok = False
307
+
308
+ # If everything is OK
309
+ if is_ok:
310
+ ok_status = "ok"
311
+ if flatten and not exclude_ok:
312
+ print_status(proj_dir, cur_branch, ok_status, "green bold")
313
+ else:
314
+ status_parts.append((ok_status, "green bold"))
315
+
316
+ # Print non-flattened output
317
+ if not flatten and (not is_ok or not exclude_ok):
318
+ text = Text()
319
+ text.append(f"{proj_dir}{cur_branch}: ")
320
+
321
+ for i, (status, style) in enumerate(status_parts):
322
+ text.append(status, style=style)
323
+ if i < len(status_parts) - 1:
324
+ text.append(" ")
325
+
326
+ console.print(text)
327
+
328
+ # Throttle if requested
329
+ if do_fetch and throttle:
330
+ time.sleep(throttle)
331
+
332
+ return is_ok
333
+
334
+
335
+ def version_callback(value: bool):
336
+ try:
337
+ __version__ = version("git-multi-status")
338
+ except PackageNotFoundError:
339
+ __version__ = "dev"
340
+
341
+ if value:
342
+ print(__version__)
343
+ raise typer.Exit()
344
+
345
+
346
+ @app.command()
347
+ def main(
348
+ dir: Annotated[str, typer.Argument(..., help="Dir to scan")] = ".",
349
+ warn_not_repo: Annotated[bool, typer.Option("-w", help="Warn about dirs that are not Git repositories")] = False,
350
+ exclude_ok: Annotated[bool, typer.Option("-e", "--no-ok", help="Exclude repos that are 'ok'")] = False,
351
+ do_fetch: Annotated[bool, typer.Option("-f", help="Do a 'git fetch' on each repo (slow for many repos)")] = False,
352
+ throttle: Annotated[
353
+ int, typer.Option("--throttle", help="Wait SEC seconds between each 'git fetch' (-f option)")
354
+ ] = 0,
355
+ depth: Annotated[
356
+ int, typer.Option("-d", "--depth", help="Scan depth: 0=no recursion, -1=unlimited, >0=max depth")
357
+ ] = 2,
358
+ flatten: Annotated[bool, typer.Option("--flatten", help="Show only one status per line")] = False,
359
+ show_branch: Annotated[bool, typer.Option("-b", help="Show currently checked out branch")] = False,
360
+ no_push: Annotated[bool, typer.Option("--no-push", help="Limit output: hide push status")] = False,
361
+ no_pull: Annotated[bool, typer.Option("--no-pull", help="Limit output: hide pull status")] = False,
362
+ no_upstream: Annotated[bool, typer.Option("--no-upstream", help="Limit output: hide upstream status")] = False,
363
+ no_uncommitted: Annotated[
364
+ bool, typer.Option("--no-uncommitted", help="Limit output: hide uncommitted changes")
365
+ ] = False,
366
+ no_untracked: Annotated[bool, typer.Option("--no-untracked", help="Limit output: hide untracked files")] = False,
367
+ no_stashes: Annotated[bool, typer.Option("--no-stashes", help="Limit output: hide stashes")] = False,
368
+ _: Annotated[bool, typer.Option("-v", "--version", callback=version_callback, is_eager=True)] = None,
369
+ __: Annotated[bool, typer.Option("--debug", help="Enable debug output", callback=debug_callback)] = False,
370
+ ):
371
+ """
372
+ git-multi-status shows uncommitted, untracked and unpushed changes in multiple Git repositories.
373
+ """
374
+
375
+ # Convert relative path to absolute path based on current working directory
376
+ start_dir = os.path.abspath(dir)
377
+
378
+ debug(f"Starting directory: {start_dir}")
379
+ debug(f"Current working directory: {os.getcwd()}")
380
+
381
+ # Process directory using absolute path
382
+ repos = find_git_repos(start_dir, depth, warn_not_repo)
383
+
384
+ debug(f"Found repositories: {repos}")
385
+
386
+ all_repos_ok = True # Track if all repos are OK
387
+
388
+ for repo in repos:
389
+ if os.path.isdir(os.path.join(repo, ".git")):
390
+ repo_ok = check_repo(
391
+ repo,
392
+ exclude_ok,
393
+ do_fetch,
394
+ throttle,
395
+ flatten,
396
+ show_branch,
397
+ no_push,
398
+ no_pull,
399
+ no_upstream,
400
+ no_uncommitted,
401
+ no_untracked,
402
+ no_stashes,
403
+ )
404
+ all_repos_ok = all_repos_ok and repo_ok
405
+
406
+ return typer.Exit(code=0 if all_repos_ok else 1)
407
+
408
+
409
+ if __name__ == "__main__":
410
+ app()
@@ -0,0 +1,12 @@
1
+ Metadata-Version: 2.4
2
+ Name: git-multi-status
3
+ Version: 0.0.1
4
+ Summary: Python port of multi-git-status
5
+ Requires-Python: >=3.10
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: rich>=14.0.0
8
+ Requires-Dist: typer>=0.15.2
9
+
10
+ # Git Multi Status
11
+
12
+ List the status of multiple Git repositories in a directory.
@@ -0,0 +1,9 @@
1
+ README.md
2
+ pyproject.toml
3
+ src/git_multi_status/__main__.py
4
+ src/git_multi_status.egg-info/PKG-INFO
5
+ src/git_multi_status.egg-info/SOURCES.txt
6
+ src/git_multi_status.egg-info/dependency_links.txt
7
+ src/git_multi_status.egg-info/entry_points.txt
8
+ src/git_multi_status.egg-info/requires.txt
9
+ src/git_multi_status.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ git-multi-status = git_multi_status.__main__:app
@@ -0,0 +1,2 @@
1
+ rich>=14.0.0
2
+ typer>=0.15.2
@@ -0,0 +1 @@
1
+ git_multi_status