cleanmsg 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.
cleanmsg/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """cleanmsg: remove text or AI attribution lines from git commit messages."""
2
+
3
+ __version__ = "0.1.0"
cleanmsg/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import run
2
+
3
+ run()
cleanmsg/clean.py ADDED
@@ -0,0 +1,151 @@
1
+ """Pure message-cleaning logic (no git here)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import re
8
+ import sys
9
+ from dataclasses import dataclass
10
+ from functools import lru_cache
11
+ from typing import Iterable, List, Sequence
12
+
13
+ ENV_SPEC = "CLEANMSG_SPEC"
14
+
15
+ # Lines that AI coding tools commonly append to commit messages.
16
+ # Each regex is matched against a single line (case-insensitive) and the
17
+ # whole line is removed when it matches.
18
+ _AI_TOOLS = (
19
+ r"Claude|Anthropic|(?:GitHub\s+)?Copilot|Cursor(?:\s+Agent)?|Codex|ChatGPT|OpenAI|"
20
+ r"Gemini|Aider|Devin|Windsurf|Codeium|Amazon\s+Q|Jules|Junie|Cline|Roo\s*Code|opencode"
21
+ )
22
+ AI_PATTERNS: List[str] = [
23
+ # Co-Authored-By: Claude <noreply@anthropic.com>, Co-authored-by: Copilot <...>, ...
24
+ rf"^[ \t]*Co-authored-by:[ \t]*(?:{_AI_TOOLS})\b.*$",
25
+ # Co-authored-by trailers identified by the tool's e-mail domain
26
+ r"^[ \t]*Co-authored-by:.*<[^>]*@(?:anthropic\.com|openai\.com|cursor\.(?:com|sh)|aider\.chat)>[ \t]*$",
27
+ # 🤖 Generated with [Claude Code](https://claude.com/claude-code), Generated by Copilot, ...
28
+ rf"^[ \t]*(?:🤖[ \t]*)?Generated[ \t]+(?:with|by|using)[ \t]+\[?(?:{_AI_TOOLS})\b.*$",
29
+ ]
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class Spec:
34
+ """What to remove. Serialisable so it can be handed to git subprocesses."""
35
+
36
+ texts: tuple = ()
37
+ regex: bool = False
38
+ ignore_case: bool = False
39
+ ai: bool = False
40
+
41
+ def to_json(self) -> str:
42
+ return json.dumps(
43
+ {"texts": list(self.texts), "regex": self.regex,
44
+ "ignore_case": self.ignore_case, "ai": self.ai}
45
+ )
46
+
47
+ @classmethod
48
+ def from_json(cls, data: str) -> "Spec":
49
+ d = json.loads(data)
50
+ return cls(tuple(d["texts"]), d["regex"], d["ignore_case"], d["ai"])
51
+
52
+ def is_empty(self) -> bool:
53
+ return not self.texts and not self.ai
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class Rule:
58
+ regex: "re.Pattern[str]"
59
+ spans_lines: bool # True -> applied to the whole message, not per line
60
+
61
+
62
+ @lru_cache(maxsize=None)
63
+ def compile_rules(spec: Spec) -> tuple:
64
+ rules = []
65
+ flags = re.IGNORECASE if spec.ignore_case else 0
66
+ for text in spec.texts:
67
+ if not text:
68
+ continue
69
+ if spec.regex:
70
+ rules.append(Rule(re.compile(text, flags), False))
71
+ else:
72
+ rules.append(Rule(re.compile(re.escape(text), flags), "\n" in text))
73
+ if spec.ai:
74
+ for pat in AI_PATTERNS:
75
+ rules.append(Rule(re.compile(pat, re.IGNORECASE), False))
76
+ return tuple(rules)
77
+
78
+
79
+ def clean_message(msg: str, rules: Sequence[Rule]) -> str:
80
+ """Return msg with every rule match removed and the result tidied up.
81
+
82
+ - Messages without any match are returned byte-for-byte unchanged.
83
+ - A line that becomes empty because of a removal is dropped.
84
+ - Double spaces left behind are collapsed and the line is trimmed.
85
+ - If nothing would be left, the original message is kept
86
+ (git commits need a message).
87
+ """
88
+ work = msg
89
+ for rule in rules:
90
+ if rule.spans_lines:
91
+ work = rule.regex.sub("", work)
92
+
93
+ line_rules = [r for r in rules if not r.spans_lines]
94
+ out = []
95
+ touched = work != msg
96
+ for line in work.split("\n"):
97
+ new = line
98
+ for rule in line_rules:
99
+ new = rule.regex.sub("", new)
100
+ if new != line:
101
+ touched = True
102
+ new = re.sub(r"[ \t]{2,}", " ", new).strip()
103
+ if not new:
104
+ continue # the line existed only for the removed text
105
+ out.append(new)
106
+
107
+ if not touched:
108
+ return msg
109
+
110
+ result = "\n".join(out)
111
+ result = re.sub(r"\n[ \t]*\n(?:[ \t]*\n)+", "\n\n", result).strip("\n")
112
+ if not result.strip():
113
+ return msg
114
+ return result + "\n"
115
+
116
+
117
+ def clean_with_spec(msg: str, spec: Spec) -> str:
118
+ return clean_message(msg, compile_rules(spec))
119
+
120
+
121
+ # --------------------------------------------------------------------------
122
+ # Entry points used from inside git rewrite engines
123
+ # --------------------------------------------------------------------------
124
+
125
+ @lru_cache(maxsize=1)
126
+ def _env_rules() -> tuple:
127
+ return compile_rules(Spec.from_json(os.environ[ENV_SPEC]))
128
+
129
+
130
+ def clean_bytes_from_env(message: bytes) -> bytes:
131
+ """Used by git filter-repo's --message-callback."""
132
+ text = message.decode("utf-8", "surrogateescape")
133
+ return clean_message(text, _env_rules()).encode("utf-8", "surrogateescape")
134
+
135
+
136
+ def filter_stdin() -> None:
137
+ """Used by git filter-branch's --msg-filter: stdin -> stdout."""
138
+ data = sys.stdin.buffer.read()
139
+ sys.stdout.buffer.write(clean_bytes_from_env(data))
140
+
141
+
142
+ def iter_changed_lines(old: str, new: str) -> Iterable[tuple]:
143
+ """Small diff for previews: ('-' | '+', line) pairs, blank lines skipped."""
144
+ import difflib
145
+
146
+ for line in difflib.unified_diff(
147
+ old.rstrip("\n").split("\n"), new.rstrip("\n").split("\n"), lineterm="", n=0
148
+ ):
149
+ if line.startswith(("---", "+++", "@@")) or not line[1:].strip():
150
+ continue
151
+ yield line[0], line[1:]
cleanmsg/cli.py ADDED
@@ -0,0 +1,266 @@
1
+ """Command-line interface."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import os
7
+ import sys
8
+ from typing import List, Optional
9
+
10
+ from . import __version__
11
+ from .clean import AI_PATTERNS, Spec, iter_changed_lines
12
+ from .gitops import (
13
+ GitError, drop_backup, find_changes, in_work_tree, list_backups,
14
+ pick_engine, push, push_plan, resolve_scope, restore, rewrite,
15
+ )
16
+ from .github import push_warnings
17
+
18
+ PREVIEW_LIMIT = 20
19
+
20
+ EPILOG = """\
21
+ examples:
22
+ cleanmsg --ai preview removal of AI attribution lines
23
+ cleanmsg --ai --apply --push remove them and force-push to GitHub
24
+ cleanmsg "WIP" --last 5 --apply clean only the last 5 commits
25
+ cleanmsg -e "[skip ci]" -e "fixup" --unpushed --apply
26
+ cleanmsg --undo restore the history from the last backup
27
+
28
+ Without --apply nothing is changed.
29
+ """
30
+
31
+
32
+ def build_parser() -> argparse.ArgumentParser:
33
+ p = argparse.ArgumentParser(
34
+ prog="cleanmsg",
35
+ description="Remove text (or AI attribution lines) from git commit messages, safely.",
36
+ epilog=EPILOG,
37
+ formatter_class=argparse.RawDescriptionHelpFormatter,
38
+ )
39
+ p.add_argument("text", nargs="*", help='text to remove, e.g. "my change"')
40
+
41
+ what = p.add_argument_group("what to remove")
42
+ what.add_argument("-e", "--text", dest="extra", action="append", default=[], metavar="TEXT",
43
+ help="another text to remove (repeatable)")
44
+ what.add_argument("--ai", action="store_true",
45
+ help="remove AI attribution lines (Co-Authored-By: Claude, "
46
+ "Generated with Claude Code, Copilot, Cursor, ...)")
47
+ what.add_argument("-E", "--regex", action="store_true",
48
+ help="treat TEXT as a regular expression (applied per line)")
49
+ what.add_argument("-i", "--ignore-case", action="store_true", help="ignore upper/lower case")
50
+ what.add_argument("--show-ai-patterns", action="store_true",
51
+ help="print the patterns used by --ai and exit")
52
+
53
+ where = p.add_argument_group("which commits (default: the whole current branch)")
54
+ scope = where.add_mutually_exclusive_group()
55
+ scope.add_argument("--all", action="store_true", help="all local branches and tags")
56
+ scope.add_argument("--last", type=int, metavar="N", help="only the last N commits")
57
+ scope.add_argument("--unpushed", action="store_true",
58
+ help="only commits not pushed to the upstream branch yet")
59
+
60
+ do = p.add_argument_group("actions")
61
+ do.add_argument("--apply", action="store_true", help="rewrite (otherwise only preview)")
62
+ do.add_argument("--push", action="store_true", help="force-push the result")
63
+ do.add_argument("-y", "--yes", action="store_true", help="do not ask for confirmation")
64
+ do.add_argument("-v", "--verbose", action="store_true", help="list every affected commit")
65
+
66
+ safety = p.add_argument_group("backups")
67
+ safety.add_argument("--undo", nargs="?", const="latest", metavar="BACKUP",
68
+ help="restore branches/tags from a backup (default: the latest)")
69
+ safety.add_argument("--list-backups", action="store_true", help="list backups and exit")
70
+ safety.add_argument("--drop-backups", action="store_true", help="delete all backups")
71
+
72
+ misc = p.add_argument_group("other")
73
+ misc.add_argument("-C", "--repo", default=".", metavar="PATH", help="run in another repository")
74
+ misc.add_argument("--engine", choices=["auto", "filter-repo", "filter-branch"], default="auto",
75
+ help="rewrite engine (auto: filter-repo if installed, it is much faster)")
76
+ misc.add_argument("--no-github-checks", action="store_true",
77
+ help="skip the protected-branch / open-PR checks done with `gh`")
78
+ misc.add_argument("--version", action="version", version=f"cleanmsg {__version__}")
79
+ return p
80
+
81
+
82
+ def confirm(question: str, assume_yes: bool) -> bool:
83
+ if assume_yes:
84
+ return True
85
+ try:
86
+ ans = input(f"{question} [y/N] ").strip().lower()
87
+ except EOFError:
88
+ return False
89
+ return ans in ("y", "yes")
90
+
91
+
92
+ def _color(code: str, text: str) -> str:
93
+ if os.environ.get("NO_COLOR") or not sys.stdout.isatty():
94
+ return text
95
+ return f"\033[{code}m{text}\033[0m"
96
+
97
+
98
+ def print_preview(changes, verbose: bool) -> None:
99
+ shown = changes if verbose else changes[:PREVIEW_LIMIT]
100
+ for c in shown:
101
+ subject = c.old.split("\n", 1)[0]
102
+ print(f" {_color('33', c.sha[:8])} {subject}")
103
+ for sign, line in iter_changed_lines(c.old, c.new):
104
+ print(" " + _color("31" if sign == "-" else "32", f"{sign} {line}"))
105
+ hidden = len(changes) - len(shown)
106
+ if hidden:
107
+ print(f" ... and {hidden} more (use -v to list all)")
108
+
109
+
110
+ def print_push_warnings(branches: List[str], skip: bool) -> None:
111
+ if skip:
112
+ return
113
+ for w in push_warnings(push_plan(branches)):
114
+ print(f"warning: {w}")
115
+
116
+
117
+ def report_push(failures: List[str]) -> int:
118
+ for f in failures:
119
+ print(f"error: {f}", file=sys.stderr)
120
+ return 1 if failures else 0
121
+
122
+
123
+ # --------------------------------------------------------------------------
124
+ # Sub-flows
125
+ # --------------------------------------------------------------------------
126
+
127
+ def cmd_list_backups() -> int:
128
+ backups = list_backups()
129
+ if not backups:
130
+ print("No backups.")
131
+ for b in backups:
132
+ parts = [f"{len(b.branches)} branch(es): {', '.join(b.branches)}"]
133
+ if b.tags:
134
+ parts.append(f"{len(b.tags)} tag(s)")
135
+ print(f" {b.stamp} " + "; ".join(parts))
136
+ return 0
137
+
138
+
139
+ def cmd_drop_backups(a) -> int:
140
+ backups = list_backups()
141
+ if not backups:
142
+ print("No backups.")
143
+ return 0
144
+ if not confirm(f"Delete {len(backups)} backup(s)? This makes --undo impossible.", a.yes):
145
+ print("Cancelled.")
146
+ return 1
147
+ for b in backups:
148
+ drop_backup(b.stamp)
149
+ print("Backups deleted.")
150
+ return 0
151
+
152
+
153
+ def cmd_undo(a) -> int:
154
+ backups = list_backups()
155
+ if not backups:
156
+ print("No backups to restore.")
157
+ return 1
158
+ if a.undo == "latest":
159
+ backup = backups[-1]
160
+ else:
161
+ match = [b for b in backups if b.stamp == a.undo]
162
+ if not match:
163
+ print(f"error: no backup named {a.undo} (see --list-backups)", file=sys.stderr)
164
+ return 1
165
+ backup = match[0]
166
+
167
+ what = ", ".join(backup.branches) + (f" + {len(backup.tags)} tag(s)" if backup.tags else "")
168
+ print(f"Backup {backup.stamp}: {what}")
169
+ if a.push:
170
+ print_push_warnings(backup.branches, a.no_github_checks)
171
+ action = "Restore and force-push" if a.push else "Restore"
172
+ if not confirm(f"{action}?", a.yes):
173
+ print("Cancelled.")
174
+ return 1
175
+ restore(backup)
176
+ print("Restored.")
177
+ if a.push:
178
+ return report_push(push(backup.branches, backup.tags))
179
+ print("Not pushed. Use --undo --push to also restore GitHub.")
180
+ return 0
181
+
182
+
183
+ def cmd_clean(a, spec: Spec) -> int:
184
+ scope = resolve_scope(a.all, a.last, a.unpushed)
185
+ engine = pick_engine(a.engine)
186
+ changes = find_changes(scope, spec)
187
+ if not changes:
188
+ print(f"Nothing to change in {scope.label}.")
189
+ return 0
190
+
191
+ print(f"{len(changes)} commit message(s) to change in {scope.label}:")
192
+ print_preview(changes, a.verbose)
193
+
194
+ if not a.apply:
195
+ print("\nPreview only, nothing changed. Add --apply to rewrite (and --push to update GitHub).")
196
+ return 0
197
+
198
+ print()
199
+ if a.push:
200
+ print_push_warnings(scope.branches, a.no_github_checks)
201
+ action = "Rewrite and force-push" if a.push else "Rewrite"
202
+ if not confirm(f"{action} {scope.label}?", a.yes):
203
+ print("Cancelled.")
204
+ return 1
205
+
206
+ print(f"Rewriting with git {engine}...")
207
+ result = rewrite(scope, spec, engine)
208
+ if not result.changed_branches and not result.changed_tags:
209
+ print("Nothing was changed.")
210
+ return 0
211
+
212
+ print(f"Done. Backup saved as {result.stamp} (undo with: cleanmsg --undo)")
213
+ if a.push:
214
+ return report_push(push(result.changed_branches, result.changed_tags))
215
+ print("Not pushed. Run `cleanmsg --undo` to revert, or `git push --force-with-lease` to publish.")
216
+ return 0
217
+
218
+
219
+ def main(argv: Optional[List[str]] = None) -> int:
220
+ try: # keep our output in order with git's (which goes straight to the terminal)
221
+ sys.stdout.reconfigure(line_buffering=True)
222
+ except (AttributeError, ValueError):
223
+ pass
224
+ a = build_parser().parse_args(argv)
225
+
226
+ if a.show_ai_patterns:
227
+ print("\n".join(AI_PATTERNS))
228
+ return 0
229
+
230
+ try:
231
+ os.chdir(a.repo)
232
+ except OSError as e:
233
+ print(f"error: {e}", file=sys.stderr)
234
+ return 1
235
+ if not in_work_tree():
236
+ print(f"error: {os.path.abspath('.')} is not a git repository", file=sys.stderr)
237
+ return 1
238
+
239
+ try:
240
+ if a.list_backups:
241
+ return cmd_list_backups()
242
+ if a.drop_backups:
243
+ return cmd_drop_backups(a)
244
+ if a.undo:
245
+ return cmd_undo(a)
246
+
247
+ spec = Spec(tuple(a.text + a.extra), a.regex, a.ignore_case, a.ai)
248
+ if spec.is_empty():
249
+ build_parser().print_usage(sys.stderr)
250
+ print("error: say what to remove: a TEXT, -e TEXT or --ai", file=sys.stderr)
251
+ return 2
252
+ if a.push and not a.apply:
253
+ print("error: --push needs --apply", file=sys.stderr)
254
+ return 2
255
+ return cmd_clean(a, spec)
256
+ except GitError as e:
257
+ print(f"error: {e}", file=sys.stderr)
258
+ return 1
259
+ except KeyboardInterrupt:
260
+ print("\nInterrupted.", file=sys.stderr)
261
+ return 130
262
+
263
+
264
+ def run() -> None:
265
+ sys.exit(main())
266
+
cleanmsg/github.py ADDED
@@ -0,0 +1,77 @@
1
+ """Best-effort GitHub checks through the `gh` CLI. Never fatal."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ import shutil
8
+ import subprocess
9
+ from typing import List, Optional, Tuple
10
+
11
+ from .gitops import remote_url
12
+
13
+ _GH_URL = re.compile(r"github\.com[:/]+([^/\s]+)/([^/\s]+?)(?:\.git)?/?$")
14
+
15
+
16
+ def parse_github_url(url: str) -> Optional[str]:
17
+ """'git@github.com:owner/repo.git' -> 'owner/repo' (None if not GitHub)."""
18
+ m = _GH_URL.search(url.strip())
19
+ return f"{m.group(1)}/{m.group(2)}" if m else None
20
+
21
+
22
+ def github_repo(remote: str) -> Optional[str]:
23
+ return parse_github_url(remote_url(remote))
24
+
25
+
26
+ def _gh(args: List[str]) -> Optional[str]:
27
+ try:
28
+ res = subprocess.run(["gh", *args], text=True, capture_output=True, timeout=15)
29
+ except (OSError, subprocess.TimeoutExpired):
30
+ return None
31
+ return res.stdout.strip() if res.returncode == 0 else None
32
+
33
+
34
+ PR_LIMIT = 50
35
+
36
+
37
+ def _prs(repo: str, flag: str, branch: str) -> List[dict]:
38
+ out = _gh(["pr", "list", "-R", repo, flag, branch, "--state", "open",
39
+ "--json", "number,title", "--limit", str(PR_LIMIT)])
40
+ try:
41
+ return json.loads(out) if out else []
42
+ except ValueError:
43
+ return []
44
+
45
+
46
+ def _count(prs: List[dict]) -> str:
47
+ return f"{PR_LIMIT}+" if len(prs) >= PR_LIMIT else str(len(prs))
48
+
49
+
50
+ def _fmt(prs: List[dict]) -> str:
51
+ shown = ", ".join(f"#{p['number']}" for p in prs[:5])
52
+ return shown + (" ..." if len(prs) > 5 else "")
53
+
54
+
55
+ def push_warnings(plan: List[Tuple[str, str, str]]) -> List[str]:
56
+ """plan: [(local_branch, remote, remote_branch)]."""
57
+ if not shutil.which("gh"):
58
+ return []
59
+ warnings = []
60
+ for _, remote, rb in plan:
61
+ repo = github_repo(remote)
62
+ if not repo:
63
+ continue
64
+ if _gh(["api", f"repos/{repo}/branches/{rb}", "--jq", ".protected"]) == "true":
65
+ warnings.append(
66
+ f"'{rb}' is a protected branch on {repo}; GitHub may reject the force-push.")
67
+ head = _prs(repo, "--head", rb)
68
+ if head:
69
+ warnings.append(
70
+ f"{_count(head)} open PR(s) come from '{rb}' ({_fmt(head)}); "
71
+ "they will show the rewritten commits.")
72
+ base = _prs(repo, "--base", rb)
73
+ if base:
74
+ warnings.append(
75
+ f"{_count(base)} open PR(s) target '{rb}' ({_fmt(base)}); "
76
+ "they may show extra commits until they are rebased.")
77
+ return warnings
cleanmsg/gitops.py ADDED
@@ -0,0 +1,342 @@
1
+ """Everything that talks to git."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import shlex
7
+ import subprocess
8
+ import sys
9
+ import time
10
+ from dataclasses import dataclass, field
11
+ from typing import Dict, List, Optional, Tuple
12
+
13
+ from .clean import ENV_SPEC, Spec, clean_with_spec
14
+
15
+ BACKUP_NS = "refs/cleanmsg-backup"
16
+
17
+
18
+ class GitError(Exception):
19
+ pass
20
+
21
+
22
+ def git(*args: str, check: bool = True, env: Optional[dict] = None) -> str:
23
+ res = subprocess.run(["git", *args], text=True, capture_output=True, env=env)
24
+ if check and res.returncode != 0:
25
+ raise GitError(f"git {' '.join(args)} failed:\n{res.stderr.strip()}")
26
+ return res.stdout
27
+
28
+
29
+ def git_ok(*args: str) -> bool:
30
+ return subprocess.run(["git", *args], capture_output=True).returncode == 0
31
+
32
+
33
+ # --------------------------------------------------------------------------
34
+ # Repository state
35
+ # --------------------------------------------------------------------------
36
+
37
+ def in_work_tree() -> bool:
38
+ return git("rev-parse", "--is-inside-work-tree", check=False).strip() == "true"
39
+
40
+
41
+ def current_branch() -> Optional[str]:
42
+ return git("symbolic-ref", "--short", "-q", "HEAD", check=False).strip() or None
43
+
44
+
45
+ def is_clean() -> bool:
46
+ return not git("status", "--porcelain", "--untracked-files=no").strip()
47
+
48
+
49
+ def local_branches() -> List[str]:
50
+ out = git("for-each-ref", "--format=%(refname:short)", "refs/heads")
51
+ return [b for b in out.split("\n") if b]
52
+
53
+
54
+ def local_tags() -> List[str]:
55
+ out = git("for-each-ref", "--format=%(refname:short)", "refs/tags")
56
+ return [t for t in out.split("\n") if t]
57
+
58
+
59
+ def rev(ref: str) -> Optional[str]:
60
+ out = git("rev-parse", "-q", "--verify", ref, check=False).strip()
61
+ return out or None
62
+
63
+
64
+ def remotes() -> List[str]:
65
+ return git("remote").split()
66
+
67
+
68
+ def upstream_of(branch: str) -> Tuple[Optional[str], Optional[str]]:
69
+ """(remote, remote_branch) the branch pushes to, falling back to origin/<branch>."""
70
+ remote = git("config", f"branch.{branch}.remote", check=False).strip()
71
+ merge = git("config", f"branch.{branch}.merge", check=False).strip()
72
+ if remote and merge and remote != ".":
73
+ return remote, merge[len("refs/heads/"):] if merge.startswith("refs/heads/") else merge
74
+ if "origin" in remotes():
75
+ return "origin", branch
76
+ return None, None
77
+
78
+
79
+ def remote_url(remote: str) -> str:
80
+ return git("config", f"remote.{remote}.url", check=False).strip()
81
+
82
+
83
+ # --------------------------------------------------------------------------
84
+ # What to rewrite
85
+ # --------------------------------------------------------------------------
86
+
87
+ @dataclass
88
+ class Scope:
89
+ branches: List[str]
90
+ base: Optional[str] = None # exclude this commit and its ancestors
91
+ tags: List[str] = field(default_factory=list)
92
+ label: str = ""
93
+
94
+ def log_revs(self) -> List[str]:
95
+ revs = [f"refs/heads/{b}" for b in self.branches]
96
+ revs += [f"refs/tags/{t}" for t in self.tags]
97
+ if self.base:
98
+ revs.insert(0, f"^{self.base}")
99
+ return revs
100
+
101
+
102
+ def resolve_scope(all_branches: bool, last: Optional[int], unpushed: bool) -> Scope:
103
+ if all_branches:
104
+ return Scope(local_branches(), tags=local_tags(), label="all branches and tags")
105
+
106
+ cur = current_branch()
107
+ if not cur:
108
+ raise GitError("you are in detached HEAD; check out a branch first (or use --all)")
109
+
110
+ if last is not None:
111
+ if last < 1:
112
+ raise GitError("--last needs a number of 1 or more")
113
+ total = int(git("rev-list", "--count", cur).strip())
114
+ base = rev(f"{cur}~{last}") if last < total else None
115
+ return Scope([cur], base=base, label=f"the last {last} commit(s) of '{cur}'")
116
+
117
+ if unpushed:
118
+ up = rev(f"{cur}@{{upstream}}")
119
+ if not up:
120
+ raise GitError(f"branch '{cur}' has no upstream, so 'unpushed' is undefined")
121
+ return Scope([cur], base=up, label=f"unpushed commits of '{cur}'")
122
+
123
+ return Scope([cur], label=f"branch '{cur}'")
124
+
125
+
126
+ @dataclass
127
+ class Change:
128
+ sha: str
129
+ old: str
130
+ new: str
131
+
132
+
133
+ def find_changes(scope: Scope, spec: Spec) -> List[Change]:
134
+ out = git("log", "--format=%H%x00%B%x01", *scope.log_revs(), "--")
135
+ changes = []
136
+ for chunk in out.split("\x01"):
137
+ chunk = chunk.lstrip("\n")
138
+ if not chunk:
139
+ continue
140
+ sha, _, body = chunk.partition("\x00")
141
+ new = clean_with_spec(body, spec)
142
+ if new != body:
143
+ changes.append(Change(sha, body, new))
144
+ return changes
145
+
146
+
147
+ # --------------------------------------------------------------------------
148
+ # Rewrite engines
149
+ # --------------------------------------------------------------------------
150
+
151
+ def has_filter_repo() -> bool:
152
+ return git_ok("filter-repo", "--version")
153
+
154
+
155
+ def pick_engine(choice: str) -> str:
156
+ if choice == "filter-branch":
157
+ return choice
158
+ available = has_filter_repo()
159
+ if choice == "filter-repo" and not available:
160
+ raise GitError("git filter-repo is not installed (pip install git-filter-repo)")
161
+ return "filter-repo" if available else "filter-branch"
162
+
163
+
164
+ def _package_parent() -> str:
165
+ return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
166
+
167
+
168
+ def _run_filter_branch(scope: Scope, env: dict) -> None:
169
+ code = (
170
+ "import sys; sys.path.insert(0, %r); "
171
+ "from cleanmsg.clean import filter_stdin; filter_stdin()" % _package_parent()
172
+ )
173
+ msg_filter = " ".join(shlex.quote(p) for p in (sys.executable, "-c", code))
174
+
175
+ args = ["filter-branch", "-f", "--msg-filter", msg_filter]
176
+ if scope.tags:
177
+ args += ["--tag-name-filter", "cat"]
178
+ args += ["--", *scope.log_revs()]
179
+ env = dict(env, FILTER_BRANCH_SQUELCH_WARNING="1")
180
+ res = subprocess.run(["git", *args], text=True, capture_output=True, env=env)
181
+ if res.returncode != 0:
182
+ raise GitError(f"git filter-branch failed:\n{res.stderr.strip()}")
183
+ # filter-branch keeps its own backup in refs/original; ours is enough.
184
+ for b in scope.branches:
185
+ git("update-ref", "-d", f"refs/original/refs/heads/{b}", check=False)
186
+ for t in scope.tags:
187
+ git("update-ref", "-d", f"refs/original/refs/tags/{t}", check=False)
188
+
189
+
190
+ def _run_filter_repo(scope: Scope, env: dict) -> None:
191
+ callback = (
192
+ "import sys\n"
193
+ f"if {_package_parent()!r} not in sys.path: sys.path.insert(0, {_package_parent()!r})\n"
194
+ "from cleanmsg.clean import clean_bytes_from_env\n"
195
+ "return clean_bytes_from_env(message)\n"
196
+ )
197
+ refs = []
198
+ for b in scope.branches:
199
+ refs.append(f"{scope.base}..refs/heads/{b}" if scope.base else f"refs/heads/{b}")
200
+ refs += [f"refs/tags/{t}" for t in scope.tags]
201
+ args = ["filter-repo", "--force", "--quiet", "--refs", *refs,
202
+ "--message-callback", callback]
203
+ res = subprocess.run(["git", *args], text=True, capture_output=True, env=env)
204
+ if res.returncode != 0:
205
+ raise GitError(f"git filter-repo failed:\n{(res.stderr or res.stdout).strip()}")
206
+
207
+
208
+ @dataclass
209
+ class RewriteResult:
210
+ stamp: str
211
+ changed_branches: List[str]
212
+ changed_tags: List[str]
213
+
214
+
215
+ def snapshot(scope: Scope) -> Dict[str, Optional[str]]:
216
+ refs = [f"refs/heads/{b}" for b in scope.branches] + [f"refs/tags/{t}" for t in scope.tags]
217
+ return {r: rev(r) for r in refs}
218
+
219
+
220
+ def make_backup(before: Dict[str, Optional[str]]) -> str:
221
+ stamp = time.strftime("%Y%m%d-%H%M%S")
222
+ n = 1
223
+ while git("for-each-ref", f"{BACKUP_NS}/{stamp}").strip():
224
+ n += 1
225
+ stamp = time.strftime("%Y%m%d-%H%M%S") + f"-{n}"
226
+ for ref, sha in before.items():
227
+ if sha:
228
+ git("update-ref", f"{BACKUP_NS}/{stamp}/{ref[len('refs/'):]}", sha)
229
+ return stamp
230
+
231
+
232
+ def rewrite(scope: Scope, spec: Spec, engine: str) -> RewriteResult:
233
+ if not is_clean():
234
+ raise GitError("you have uncommitted changes; commit or stash them first")
235
+
236
+ before = snapshot(scope)
237
+ stamp = make_backup(before)
238
+ env = dict(os.environ)
239
+ env[ENV_SPEC] = spec.to_json()
240
+
241
+ try:
242
+ if engine == "filter-repo":
243
+ _run_filter_repo(scope, env)
244
+ else:
245
+ _run_filter_branch(scope, env)
246
+ except GitError:
247
+ drop_backup(stamp)
248
+ raise
249
+
250
+ after = snapshot(scope)
251
+ changed = [r for r in before if before[r] != after[r]]
252
+ if not changed:
253
+ drop_backup(stamp)
254
+ return RewriteResult(
255
+ stamp,
256
+ [r[len("refs/heads/"):] for r in changed if r.startswith("refs/heads/")],
257
+ [r[len("refs/tags/"):] for r in changed if r.startswith("refs/tags/")],
258
+ )
259
+
260
+
261
+ # --------------------------------------------------------------------------
262
+ # Backups / undo
263
+ # --------------------------------------------------------------------------
264
+
265
+ @dataclass
266
+ class Backup:
267
+ stamp: str
268
+ refs: Dict[str, str] # "refs/heads/x" -> sha
269
+
270
+ @property
271
+ def branches(self) -> List[str]:
272
+ return [r[len("refs/heads/"):] for r in self.refs if r.startswith("refs/heads/")]
273
+
274
+ @property
275
+ def tags(self) -> List[str]:
276
+ return [r[len("refs/tags/"):] for r in self.refs if r.startswith("refs/tags/")]
277
+
278
+
279
+ def list_backups() -> List[Backup]:
280
+ out = git("for-each-ref", "--format=%(refname) %(objectname)", BACKUP_NS)
281
+ found: Dict[str, Dict[str, str]] = {}
282
+ for line in out.split("\n"):
283
+ if not line:
284
+ continue
285
+ ref, sha = line.split(" ", 1)
286
+ rest = ref[len(BACKUP_NS) + 1:]
287
+ stamp, _, target = rest.partition("/")
288
+ found.setdefault(stamp, {})[f"refs/{target}"] = sha
289
+ return [Backup(s, found[s]) for s in sorted(found)]
290
+
291
+
292
+ def drop_backup(stamp: str) -> None:
293
+ out = git("for-each-ref", "--format=%(refname)", f"{BACKUP_NS}/{stamp}")
294
+ for ref in out.split():
295
+ git("update-ref", "-d", ref)
296
+
297
+
298
+ def restore(backup: Backup) -> None:
299
+ if not is_clean():
300
+ raise GitError("you have uncommitted changes; commit or stash them first")
301
+ cur = current_branch()
302
+ for ref, sha in backup.refs.items():
303
+ if cur and ref == f"refs/heads/{cur}":
304
+ git("reset", "--hard", "-q", sha)
305
+ else:
306
+ git("update-ref", ref, sha)
307
+
308
+
309
+ # --------------------------------------------------------------------------
310
+ # Push
311
+ # --------------------------------------------------------------------------
312
+
313
+ def push_plan(branches: List[str]) -> List[Tuple[str, str, str]]:
314
+ plan = []
315
+ for b in branches:
316
+ remote, rb = upstream_of(b)
317
+ if remote:
318
+ plan.append((b, remote, rb))
319
+ return plan
320
+
321
+
322
+ def push(branches: List[str], tags: List[str]) -> List[str]:
323
+ """Force-push; returns a list of failure messages."""
324
+ failures = []
325
+ pushed_to = set()
326
+ for b, remote, rb in push_plan(branches):
327
+ print(f"Force-pushing {b} -> {remote}/{rb}")
328
+ res = subprocess.run(["git", "push", "--force-with-lease", remote, f"refs/heads/{b}:refs/heads/{rb}"])
329
+ if res.returncode != 0:
330
+ failures.append(f"push of {b} to {remote} failed (protected branch? someone else pushed?)")
331
+ pushed_to.add(remote)
332
+ skipped = [b for b in branches if not upstream_of(b)[0]]
333
+ for b in skipped:
334
+ failures.append(f"{b} has no remote; not pushed")
335
+ if tags:
336
+ remote = sorted(pushed_to)[0] if pushed_to else ("origin" if "origin" in remotes() else None)
337
+ if remote:
338
+ print(f"Force-pushing {len(tags)} tag(s) -> {remote}")
339
+ res = subprocess.run(["git", "push", "--force", remote, *[f"refs/tags/{t}" for t in tags]])
340
+ if res.returncode != 0:
341
+ failures.append(f"push of tags to {remote} failed")
342
+ return failures
@@ -0,0 +1,214 @@
1
+ Metadata-Version: 2.5
2
+ Name: cleanmsg
3
+ Version: 0.1.0
4
+ Summary: Remove AI attribution lines (Co-Authored-By: Claude, Copilot, Cursor...) or any text from git commit messages, safely.
5
+ Project-URL: Homepage, https://github.com/enikakis/cleanmsg
6
+ Project-URL: Issues, https://github.com/enikakis/cleanmsg/issues
7
+ Author: enikakis
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: ai,claude,cli,co-authored-by,commit-message,copilot,git,rewrite-history
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: MacOS
15
+ Classifier: Operating System :: POSIX :: Linux
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Topic :: Software Development :: Version Control :: Git
18
+ Requires-Python: >=3.10
19
+ Provides-Extra: fast
20
+ Requires-Dist: git-filter-repo; extra == 'fast'
21
+ Description-Content-Type: text/markdown
22
+
23
+ # cleanmsg
24
+
25
+ **Remove AI attribution lines, or any text, from your git commit messages. Safely.**
26
+
27
+ AI coding tools like to sign their work. After a while your history looks like this:
28
+
29
+ ```
30
+ Add login form
31
+
32
+ 🤖 Generated with [Claude Code](https://claude.com/claude-code)
33
+
34
+ Co-Authored-By: Claude <noreply@anthropic.com>
35
+ ```
36
+
37
+ Whether you keep those lines is your call (some projects require them). If you
38
+ don't want them, `cleanmsg` strips them out of existing commits: it shows you what
39
+ will change first, keeps a backup, and can force-push the result to GitHub.
40
+
41
+ It works for any text, too: `WIP`, `[skip ci]`, a ticket number, a typo you
42
+ repeated in 40 commits.
43
+
44
+ ## Example
45
+
46
+ ```console
47
+ $ cleanmsg --ai
48
+ 3 commit message(s) to change in branch 'main':
49
+ 88912d10 Add password reset flow
50
+ - 🤖 Generated with [Claude Code](https://claude.com/claude-code)
51
+ - Co-Authored-By: Claude <noreply@anthropic.com>
52
+ d4de968e Validate e-mail on submit
53
+ - Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
54
+ 52744c5d Add login form
55
+ - 🤖 Generated with [Claude Code](https://claude.com/claude-code)
56
+ - Co-Authored-By: Claude <noreply@anthropic.com>
57
+
58
+ Preview only, nothing changed. Add --apply to rewrite (and --push to update GitHub).
59
+
60
+ $ cleanmsg --ai --apply --push
61
+ ...
62
+ Rewrite and force-push branch 'main'? [y/N] y
63
+ Rewriting with git filter-repo...
64
+ Done. Backup saved as 20261127-135715 (undo with: cleanmsg --undo)
65
+ Force-pushing main -> origin/main
66
+ ```
67
+
68
+ Afterwards the commit reads just:
69
+
70
+ ```
71
+ Add login form
72
+ ```
73
+
74
+ Removing your own text works the same way:
75
+
76
+ ```console
77
+ $ cleanmsg "my change"
78
+ 1 commit message(s) to change in branch 'main':
79
+ 169560e2 fix login my change
80
+ - fix login my change
81
+ + fix login
82
+ ```
83
+
84
+ ## Install
85
+
86
+ ```bash
87
+ pipx install "cleanmsg[fast]" # or: uv tool install "cleanmsg[fast]"
88
+ ```
89
+
90
+ `[fast]` also installs [git-filter-repo](https://github.com/newren/git-filter-repo),
91
+ which makes rewriting large repos much faster. Without it, `cleanmsg` falls back to
92
+ the `git filter-branch` command that ships with git. Both give the same result.
93
+
94
+ Needs Python 3.10+ and git. It installs both a `cleanmsg` command and `git cleanmsg`.
95
+
96
+ From source:
97
+
98
+ ```bash
99
+ git clone https://github.com/enikakis/cleanmsg && cd cleanmsg
100
+ pipx install ".[fast]"
101
+ ```
102
+
103
+ ## Usage
104
+
105
+ Run it inside a repository. **Nothing is changed unless you pass `--apply`.**
106
+
107
+ ```bash
108
+ cleanmsg --ai # preview: which AI lines would go
109
+ cleanmsg --ai --apply # rewrite the current branch locally
110
+ cleanmsg --ai --apply --push # ... and force-push to GitHub
111
+ cleanmsg "WIP" --last 5 --apply # only the last 5 commits
112
+ cleanmsg -e "[skip ci]" -e "fixup" --unpushed --apply
113
+ cleanmsg -E 'JIRA-\d+' --apply # regular expression
114
+ cleanmsg --undo # put the old history back
115
+ ```
116
+
117
+ ### What to remove
118
+
119
+ | Option | |
120
+ |---|---|
121
+ | `TEXT` / `-e TEXT` | text to remove; give as many as you like |
122
+ | `--ai` | AI attribution lines (see below) |
123
+ | `-E`, `--regex` | treat TEXT as a regular expression, matched per line |
124
+ | `-i`, `--ignore-case` | match regardless of case |
125
+
126
+ A line that only contained the removed text is deleted entirely. Leftover
127
+ double spaces are collapsed. If a message would end up empty, it is left as is.
128
+ Messages without a match are not touched, so those commits keep their hash.
129
+
130
+ ### Which commits
131
+
132
+ | Option | |
133
+ |---|---|
134
+ | *(default)* | the whole current branch |
135
+ | `--last N` | only the last N commits |
136
+ | `--unpushed` | only commits that aren't on the upstream branch yet (no force-push needed) |
137
+ | `--all` | every local branch and tag |
138
+
139
+ ### Actions
140
+
141
+ | Option | |
142
+ |---|---|
143
+ | `--apply` | actually rewrite (otherwise: preview only) |
144
+ | `--push` | force-push the rewritten branches (and tags) to their remote |
145
+ | `-y` | don't ask for confirmation |
146
+ | `-v` | list every affected commit (the preview shows the first 20) |
147
+ | `-C PATH` | run on another repository |
148
+
149
+ ### What `--ai` removes
150
+
151
+ Whole lines like these (case-insensitive):
152
+
153
+ ```
154
+ Co-Authored-By: Claude <noreply@anthropic.com>
155
+ Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
156
+ Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
157
+ Co-authored-by: Cursor Agent <cursoragent@cursor.com>
158
+ Co-authored-by: aider (gpt-4o) <noreply@aider.chat>
159
+ 🤖 Generated with [Claude Code](https://claude.com/claude-code)
160
+ Generated by GitHub Copilot
161
+ ```
162
+
163
+ Also Codex, ChatGPT, Gemini, Devin, Windsurf, Codeium, Amazon Q, Jules, Junie, Cline,
164
+ Roo Code and opencode. Human co-authors (`Co-authored-by: Jane <jane@example.com>`)
165
+ are kept. Run `cleanmsg --show-ai-patterns` for the exact regular expressions.
166
+ Missing a tool? Open an issue or PR.
167
+
168
+ ## Safety
169
+
170
+ Rewriting history is the scary part, so `cleanmsg` is careful about it:
171
+
172
+ - **Preview by default.** You see every line that will go before anything happens.
173
+ - **Confirmation** before rewriting or pushing (skip with `-y`).
174
+ - **Backups.** Before every rewrite the old branches and tags are saved under
175
+ `refs/cleanmsg-backup/<time>/`. `cleanmsg --undo` restores the latest one
176
+ (`--undo --push` restores GitHub too). See them with `--list-backups` and delete
177
+ them with `--drop-backups`.
178
+ - **`--force-with-lease`** instead of a plain force-push: if someone pushed in the
179
+ meantime, the push is refused instead of overwriting their work.
180
+ - **GitHub checks.** If the [`gh`](https://cli.github.com) CLI is installed and logged
181
+ in, `cleanmsg` warns you before pushing to a **protected branch** or a branch with
182
+ **open pull requests** (turn off with `--no-github-checks`).
183
+ - Refuses to run with uncommitted changes.
184
+
185
+ ### Things to know
186
+
187
+ - Changing a commit message changes that commit's hash **and the hash of every
188
+ commit after it**. That is why a force-push is needed, and why anyone else with a
189
+ clone needs to reset to the new history (`git fetch && git reset --hard origin/main`).
190
+ It's best on your own repos or branches.
191
+ - Rewritten commits lose their GPG/SSH **signatures**.
192
+ - **This is not a way to scrub secrets.** GitHub can keep old commits reachable by
193
+ their hash, and pull requests keep their own copies. If you committed a password or
194
+ key, rotate it, and follow GitHub's guide to
195
+ [removing sensitive data](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/removing-sensitive-data-from-a-repository).
196
+
197
+ ## How it works
198
+
199
+ `cleanmsg` reads the messages with `git log` to build the preview. When you apply,
200
+ it hands the same cleaning function to `git filter-repo` (if installed) or
201
+ `git filter-branch`, limited to the commits you chose. Authors, dates and file
202
+ contents stay exactly the same; only the messages change.
203
+
204
+ ## Development
205
+
206
+ ```bash
207
+ python -m pip install pytest git-filter-repo
208
+ python -m pytest # runs the end-to-end tests with both engines
209
+ ./bin/cleanmsg --help # run from the checkout without installing
210
+ ```
211
+
212
+ ## License
213
+
214
+ [MIT](LICENSE)
@@ -0,0 +1,11 @@
1
+ cleanmsg/__init__.py,sha256=1BtlL6nehueCOW8zypA7TeR39Q7rMP94TVJgiVenlok,101
2
+ cleanmsg/__main__.py,sha256=yQP0sf-rkTO-3MOotv4blvukvNGwbJFz10hQhMsxcJM,28
3
+ cleanmsg/clean.py,sha256=0Qy-xwMPIf3N5CU2ALbDY4KhycHoUY99t9q0pWsoV0c,5020
4
+ cleanmsg/cli.py,sha256=rLBa25Iq2J1dPP6HI0wLS8LjZAeeW2cZkV28J-l9J64,9713
5
+ cleanmsg/github.py,sha256=OH_xYiF1FK60e5Xj4ScF6mNqXi0txJ8Ma-mQWhUpLCY,2454
6
+ cleanmsg/gitops.py,sha256=qEM4i11V_LkuwUVdZcC_UKGZRKYYFj3OCDeh5UQGlks,11541
7
+ cleanmsg-0.1.0.dist-info/METADATA,sha256=RQrENldvNPpHQpMoCwX9iqW7-punoQOVa8-PX0dIm60,7888
8
+ cleanmsg-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
9
+ cleanmsg-0.1.0.dist-info/entry_points.txt,sha256=lz-LF8CbcNgonBtBBRAgYXc888Wmu2tpju5IL8qUm6I,78
10
+ cleanmsg-0.1.0.dist-info/licenses/LICENSE,sha256=PbrJ75tk50zAHiuLl4IHl7-fGuog-w3pEkPVron9_K4,1065
11
+ cleanmsg-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ cleanmsg = cleanmsg.cli:run
3
+ git-cleanmsg = cleanmsg.cli:run
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 enikakis
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.