git-nearest 0.2.1__tar.gz → 0.3.0__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.
Files changed (28) hide show
  1. git_nearest-0.3.0/PKG-INFO +141 -0
  2. git_nearest-0.3.0/README.md +123 -0
  3. {git_nearest-0.2.1 → git_nearest-0.3.0}/pyproject.toml +2 -2
  4. {git_nearest-0.2.1 → git_nearest-0.3.0}/src/git_nearest/__init__.py +1 -1
  5. git_nearest-0.3.0/src/git_nearest/cli.py +164 -0
  6. {git_nearest-0.2.1 → git_nearest-0.3.0}/src/git_nearest/gitutil.py +2 -2
  7. git_nearest-0.3.0/src/git_nearest/graph.py +239 -0
  8. git_nearest-0.3.0/src/git_nearest/refs.py +86 -0
  9. git_nearest-0.3.0/src/git_nearest/tui.py +317 -0
  10. git_nearest-0.3.0/tests/test_cli.py +146 -0
  11. git_nearest-0.3.0/tests/test_graph.py +160 -0
  12. git_nearest-0.3.0/tests/test_interactive.py +91 -0
  13. git_nearest-0.3.0/tests/test_refs.py +55 -0
  14. {git_nearest-0.2.1 → git_nearest-0.3.0}/tests/test_status.py +11 -6
  15. git_nearest-0.2.1/PKG-INFO +0 -140
  16. git_nearest-0.2.1/README.md +0 -122
  17. git_nearest-0.2.1/src/git_nearest/cli.py +0 -77
  18. git_nearest-0.2.1/src/git_nearest/graph.py +0 -160
  19. git_nearest-0.2.1/src/git_nearest/refs.py +0 -43
  20. git_nearest-0.2.1/src/git_nearest/table.py +0 -19
  21. git_nearest-0.2.1/tests/test_cli.py +0 -115
  22. git_nearest-0.2.1/tests/test_graph.py +0 -90
  23. {git_nearest-0.2.1 → git_nearest-0.3.0}/.gitignore +0 -0
  24. {git_nearest-0.2.1 → git_nearest-0.3.0}/LICENSE +0 -0
  25. {git_nearest-0.2.1 → git_nearest-0.3.0}/src/git_nearest/__main__.py +0 -0
  26. {git_nearest-0.2.1 → git_nearest-0.3.0}/src/git_nearest/color.py +0 -0
  27. {git_nearest-0.2.1 → git_nearest-0.3.0}/src/git_nearest/status.py +0 -0
  28. {git_nearest-0.2.1 → git_nearest-0.3.0}/tests/conftest.py +0 -0
@@ -0,0 +1,141 @@
1
+ Metadata-Version: 2.5
2
+ Name: git-nearest
3
+ Version: 0.3.0
4
+ Summary: Explore nearby Git branches and commits in a compact, optionally interactive map.
5
+ Project-URL: Homepage, https://github.com/hwei/git-nearest
6
+ Project-URL: Issues, https://github.com/hwei/git-nearest/issues
7
+ Author-email: hwei <814065+hwei@users.noreply.github.com>
8
+ License: MIT
9
+ License-File: LICENSE
10
+ Keywords: branch,cli,git,merge-base,parent-branch
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Topic :: Software Development :: Version Control :: Git
16
+ Requires-Python: >=3.8
17
+ Description-Content-Type: text/markdown
18
+
19
+ # git-nearest
20
+
21
+ A compact Git graph of the branches closest to HEAD or another commit. Run `git nearest` for a
22
+ quick view of the neighborhood, or `git nearest -i` to explore it in your terminal.
23
+
24
+ <img src="https://raw.githubusercontent.com/hwei/git-nearest/main/docs/img/graph.svg" alt="git nearest showing the graph of a local branch and nearby remote-tracking branches">
25
+
26
+ <details><summary>as text</summary>
27
+
28
+ ```console
29
+ $ git nearest
30
+ @ ae22273d HEAD -> fix-typo [1 staged, 1 untracked]
31
+ ~ (1)
32
+ ○ 574e9395 origin/main [nearest]
33
+ ├─╮
34
+ ~ │ (3)
35
+ │ │ ○ 2cf4c0c2 origin/release/1.2
36
+ ├─┼─╯
37
+ ○ │ fc1afa3b merge-base
38
+ ~ │ (1)
39
+ │ ○ 51eef8f5 origin/feature/login
40
+ │ ~ (2)
41
+ ├─╯
42
+ ○ 5a42fea0 merge-base
43
+ ~ (n) = n commits folded between
44
+ ```
45
+ </details>
46
+
47
+ `@` marks the view center. The graph highlights the nearest branch tips and keeps merge-bases
48
+ visible. A row such as `~ (3)` folds three commits that you can expand as needed. The working tree
49
+ note next to HEAD shows whether there are staged, modified, untracked or conflicted files.
50
+
51
+ The example is generated from a synthetic repository. [Demo script](https://github.com/hwei/git-nearest/blob/main/scripts/demo.py)
52
+
53
+ ## Install
54
+
55
+ Needs Python 3.8+ and git. No other dependencies.
56
+
57
+ ```console
58
+ uv tool install git-nearest # or: pipx install git-nearest
59
+ ```
60
+
61
+ The package installs an executable called `git-nearest`; git runs any `git-<name>` on your `PATH` as
62
+ `git <name>`.
63
+
64
+ ## Usage
65
+
66
+ ```
67
+ git nearest [N] [-b REV] [--match REGEX] [--expand REV]... [--details REV] [-i]
68
+ [--no-status] [--color {auto,always,never}] [--no-color] [--version]
69
+ ```
70
+
71
+ | | |
72
+ |---|---|
73
+ | `N` | number of distinct branch tip commits to show (default 5) |
74
+ | `-b`, `--branch REV` | center the view on this branch or commit (default HEAD) |
75
+ | `--match REGEX` | select branches by a regular expression on their full ref names |
76
+ | `--expand REV` | show the commits in the fold below REV (repeatable) |
77
+ | `--details REV` | show the commit subject, author, time, SHA, and parents for REV |
78
+ | `-i`, `--interactive` | explore the graph with the keyboard |
79
+ | `--no-status` | skip the working tree check (it runs `git status`, which can be slow on huge repositories) |
80
+ | `--color` | `auto` (default) colors only on a terminal and respects `NO_COLOR` |
81
+ | `--version` | print the version and exit |
82
+
83
+ By default, the candidates are all remote-tracking branches. With `--match`, the pattern is
84
+ searched against the full ref names of local and remote-tracking branches. The filter applies before
85
+ selecting the nearest tips. Branches that point to the same commit share one place in the result.
86
+
87
+ ```sh
88
+ git nearest --match '^refs/remotes/origin/(main$|release/)'
89
+ git nearest --match '^refs/heads/'
90
+ git nearest -b origin/main --expand origin/main --details origin/main
91
+ ```
92
+
93
+ ## Interactive mode
94
+
95
+ Run `git nearest -i` in a terminal. The initial view comes from the same options as command mode.
96
+ Use the keys below to change that view. Quitting prints the final graph into your terminal scrollback.
97
+
98
+ | Key | Action |
99
+ |---|---|
100
+ | `↑` / `↓` or `k` / `j` | Select a commit or fold |
101
+ | `Enter` | Center the view on the selected commit |
102
+ | `g` | Jump to a branch or commit |
103
+ | `f` | Edit the branch regex filter |
104
+ | `n` | Edit the number of distinct tips to show |
105
+ | `Backspace` | Return to the previous view |
106
+ | `Home` | Return to the checked-out HEAD |
107
+ | `Space` | Expand or collapse the selected fold |
108
+ | `i` | Toggle details for the selected commit |
109
+ | `q` | Quit and leave the final graph in the terminal |
110
+
111
+ Centering the view is a read-only operation. Press `Esc` to cancel a prompt or `Ctrl+U` to clear its
112
+ input. Use the command-line options to render the same view directly from the shell.
113
+
114
+ ## How it works
115
+
116
+ Git records ancestry through commits. The closest tip is the one that leaves the fewest commits
117
+ exclusive to the view center, then the fewest commits exclusive to the tip. A branch that has absorbed
118
+ the center's history through a merge can rank above the branch it originally split from. The graph
119
+ shows newest commits first while keeping children above their parents. Fold counts show how many
120
+ commits are hidden in that section of the graph.
121
+
122
+ Remote-tracking branches come from your local repository. Run `git fetch` to update them.
123
+ If no branches match, the graph still shows the view center.
124
+
125
+ ## Similar tools
126
+
127
+ - Scripts based on `git show-branch` or on grepping `git log --decorate` for `origin/` (the usual
128
+ Stack Overflow answers) look only at the first decorated ancestor, so they miss ties.
129
+ - [Git Town](https://www.git-town.com/) records a parent for each branch when it creates the branch.
130
+ That is exact but only works for branches it knows about; `git-nearest` infers from history and needs
131
+ no setup.
132
+
133
+ ## Development
134
+
135
+ ```console
136
+ uv run pytest
137
+ ```
138
+
139
+ ## License
140
+
141
+ MIT
@@ -0,0 +1,123 @@
1
+ # git-nearest
2
+
3
+ A compact Git graph of the branches closest to HEAD or another commit. Run `git nearest` for a
4
+ quick view of the neighborhood, or `git nearest -i` to explore it in your terminal.
5
+
6
+ <img src="https://raw.githubusercontent.com/hwei/git-nearest/main/docs/img/graph.svg" alt="git nearest showing the graph of a local branch and nearby remote-tracking branches">
7
+
8
+ <details><summary>as text</summary>
9
+
10
+ ```console
11
+ $ git nearest
12
+ @ ae22273d HEAD -> fix-typo [1 staged, 1 untracked]
13
+ ~ (1)
14
+ ○ 574e9395 origin/main [nearest]
15
+ ├─╮
16
+ ~ │ (3)
17
+ │ │ ○ 2cf4c0c2 origin/release/1.2
18
+ ├─┼─╯
19
+ ○ │ fc1afa3b merge-base
20
+ ~ │ (1)
21
+ │ ○ 51eef8f5 origin/feature/login
22
+ │ ~ (2)
23
+ ├─╯
24
+ ○ 5a42fea0 merge-base
25
+ ~ (n) = n commits folded between
26
+ ```
27
+ </details>
28
+
29
+ `@` marks the view center. The graph highlights the nearest branch tips and keeps merge-bases
30
+ visible. A row such as `~ (3)` folds three commits that you can expand as needed. The working tree
31
+ note next to HEAD shows whether there are staged, modified, untracked or conflicted files.
32
+
33
+ The example is generated from a synthetic repository. [Demo script](https://github.com/hwei/git-nearest/blob/main/scripts/demo.py)
34
+
35
+ ## Install
36
+
37
+ Needs Python 3.8+ and git. No other dependencies.
38
+
39
+ ```console
40
+ uv tool install git-nearest # or: pipx install git-nearest
41
+ ```
42
+
43
+ The package installs an executable called `git-nearest`; git runs any `git-<name>` on your `PATH` as
44
+ `git <name>`.
45
+
46
+ ## Usage
47
+
48
+ ```
49
+ git nearest [N] [-b REV] [--match REGEX] [--expand REV]... [--details REV] [-i]
50
+ [--no-status] [--color {auto,always,never}] [--no-color] [--version]
51
+ ```
52
+
53
+ | | |
54
+ |---|---|
55
+ | `N` | number of distinct branch tip commits to show (default 5) |
56
+ | `-b`, `--branch REV` | center the view on this branch or commit (default HEAD) |
57
+ | `--match REGEX` | select branches by a regular expression on their full ref names |
58
+ | `--expand REV` | show the commits in the fold below REV (repeatable) |
59
+ | `--details REV` | show the commit subject, author, time, SHA, and parents for REV |
60
+ | `-i`, `--interactive` | explore the graph with the keyboard |
61
+ | `--no-status` | skip the working tree check (it runs `git status`, which can be slow on huge repositories) |
62
+ | `--color` | `auto` (default) colors only on a terminal and respects `NO_COLOR` |
63
+ | `--version` | print the version and exit |
64
+
65
+ By default, the candidates are all remote-tracking branches. With `--match`, the pattern is
66
+ searched against the full ref names of local and remote-tracking branches. The filter applies before
67
+ selecting the nearest tips. Branches that point to the same commit share one place in the result.
68
+
69
+ ```sh
70
+ git nearest --match '^refs/remotes/origin/(main$|release/)'
71
+ git nearest --match '^refs/heads/'
72
+ git nearest -b origin/main --expand origin/main --details origin/main
73
+ ```
74
+
75
+ ## Interactive mode
76
+
77
+ Run `git nearest -i` in a terminal. The initial view comes from the same options as command mode.
78
+ Use the keys below to change that view. Quitting prints the final graph into your terminal scrollback.
79
+
80
+ | Key | Action |
81
+ |---|---|
82
+ | `↑` / `↓` or `k` / `j` | Select a commit or fold |
83
+ | `Enter` | Center the view on the selected commit |
84
+ | `g` | Jump to a branch or commit |
85
+ | `f` | Edit the branch regex filter |
86
+ | `n` | Edit the number of distinct tips to show |
87
+ | `Backspace` | Return to the previous view |
88
+ | `Home` | Return to the checked-out HEAD |
89
+ | `Space` | Expand or collapse the selected fold |
90
+ | `i` | Toggle details for the selected commit |
91
+ | `q` | Quit and leave the final graph in the terminal |
92
+
93
+ Centering the view is a read-only operation. Press `Esc` to cancel a prompt or `Ctrl+U` to clear its
94
+ input. Use the command-line options to render the same view directly from the shell.
95
+
96
+ ## How it works
97
+
98
+ Git records ancestry through commits. The closest tip is the one that leaves the fewest commits
99
+ exclusive to the view center, then the fewest commits exclusive to the tip. A branch that has absorbed
100
+ the center's history through a merge can rank above the branch it originally split from. The graph
101
+ shows newest commits first while keeping children above their parents. Fold counts show how many
102
+ commits are hidden in that section of the graph.
103
+
104
+ Remote-tracking branches come from your local repository. Run `git fetch` to update them.
105
+ If no branches match, the graph still shows the view center.
106
+
107
+ ## Similar tools
108
+
109
+ - Scripts based on `git show-branch` or on grepping `git log --decorate` for `origin/` (the usual
110
+ Stack Overflow answers) look only at the first decorated ancestor, so they miss ties.
111
+ - [Git Town](https://www.git-town.com/) records a parent for each branch when it creates the branch.
112
+ That is exact but only works for branches it knows about; `git-nearest` infers from history and needs
113
+ no setup.
114
+
115
+ ## Development
116
+
117
+ ```console
118
+ uv run pytest
119
+ ```
120
+
121
+ ## License
122
+
123
+ MIT
@@ -4,8 +4,8 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "git-nearest"
7
- version = "0.2.1"
8
- description = "Find the remote branches closest to your current branch, with ahead/behind counts and a compact jj-style graph."
7
+ version = "0.3.0"
8
+ description = "Explore nearby Git branches and commits in a compact, optionally interactive map."
9
9
  readme = "README.md"
10
10
  license = { text = "MIT" }
11
11
  requires-python = ">=3.8"
@@ -1,3 +1,3 @@
1
1
  """Find the remote branches closest to HEAD."""
2
2
 
3
- __version__ = "0.2.1"
3
+ __version__ = "0.3.0"
@@ -0,0 +1,164 @@
1
+ import argparse
2
+ from collections import Counter
3
+ from dataclasses import dataclass, replace
4
+ import os
5
+ import re
6
+ import sys
7
+ from typing import Optional, Tuple
8
+
9
+ from . import __version__, color, graph, refs, status, tui
10
+ from .color import Painter
11
+ from .gitutil import GitError, git
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class Options:
16
+ limit: int = 5
17
+ rev: str = "HEAD"
18
+ pattern: Optional[str] = None
19
+ expanded: Tuple[str, ...] = ()
20
+ details: Optional[str] = None
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class View:
25
+ state: Options
26
+ center: str
27
+ rows: Tuple[graph.Row, ...]
28
+
29
+
30
+ def _parser():
31
+ parser = argparse.ArgumentParser(
32
+ prog="git nearest",
33
+ description="Draw a compact map of the branches closest to a Git commit.",
34
+ )
35
+ parser.add_argument("limit", nargs="?", type=int, default=5,
36
+ help="how many distinct branch tips to show (default: 5)")
37
+ parser.add_argument("-b", "--branch", metavar="REV", default="HEAD",
38
+ help="center the map on this branch or commit (default: HEAD)")
39
+ parser.add_argument("--match", metavar="REGEX",
40
+ help="match full local and remote branch ref names; without this, show remote branches")
41
+ parser.add_argument("--expand", metavar="REV", action="append", default=[],
42
+ help="unfold the history below this commit in the map (repeatable)")
43
+ parser.add_argument("--details", metavar="REV", help="show this commit's details")
44
+ parser.add_argument("-i", "--interactive", action="store_true",
45
+ help="explore the map interactively; leave the final map in the terminal")
46
+ parser.add_argument("--color", choices=["auto", "always", "never"], default="auto")
47
+ parser.add_argument("--no-color", dest="color", action="store_const", const="never",
48
+ help="same as --color=never")
49
+ parser.add_argument("--no-status", action="store_true",
50
+ help="don't check the working tree (faster on huge repos)")
51
+ parser.add_argument("--version", action="version", version="git-nearest " + __version__)
52
+ return parser
53
+
54
+
55
+ def _resolve(rev):
56
+ args = ("rev-parse", "--verify", "--end-of-options", rev + "^{commit}")
57
+ if rev == "HEAD":
58
+ return git(*args)
59
+ oid = git(*args, check=False)
60
+ if oid:
61
+ return oid
62
+ raise GitError("not a valid branch or commit: " + _one_line(rev))
63
+
64
+
65
+ def _one_line(text):
66
+ return "".join(c if c.isprintable() else " " for c in text)
67
+
68
+
69
+ def _head_label():
70
+ branch = git("symbolic-ref", "--short", "-q", "HEAD", check=False)
71
+ return "HEAD -> " + branch if branch else "HEAD (detached)"
72
+
73
+
74
+ def _details(oid):
75
+ subject, author, date, parents = git(
76
+ "show", "-s", "--format=%s%x00%an%x00%aI%x00%P", oid, strip=False
77
+ ).rstrip("\n").split("\0")
78
+ return [
79
+ "Commit " + oid,
80
+ " " + _one_line(subject),
81
+ " Author " + _one_line(author),
82
+ " Date " + date,
83
+ " Parents " + (parents or "(root)"),
84
+ ]
85
+
86
+
87
+ def _load(state, paint, check_tree):
88
+ try:
89
+ pattern = re.compile(state.pattern) if state.pattern is not None else None
90
+ except re.error as exc:
91
+ raise GitError("invalid branch regex: " + _one_line(str(exc))) from exc
92
+
93
+ center = _resolve(state.rev)
94
+ actual_head = center if state.rev == "HEAD" else git(
95
+ "rev-parse", "--verify", "--end-of-options", "HEAD^{commit}", check=False
96
+ )
97
+ skip = git("rev-parse", "--verify", "--symbolic-full-name", "--end-of-options", state.rev, check=False)
98
+ ranked = refs.rank(state.limit, center, skip, pattern=pattern)
99
+
100
+ names = {}
101
+ nearest = set()
102
+ labels = Counter(row.ref for row in ranked)
103
+ for row in ranked:
104
+ name = row.full_ref if labels[row.ref] > 1 else row.ref
105
+ names.setdefault(row.oid, []).append(name)
106
+ if (row.ahead, row.behind) == (ranked[0].ahead, ranked[0].behind):
107
+ nearest.add(row.oid)
108
+
109
+ expanded = tuple(dict.fromkeys(_resolve(rev) for rev in state.expanded))
110
+ detail_oid = _resolve(state.details) if state.details is not None else None
111
+ state = replace(state, expanded=expanded, details=detail_oid)
112
+ details = (detail_oid, _details(detail_oid)) if detail_oid else None
113
+ if state.rev == "HEAD":
114
+ label = _head_label()
115
+ else:
116
+ label = _one_line(state.rev) + (" [HEAD]" if center == actual_head else "")
117
+ note = status.describe(status.read(), paint) if state.rev == "HEAD" and check_tree else None
118
+
119
+ rows = list(graph.render_map(
120
+ names, paint, center, label, note, actual_head=actual_head,
121
+ nearest=nearest, expanded=expanded, details=details,
122
+ ))
123
+ if actual_head and actual_head != center and not any(row.oid == actual_head for row in rows):
124
+ rows.append(graph.Row(paint(color.DIM, _head_label() + " (outside map)"), None, "text"))
125
+ if not ranked:
126
+ message = ("No branches match the filter." if pattern is not None else
127
+ "No remote branches found (try git fetch or --match '^refs/heads/').")
128
+ rows.append(graph.Row(paint(color.DIM, message), None, "text"))
129
+ return View(state, center, tuple(rows))
130
+
131
+
132
+ def _use_color(mode):
133
+ if mode == "always":
134
+ return True
135
+ return mode == "auto" and sys.stdout.isatty() and not os.environ.get("NO_COLOR")
136
+
137
+
138
+ def main(argv=None):
139
+ parser = _parser()
140
+ args = parser.parse_args(argv)
141
+ if args.limit < 1:
142
+ parser.error("limit must be at least 1")
143
+ if args.interactive and not (sys.stdin.isatty() and sys.stdout.isatty()):
144
+ parser.error("-i requires an interactive terminal")
145
+ if os.name == "nt" and sys.stdout.isatty():
146
+ os.system("") # enables ANSI handling in the legacy Windows console
147
+ if not sys.stdout.isatty() and hasattr(sys.stdout, "reconfigure"):
148
+ sys.stdout.reconfigure(encoding="utf-8")
149
+
150
+ paint = Painter(_use_color(args.color))
151
+ state = Options(args.limit, args.branch, args.match, tuple(args.expand), args.details)
152
+
153
+ def reload_view(options):
154
+ return _load(options, paint, check_tree=not args.no_status)
155
+
156
+ try:
157
+ view = reload_view(state)
158
+ if args.interactive:
159
+ view = tui.run(view, reload_view)
160
+ except GitError as exc:
161
+ print("git-nearest: " + str(exc), file=sys.stderr)
162
+ return 1
163
+ print("\n".join(row.text for row in view.rows))
164
+ return 0
@@ -6,14 +6,14 @@ class GitError(Exception):
6
6
  pass
7
7
 
8
8
 
9
- def git(*args, check=True, strip=True):
9
+ def git(*args, check=True, strip=True, input=None):
10
10
  """Run git and return stdout (stripped unless strip is False).
11
11
 
12
12
  On failure raise GitError, or return "" when check is False.
13
13
  """
14
14
  try:
15
15
  p = subprocess.run(
16
- ["git", *args], capture_output=True, text=True, encoding="utf-8", errors="replace"
16
+ ["git", *args], input=input, capture_output=True, text=True, encoding="utf-8", errors="replace"
17
17
  )
18
18
  except FileNotFoundError:
19
19
  raise GitError("git executable not found")