git-merge-list 0.0.1__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.
@@ -0,0 +1,5 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Junbo Zheng
3
+ """git-merge-list: list commits merged within a time range across git repos."""
4
+
5
+ __version__ = "0.0.1"
git_merge_list/cli.py ADDED
@@ -0,0 +1,162 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Junbo Zheng
3
+ """CLI entry point for git-merge-list."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import argparse
8
+ import sys
9
+ from datetime import datetime
10
+ from importlib.metadata import PackageNotFoundError, version
11
+
12
+ from . import __version__
13
+ from .discover import find_repos
14
+ from .gerrit import derive_base, get_remote_url
15
+ from .output import print_terminal, render_markdown
16
+ from .query import query_repo
17
+ from .timeparse import build_range
18
+
19
+ PKG = "git-merge-list"
20
+
21
+
22
+ def _version() -> str:
23
+ try:
24
+ return version(PKG)
25
+ except PackageNotFoundError:
26
+ return __version__
27
+
28
+
29
+ def _build_parser() -> argparse.ArgumentParser:
30
+ p = argparse.ArgumentParser(
31
+ prog="git-merge-list",
32
+ description=(
33
+ "Recursively scan git repos under a path and list commits merged "
34
+ "within a time range (by committer date), with Gerrit patch links."
35
+ ),
36
+ )
37
+ p.add_argument(
38
+ "path",
39
+ nargs="?",
40
+ default=".",
41
+ help="root path to scan for git repos (default: current directory)",
42
+ )
43
+ time_grp = p.add_argument_group("time selector (pick one)")
44
+ time_grp.add_argument("--day", help="YYYY-MM-DD — the whole calendar day")
45
+ time_grp.add_argument("--hour", help="'YYYY-MM-DD HH' — the whole calendar hour")
46
+ time_grp.add_argument(
47
+ "--since",
48
+ help="start time (inclusive), e.g. '2026-07-05' or " "'2026-07-05 14:00'",
49
+ )
50
+ time_grp.add_argument(
51
+ "--until",
52
+ help="end time (exclusive-ish, inclusive in git). "
53
+ "Defaults to now when only --since is given.",
54
+ )
55
+ p.add_argument(
56
+ "--tz",
57
+ help="timezone for the selectors: '+0800', '+08:00', 'Z', or an "
58
+ "IANA name like 'Asia/Shanghai'. Defaults to system local.",
59
+ )
60
+ p.add_argument(
61
+ "--author",
62
+ help="regex matched against author name/email (the 'submitter'). "
63
+ "Use --by-committer to match committer instead.",
64
+ )
65
+ p.add_argument(
66
+ "--by-committer",
67
+ action="store_true",
68
+ help="show committer (not author) as the 'submitter' column. In "
69
+ "Gerrit flows the author is usually the developer; the committer "
70
+ "is often the merge bot.",
71
+ )
72
+ p.add_argument("--max-count", type=int, help="per-repo commit cap")
73
+ p.add_argument(
74
+ "--reverse", action="store_true", help="oldest-first within each repo"
75
+ )
76
+ p.add_argument(
77
+ "-o",
78
+ "--output",
79
+ help="Markdown report path. Defaults to "
80
+ "git-merge-list-report-<timestamp>.md. Use with --no-markdown to "
81
+ "suppress the file entirely.",
82
+ )
83
+ p.add_argument(
84
+ "--no-markdown",
85
+ action="store_true",
86
+ help="do not write a Markdown report file",
87
+ )
88
+ p.add_argument(
89
+ "-V",
90
+ "--version",
91
+ action="version",
92
+ version=f"{PKG} {_version()}",
93
+ )
94
+ return p
95
+
96
+
97
+ def main(argv: list[str] | None = None) -> int:
98
+ args = _build_parser().parse_args(argv)
99
+
100
+ try:
101
+ since, until = build_range(
102
+ day=args.day,
103
+ hour=args.hour,
104
+ since=args.since,
105
+ until=args.until,
106
+ tz_arg=args.tz,
107
+ )
108
+ except ValueError as e:
109
+ print(f"error: {e}", file=sys.stderr)
110
+ return 2
111
+
112
+ repos = find_repos(args.path)
113
+ if not repos:
114
+ print(f"no git repos found under {args.path}", file=sys.stderr)
115
+ return 1
116
+
117
+ grouped: list[tuple[str, list]] = []
118
+ total = 0
119
+ for repo in repos:
120
+ base = derive_base(get_remote_url(repo))
121
+ commits, err = query_repo(
122
+ repo,
123
+ since,
124
+ until,
125
+ author=args.author,
126
+ max_count=args.max_count,
127
+ reverse=args.reverse,
128
+ base_url=base,
129
+ )
130
+ if err:
131
+ print(f"warn: {repo}: {err}", file=sys.stderr)
132
+ if commits:
133
+ grouped.append((repo, commits))
134
+ total += len(commits)
135
+
136
+ print_terminal(
137
+ grouped,
138
+ by_committer=args.by_committer,
139
+ since=since,
140
+ until=until,
141
+ )
142
+
143
+ if not args.no_markdown:
144
+ out_path = args.output or (
145
+ f"git-merge-list-report-" f"{datetime.now().strftime('%Y%m%d-%H%M%S')}.md"
146
+ )
147
+ md = render_markdown(
148
+ grouped,
149
+ by_committer=args.by_committer,
150
+ since=since,
151
+ until=until,
152
+ root=args.path,
153
+ )
154
+ with open(out_path, "w", encoding="utf-8") as f:
155
+ f.write(md)
156
+ print(f"report: {out_path}", file=sys.stderr)
157
+
158
+ return 0 if total > 0 else 0
159
+
160
+
161
+ if __name__ == "__main__":
162
+ raise SystemExit(main())
@@ -0,0 +1,36 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Junbo Zheng
3
+ """Recursively discover git repos under a path.
4
+
5
+ A "repo" is any directory that contains a `.git` entry — either a `.git`
6
+ directory (normal checkout) or a `.git` file (worktree / submodule). This
7
+ covers both standalone repos and the many individual git repos created by
8
+ the `repo` tool, since each checked-out project is itself a normal git repo.
9
+
10
+ We never descend into `.git` directories or the `.repo/` metadata directory,
11
+ but we DO keep walking a found repo's subdirectories so nested submodules
12
+ are picked up too.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import os
18
+
19
+ # Directory names we never recurse into.
20
+ SKIP_DIR_NAMES = {".git", ".repo"}
21
+
22
+
23
+ def find_repos(root: str) -> list[str]:
24
+ """Return repo-root paths under `root`, in walk order, deduplicated."""
25
+ repos: list[str] = []
26
+ seen: set[str] = set()
27
+ for dirpath, dirnames, filenames in os.walk(root):
28
+ # Detect BEFORE pruning: .git is itself in SKIP_DIR_NAMES, so if we
29
+ # pruned first the membership check below would always be False.
30
+ is_repo = ".git" in dirnames or ".git" in filenames
31
+ # Prune the walk so we don't enter .git/.repo subtrees.
32
+ dirnames[:] = [d for d in dirnames if d not in SKIP_DIR_NAMES]
33
+ if is_repo and dirpath not in seen:
34
+ seen.add(dirpath)
35
+ repos.append(dirpath)
36
+ return repos
@@ -0,0 +1,81 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Junbo Zheng
3
+ """Derive a Gerrit patch URL from a repo's remote URL + a commit's Change-Id.
4
+
5
+ The remote URL gives us the Gerrit host; the commit message's `Change-Id`
6
+ gives us a searchable token. We build `https://<host>/q/<Change-Id>`, which
7
+ is Gerrit's search-redirect URL — clickable, no network/auth needed at query
8
+ time. When a commit has no Change-Id we fall back to the commit hash, which
9
+ Gerrit can also search on.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import re
15
+ import subprocess
16
+ from urllib.parse import urlparse
17
+
18
+ # scp-like syntax: [user@]host:path (no scheme)
19
+ _SCP_RE = re.compile(r"^(?:[^@/\s]+@)?([^:/\s]+):")
20
+
21
+
22
+ def derive_base(remote_url: str) -> str | None:
23
+ """Return `https://<host>[:port]` for a Gerrit remote URL, or None."""
24
+ s = (remote_url or "").strip()
25
+ if not s:
26
+ return None
27
+ if s.startswith(("ssh://", "http://", "https://")):
28
+ parsed = urlparse(s)
29
+ host = parsed.hostname
30
+ if not host:
31
+ return None
32
+ netloc = host
33
+ port = parsed.port
34
+ # The ssh port (e.g. Gerrit's 29418) is for `git push`, not web
35
+ # browsing — the Gerrit web UI runs on https (443). So for ssh
36
+ # remotes we drop the port entirely. Only an https/http remote with
37
+ # a non-default port could be a web UI on a custom port, so keep it.
38
+ if parsed.scheme in ("https", "http"):
39
+ default = 443 if parsed.scheme == "https" else 80
40
+ if port and port != default:
41
+ netloc = f"{host}:{port}"
42
+ scheme = "https" if parsed.scheme in ("ssh", "https") else "http"
43
+ return f"{scheme}://{netloc}"
44
+ m = _SCP_RE.match(s)
45
+ if m:
46
+ return f"https://{m.group(1)}"
47
+ return None
48
+
49
+
50
+ def get_remote_url(repo: str) -> str:
51
+ """Return the origin (or first listed) remote URL for `repo`, or ''."""
52
+ try:
53
+ r = subprocess.run(
54
+ ["git", "-C", repo, "remote"],
55
+ capture_output=True,
56
+ text=True,
57
+ check=False,
58
+ )
59
+ except (FileNotFoundError, OSError):
60
+ return ""
61
+ remotes = r.stdout.split()
62
+ if not remotes:
63
+ return ""
64
+ name = "origin" if "origin" in remotes else remotes[0]
65
+ r2 = subprocess.run(
66
+ ["git", "-C", repo, "remote", "get-url", name],
67
+ capture_output=True,
68
+ text=True,
69
+ check=False,
70
+ )
71
+ return r2.stdout.strip()
72
+
73
+
74
+ def patch_url(base: str | None, change_id: str, commit_hash: str) -> str:
75
+ """Build a Gerrit search URL for the change, falling back to the hash."""
76
+ if not base:
77
+ return ""
78
+ token = change_id or commit_hash
79
+ if not token:
80
+ return ""
81
+ return f"{base}/q/{token}"
@@ -0,0 +1,130 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Junbo Zheng
3
+ """Render query results: a colored terminal table + a Markdown report file.
4
+
5
+ Terminal coloring is gated on `stdout.isatty()` and the NO_COLOR convention
6
+ (https://no-color.org). When color is off, output is plain text that still
7
+ reads correctly — color is never the only signal.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ import sys
14
+ from datetime import datetime
15
+
16
+ from .query import Commit
17
+
18
+ # Column width caps (terminal table only).
19
+ W_PERSON = 18
20
+ W_TIME = 25
21
+ W_PATCH = 48
22
+ W_SUBJECT = 50
23
+
24
+ HEADER = ["Merge time", "Patch", "Submitter", "Subject"]
25
+
26
+
27
+ def _color_enabled() -> bool:
28
+ if "NO_COLOR" in os.environ:
29
+ return False
30
+ return sys.stdout.isatty()
31
+
32
+
33
+ def _c(text: str, code: str, enabled: bool) -> str:
34
+ return f"\033[{code}m{text}\033[0m" if enabled else text
35
+
36
+
37
+ def _trunc(s: str, width: int) -> str:
38
+ return s if len(s) <= width else s[: width - 1] + "…"
39
+
40
+
41
+ def _person(c: Commit, by_committer: bool) -> str:
42
+ name = c.committer_name if by_committer else c.author_name
43
+ email = c.committer_email if by_committer else c.author_email
44
+ return f"{name} <{email}>"
45
+
46
+
47
+ def _patch_label(c: Commit) -> str:
48
+ # Short token for the patch link: prefer Change-Id, fall back to commit hash.
49
+ # The full token is already carried in the URL (https://<host>/q/<token>),
50
+ # so the link text only needs a short identifier.
51
+ if c.change_id:
52
+ return c.change_id[:11]
53
+ if c.patch_url:
54
+ return c.hash[:11]
55
+ return ""
56
+
57
+
58
+ def print_terminal(
59
+ grouped: list[tuple[str, list[Commit]]],
60
+ *,
61
+ by_committer: bool,
62
+ since: str | None,
63
+ until: str | None,
64
+ ) -> None:
65
+ enabled = _color_enabled()
66
+ rng = until if until else "now"
67
+ print(_c("git-merge-list", "1;36", enabled) + f" range: {since} .. {rng}")
68
+ total = sum(len(cs) for _, cs in grouped)
69
+ print(f"{total} commit(s) across {len(grouped)} repo(s)\n")
70
+
71
+ for repo, commits in grouped:
72
+ print(_c(repo, "1;33", enabled) + f" ({len(commits)})")
73
+ rows = [
74
+ [
75
+ _trunc(c.committer_date, W_TIME),
76
+ _trunc(c.patch_url, W_PATCH),
77
+ _trunc(_person(c, by_committer), W_PERSON),
78
+ _trunc(c.subject, W_SUBJECT),
79
+ ]
80
+ for c in commits
81
+ ]
82
+ widths = [
83
+ max(len(h), max((len(r[i]) for r in rows), default=0))
84
+ for i, h in enumerate(HEADER)
85
+ ]
86
+ fmt = " ".join(f"{{:<{w}}}" for w in widths)
87
+ print(" " + _c(fmt.format(*HEADER), "2", enabled))
88
+ for r in rows:
89
+ print(" " + fmt.format(*r))
90
+ print()
91
+
92
+
93
+ def render_markdown(
94
+ grouped: list[tuple[str, list[Commit]]],
95
+ *,
96
+ by_committer: bool,
97
+ since: str | None,
98
+ until: str | None,
99
+ root: str,
100
+ ) -> str:
101
+ rng = until if until else "now"
102
+ total = sum(len(cs) for _, cs in grouped)
103
+ person_col = "Committer" if by_committer else "Author"
104
+ lines = [
105
+ "# git-merge-list report",
106
+ "",
107
+ f"- **Path**: `{root}`",
108
+ f"- **Range**: `{since}` .. `{rng}`",
109
+ f"- **Total**: {total} commit(s) across {len(grouped)} repo(s)",
110
+ f"- **Generated**: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
111
+ "",
112
+ ]
113
+ if not grouped:
114
+ lines.append("_No commits in range._\n")
115
+ return "\n".join(lines)
116
+
117
+ for repo, commits in grouped:
118
+ lines.append(f"## `{repo}` ({len(commits)})")
119
+ lines.append("")
120
+ lines.append(f"| Merge time | Patch | {person_col} | Subject |")
121
+ lines.append("|---|---|---|---|")
122
+ for c in commits:
123
+ person = _person(c, by_committer).replace("|", "\\|")
124
+ subj = c.subject.replace("|", "\\|").replace("\n", " ")
125
+ patch = f"[{_patch_label(c)}]({c.patch_url})" if c.patch_url else "-"
126
+ lines.append(
127
+ f"| {c.committer_date} | {patch} | {person} | {subj} |"
128
+ )
129
+ lines.append("")
130
+ return "\n".join(lines)
@@ -0,0 +1,105 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Junbo Zheng
3
+ """Query commits from a single repo via `git log`, filtered by committer date.
4
+
5
+ `git log --since`/`--until` filter on the committer date (merge time), not the
6
+ author date — exactly the semantics the tool promises. We use a NUL-separated
7
+ `-z` output with a unit-separator field delimiter so commit bodies (which may
8
+ contain newlines) parse reliably.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import re
14
+ import subprocess
15
+ from dataclasses import dataclass
16
+
17
+ FIELD = "\x1f" # unit separator: between fields within one commit
18
+ CHANGE_ID_RE = re.compile(r"^\s*Change-Id:\s*(I[0-9a-f]{40})\s*$", re.MULTILINE)
19
+
20
+
21
+ @dataclass
22
+ class Commit:
23
+ repo: str
24
+ hash: str
25
+ author_name: str
26
+ author_email: str
27
+ committer_name: str
28
+ committer_email: str
29
+ committer_date: str # ISO 8601 from %cI
30
+ subject: str
31
+ change_id: str
32
+ patch_url: str
33
+
34
+
35
+ def query_repo(
36
+ repo: str,
37
+ since: str | None,
38
+ until: str | None,
39
+ *,
40
+ author: str | None = None,
41
+ max_count: int | None = None,
42
+ reverse: bool = False,
43
+ base_url: str | None = None,
44
+ ) -> tuple[list[Commit], str]:
45
+ """Return `(commits, stderr)`. `stderr` is '' on success.
46
+
47
+ `base_url` is the pre-derived Gerrit base for this repo; passing it in
48
+ keeps the gerrit module out of the hot loop.
49
+ """
50
+ fmt = FIELD.join(["%H", "%an", "%ae", "%cn", "%ce", "%cI", "%s", "%B"])
51
+ args: list[str] = [
52
+ "git",
53
+ "-C",
54
+ repo,
55
+ "log",
56
+ "-z",
57
+ f"--format={fmt}",
58
+ ]
59
+ if since:
60
+ args.append(f"--since={since}")
61
+ if until:
62
+ args.append(f"--until={until}")
63
+ if author:
64
+ args.append(f"--author={author}")
65
+ if max_count:
66
+ args.append(f"--max-count={max_count}")
67
+ if reverse:
68
+ args.append("--reverse")
69
+
70
+ res = subprocess.run(args, capture_output=True, text=True, check=False)
71
+ if res.returncode != 0:
72
+ return [], (res.stderr or f"git log failed (exit {res.returncode})").strip()
73
+
74
+ commits: list[Commit] = []
75
+ for rec in res.stdout.split("\x00"):
76
+ if not rec:
77
+ continue
78
+ parts = rec.split(FIELD)
79
+ if len(parts) < 8:
80
+ continue
81
+ h, an, ae, cn, ce, ci, subj, body = parts[:8]
82
+ m = CHANGE_ID_RE.search(body or "")
83
+ cid = m.group(1) if m else ""
84
+ commits.append(
85
+ Commit(
86
+ repo=repo,
87
+ hash=h,
88
+ author_name=an,
89
+ author_email=ae,
90
+ committer_name=cn,
91
+ committer_email=ce,
92
+ committer_date=ci,
93
+ subject=subj,
94
+ change_id=cid,
95
+ patch_url=gerrit_patch_url(base_url, cid, h),
96
+ )
97
+ )
98
+ return commits, ""
99
+
100
+
101
+ # Local import shim to avoid a circular import at module load time.
102
+ def gerrit_patch_url(base: str | None, cid: str, h: str) -> str:
103
+ from .gerrit import patch_url
104
+
105
+ return patch_url(base, cid, h)
@@ -0,0 +1,114 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Junbo Zheng
3
+ """Parse user-supplied time selectors into git `--since`/`--until` strings.
4
+
5
+ All ranges are interpreted in the local timezone unless `--tz` overrides it.
6
+ git's `--since`/`--until` filter on the committer date (merge time), which is
7
+ exactly what we want — not the author date (commit time).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import re
13
+ import time
14
+ from datetime import datetime, timedelta
15
+ from zoneinfo import ZoneInfo
16
+
17
+ DAY_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
18
+ HOUR_RE = re.compile(r"^(\d{4})-(\d{2})-(\d{2})[ T](\d{2})$")
19
+ OFFSET_RE = re.compile(r"[+-]\d{2}:?\d{2}$")
20
+
21
+
22
+ def local_offset_str() -> str:
23
+ """Return the system local offset as a git-style `+HHMM` string."""
24
+ is_dst = time.localtime().tm_isdst > 0
25
+ off = -time.altzone if is_dst else -time.timezone
26
+ sign = "+" if off >= 0 else "-"
27
+ off = abs(off)
28
+ return f"{sign}{off // 3600:02d}{(off % 3600) // 60:02d}"
29
+
30
+
31
+ def parse_tz(tz_arg: str | None) -> str:
32
+ """Resolve a `--tz` argument (or None) to a `+HHMM` string.
33
+
34
+ Accepts `+HHMM` / `+HH:MM` / `Z`, or an IANA zone name like
35
+ `Asia/Shanghai`. Falls back to the system offset on any parse failure.
36
+ """
37
+ if not tz_arg:
38
+ return local_offset_str()
39
+ arg = tz_arg.strip()
40
+ if arg.upper() == "Z":
41
+ return "+0000"
42
+ if arg.startswith(("+", "-")):
43
+ clean = arg.replace(":", "")
44
+ if len(clean) == 5:
45
+ return clean
46
+ if len(clean) == 3: # e.g. "+8" → "+0800"
47
+ return f"{clean[0]}0{clean[1:]}00"
48
+ return local_offset_str()
49
+ try:
50
+ off = ZoneInfo(arg).utcoffset(datetime.now())
51
+ total = int(off.total_seconds())
52
+ sign = "+" if total >= 0 else "-"
53
+ total = abs(total)
54
+ return f"{sign}{total // 3600:02d}{(total % 3600) // 60:02d}"
55
+ except Exception:
56
+ return local_offset_str()
57
+
58
+
59
+ def _ensure_tz(s: str, tz: str) -> str:
60
+ """Append the offset to a bare time string unless it already carries one."""
61
+ s = s.strip()
62
+ if OFFSET_RE.search(s) or s.endswith("Z"):
63
+ return s
64
+ if DAY_RE.match(s):
65
+ return f"{s} 00:00 {tz}"
66
+ return f"{s} {tz}"
67
+
68
+
69
+ def build_range(
70
+ *,
71
+ day: str | None,
72
+ hour: str | None,
73
+ since: str | None,
74
+ until: str | None,
75
+ tz_arg: str | None,
76
+ ) -> tuple[str | None, str | None]:
77
+ """Turn one of --day / --hour / --since(+--until) into `(since, until)`.
78
+
79
+ Raises ValueError on malformed input or on no time selector being given.
80
+ `until` is None when only `--since` is provided (means: since → now).
81
+ """
82
+ tz = parse_tz(tz_arg)
83
+ selectors = sum(bool(x) for x in (day, hour, since))
84
+ if selectors == 0:
85
+ raise ValueError("no time selector given; pass one of --day / --hour / --since")
86
+ if selectors > 1:
87
+ raise ValueError("--day / --hour / --since are mutually exclusive; pick one")
88
+
89
+ if day:
90
+ if not DAY_RE.match(day):
91
+ raise ValueError(f"--day expects YYYY-MM-DD, got: {day!r}")
92
+ start = datetime.strptime(day, "%Y-%m-%d")
93
+ end = start + timedelta(days=1)
94
+ return (
95
+ f"{start.strftime('%Y-%m-%d')} 00:00 {tz}",
96
+ f"{end.strftime('%Y-%m-%d')} 00:00 {tz}",
97
+ )
98
+
99
+ if hour:
100
+ m = HOUR_RE.match(hour)
101
+ if not m:
102
+ raise ValueError(f"--hour expects 'YYYY-MM-DD HH', got: {hour!r}")
103
+ y, mo, d, h = (int(x) for x in m.groups())
104
+ start = datetime(y, mo, d, h)
105
+ end = start + timedelta(hours=1)
106
+ return (
107
+ f"{start.strftime('%Y-%m-%d %H:%M')} {tz}",
108
+ f"{end.strftime('%Y-%m-%d %H:%M')} {tz}",
109
+ )
110
+
111
+ # --since (until optional)
112
+ since_str = _ensure_tz(since, tz)
113
+ until_str = _ensure_tz(until, tz) if until else None
114
+ return since_str, until_str
@@ -0,0 +1,192 @@
1
+ Metadata-Version: 2.4
2
+ Name: git-merge-list
3
+ Version: 0.0.1
4
+ Summary: Recursively scan git repos under a path and list commits merged within a time range (by committer date), with Gerrit patch links.
5
+ Project-URL: Homepage, https://github.com/Junbo-Zheng/git-merge-list
6
+ Project-URL: Issues, https://github.com/Junbo-Zheng/git-merge-list/issues
7
+ Author: Junbo Zheng
8
+ License: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: commits,gerrit,git,merge-log,repo
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Operating System :: MacOS
16
+ Classifier: Operating System :: POSIX :: Linux
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Topic :: Software Development :: Version Control :: Git
22
+ Requires-Python: >=3.10
23
+ Provides-Extra: dev
24
+ Requires-Dist: black; extra == 'dev'
25
+ Requires-Dist: build; extra == 'dev'
26
+ Requires-Dist: pytest-cov; extra == 'dev'
27
+ Requires-Dist: pytest>=7.0; extra == 'dev'
28
+ Requires-Dist: twine; extra == 'dev'
29
+ Description-Content-Type: text/markdown
30
+
31
+ # git-merge-list
32
+
33
+ ![PyPI](https://img.shields.io/pypi/v/git-merge-list)
34
+ ![PyPI - Downloads](https://img.shields.io/pypi/dm/git-merge-list)
35
+ ![License: Apache 2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg)
36
+ ![Python](https://img.shields.io/badge/python-3.10%2B-blue)
37
+
38
+ Recursively scan git repositories under a path and list commits **merged**
39
+ within a time range — by **committer date**, not author date — across every
40
+ repo it finds, with Gerrit patch links.
41
+
42
+ Built for the recurring question: _"a problem showed up; who landed what
43
+ into these repos in this window, and what are the patch links?"_
44
+
45
+ ## Why committer date
46
+
47
+ In a Gerrit workflow the **author date** is when the developer wrote the
48
+ patch; the **committer date** is when it actually landed on the branch
49
+ (merged / cherry-picked / rebased in). When you `git pull` / `repo sync`
50
+ to latest and ask "what got merged on July 5th", you want committer date.
51
+ `git log --since`/`--until` filter on committer date, so that is what this
52
+ tool uses.
53
+
54
+ ## Features
55
+
56
+ - **Three time selectors** (pick one): `--day`, `--hour`, or `--since`/`--until`.
57
+ - **Cross-repo by default**: recursively finds every `.git` under the path —
58
+ standalone repos **and** `repo`-tool-managed multi-repos. Nested submodules
59
+ are picked up too.
60
+ - **Gerrit patch links**: host derived from each repo's `origin` remote;
61
+ link is `https://<host>/q/<Change-Id>` (clickable, no network/auth needed).
62
+ - **Two outputs**: a colored terminal table grouped by repo, plus a Markdown
63
+ report file.
64
+ - **Zero runtime dependencies** — standard library only.
65
+
66
+ ## Install
67
+
68
+ Prerequisite: `git` must be on `PATH` (the tool shells out to `git log` /
69
+ `git config`). Python ≥ 3.10.
70
+
71
+ From PyPI:
72
+
73
+ ```bash
74
+ pip install git-merge-list
75
+ git-merge-list --version
76
+ ```
77
+
78
+ Editable install (for development, with test/lint deps):
79
+
80
+ ```bash
81
+ pip install -e ".[dev]"
82
+ ```
83
+
84
+ Or run from source with no install:
85
+
86
+ ```bash
87
+ ./main.py --version
88
+ ```
89
+
90
+ ## Usage
91
+
92
+ ```bash
93
+ # Whole calendar day (local timezone)
94
+ git-merge-list /path/to/workspace --day 2026-07-05
95
+
96
+ # Whole calendar hour
97
+ git-merge-list /path/to/workspace --hour "2026-07-05 14"
98
+
99
+ # Precise range (--until defaults to now when omitted)
100
+ git-merge-list /path/to/workspace --since "2026-07-05 14:00" --until "2026-07-05 15:30"
101
+
102
+ # Force a timezone for the selectors
103
+ git-merge-list . --day 2026-07-05 --tz Asia/Shanghai
104
+
105
+ # Filter by submitter; show committer instead of author
106
+ git-merge-list . --since "2026-07-05" --author "alice" --by-committer
107
+ ```
108
+
109
+ > [!NOTE]
110
+ > The tool only reads local state — it does not pull. Run `git pull` /
111
+ > `repo sync` to latest first.
112
+
113
+ ### Example
114
+
115
+ Terminal output (colors shown when stdout is a TTY and `NO_COLOR` is unset):
116
+
117
+ ```text
118
+ $ git-merge-list /path/to/workspace --day 2026-07-05
119
+ git-merge-list range: 2026-07-05 .. 2026-07-06
120
+ 3 commit(s) across 2 repo(s)
121
+
122
+ platform/native (2)
123
+ Merge time Patch Submitter Subject
124
+ 2026-07-05 09:12:33 +0800 https://gerrit.example.com/q/I1a2b3c4d5e6 Alice <a@x.example> Fix audio underrun on cold start
125
+ 2026-07-05 14:45:10 +0800 https://gerrit.example.com/q/I2b3c4d5e6f7 Bob <b@x.example> Refactor PCM open path
126
+
127
+ vendor/hal (1)
128
+ Merge time Patch Submitter Subject
129
+ 2026-07-05 10:03:55 +0800 https://gerrit.example.com/q/I3c4d5e6f7g8 Carol <c@x.example> Lower default buffer size
130
+ ```
131
+
132
+ A Markdown report with the same content is written next to the run
133
+ (`git-merge-list-report-<timestamp>.md` by default).
134
+
135
+ ### Output
136
+
137
+ - **Terminal**: a color table grouped by repo, columns
138
+ `Merge time | Patch | Submitter | Subject`. Color is gated on TTY and
139
+ `NO_COLOR`.
140
+ - **Markdown report**: written to `git-merge-list-report-<timestamp>.md`
141
+ (override with `-o`, suppress with `--no-markdown`).
142
+
143
+ > [!TIP]
144
+ > To preview the rendered Markdown report: `grip <file.md>` (local server) or
145
+ > `pandoc <file.md> -s -o <file.html>` (standalone HTML).
146
+
147
+ ### Options
148
+
149
+ | Option | Description |
150
+ | --- | --- |
151
+ | `path` | root path to scan (default: current directory) |
152
+ | `--day YYYY-MM-DD` | whole calendar day |
153
+ | `--hour "YYYY-MM-DD HH"` | whole calendar hour |
154
+ | `--since ...` | start time (inclusive); `--until` defaults to now |
155
+ | `--until ...` | end time |
156
+ | `--tz ...` | `+0800` \| `+08:00` \| `Z` \| `Asia/Shanghai` (default: system local) |
157
+ | `--author REGEX` | match author name/email |
158
+ | `--by-committer` | show committer (not author) as the submitter column |
159
+ | `--max-count N` | per-repo commit cap |
160
+ | `--reverse` | oldest-first within each repo |
161
+ | `-o, --output PATH` | Markdown report path |
162
+ | `--no-markdown` | do not write a Markdown report file |
163
+ | `-V, --version` | show version and exit |
164
+
165
+ ## How it works
166
+
167
+ - **Repo discovery**: a "repo" is any directory containing a `.git` entry —
168
+ a `.git` directory (normal checkout) or a `.git` file (worktree /
169
+ submodule). The scan never enters `.git/` or `.repo/` metadata, but keeps
170
+ walking a found repo's subdirectories so nested submodules are found.
171
+ Each `repo`-tool project is itself a normal git repo, so it is covered.
172
+ - **Time field**: `git log --since`/`--until` filter on the committer date.
173
+ Author date is not used for filtering.
174
+ - **Patch link**: the Gerrit host is parsed from each repo's `origin`
175
+ remote URL. For `ssh://` remotes the port (e.g. Gerrit's 29418) is
176
+ dropped — that's the push port; the web UI runs on HTTPS (443). The link
177
+ `https://<host>/q/<Change-Id>` is Gerrit's search-redirect URL. Commits
178
+ without a `Change-Id` fall back to the commit hash.
179
+
180
+ ## Development
181
+
182
+ ```bash
183
+ pip install -e ".[dev]"
184
+ pytest # tests
185
+ black --check src tests # format check (CI-enforced)
186
+ python -m build # build wheel
187
+ ```
188
+
189
+ ## License
190
+
191
+ Apache License 2.0 — see [LICENSE](LICENSE).
192
+
@@ -0,0 +1,12 @@
1
+ git_merge_list/__init__.py,sha256=fX5gJgIBUSJzqvtwA4wHQjUeWpQWEBZ4wQscH4WdLew,170
2
+ git_merge_list/cli.py,sha256=3eejB8FdYrr5Sy0V0pOX8l6IVG7vVBL6hA_zMm3KJ2s,4699
3
+ git_merge_list/discover.py,sha256=O9rbmCJrXvZcI1TeDtJTq1Xwh5OXSdFJAU3Jwz8t-wA,1410
4
+ git_merge_list/gerrit.py,sha256=7LW5TPnkVXzVQq1rnS80qw8X145DIYwpKXoupLZvDp8,2731
5
+ git_merge_list/output.py,sha256=1S2RDvIKsFCbMTFaZF_v_Del_FGUU_pO1iA762qoLxg,4020
6
+ git_merge_list/query.py,sha256=UNXhZS7LfrOzaiQyplYFYlZWQCahhSdr8JVCfAOcR8c,3001
7
+ git_merge_list/timeparse.py,sha256=be_a6tk-SKAwwi99syhVwm_vtHbTdoWONmmPUeNpLDA,3823
8
+ git_merge_list-0.0.1.dist-info/METADATA,sha256=lOi_J6ffCUXfqQF4p7UwBJOKbgLLuWM_3-G1TKkFLXc,7116
9
+ git_merge_list-0.0.1.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
10
+ git_merge_list-0.0.1.dist-info/entry_points.txt,sha256=YUnxfDK7Y8UuXgMlErZoc_gVyhqOwWnzpveD2r0k8H0,59
11
+ git_merge_list-0.0.1.dist-info/licenses/LICENSE,sha256=NfPSZxmx_2JKSCbHTgRt9Ajzpt3qAe7Wp-NEYNq8BY8,11341
12
+ git_merge_list-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.30.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ git-merge-list = git_merge_list.cli:main
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Junbo Zheng
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.