gdiff-cli 2.0.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.
- gdiff/__init__.py +1 -0
- gdiff/__main__.py +5 -0
- gdiff/cli.py +123 -0
- gdiff/clipboard.py +44 -0
- gdiff/commands/__init__.py +0 -0
- gdiff/commands/generate.py +94 -0
- gdiff/commands/message.py +45 -0
- gdiff/commands/rule.py +91 -0
- gdiff/data/rule.txt +35 -0
- gdiff/errors.py +15 -0
- gdiff/git.py +124 -0
- gdiff/rules.py +129 -0
- gdiff/ui.py +47 -0
- gdiff_cli-2.0.0.dist-info/METADATA +316 -0
- gdiff_cli-2.0.0.dist-info/RECORD +19 -0
- gdiff_cli-2.0.0.dist-info/WHEEL +5 -0
- gdiff_cli-2.0.0.dist-info/entry_points.txt +2 -0
- gdiff_cli-2.0.0.dist-info/licenses/LICENSE +21 -0
- gdiff_cli-2.0.0.dist-info/top_level.txt +1 -0
gdiff/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "2.0.0"
|
gdiff/__main__.py
ADDED
gdiff/cli.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import os
|
|
3
|
+
import sys
|
|
4
|
+
from collections.abc import Sequence
|
|
5
|
+
from typing import NoReturn, TextIO
|
|
6
|
+
|
|
7
|
+
from gdiff import __version__, ui
|
|
8
|
+
from gdiff.commands import generate, message, rule
|
|
9
|
+
from gdiff.errors import GdiffError
|
|
10
|
+
|
|
11
|
+
# Subcommands must be the first argument; anything else goes to `generate`.
|
|
12
|
+
COMMANDS = {"message": message, "rule": rule}
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
16
|
+
_configure_streams()
|
|
17
|
+
|
|
18
|
+
if argv is None:
|
|
19
|
+
argv = sys.argv[1:]
|
|
20
|
+
|
|
21
|
+
args = list(argv)
|
|
22
|
+
|
|
23
|
+
try:
|
|
24
|
+
code = _dispatch(args)
|
|
25
|
+
sys.stdout.flush()
|
|
26
|
+
return code
|
|
27
|
+
except GdiffError as err:
|
|
28
|
+
ui.error(err.label, str(err), err.hint)
|
|
29
|
+
return err.exit_code
|
|
30
|
+
except KeyboardInterrupt:
|
|
31
|
+
return 130
|
|
32
|
+
except BrokenPipeError:
|
|
33
|
+
# e.g. `gdiff -p | head`: silence the second error Python raises at exit
|
|
34
|
+
os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
|
|
35
|
+
return 1
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class _Parser(argparse.ArgumentParser):
|
|
39
|
+
"""argparse that raises GdiffError and prints gdiff's own help."""
|
|
40
|
+
|
|
41
|
+
help_text = ""
|
|
42
|
+
|
|
43
|
+
def error(self, message: str) -> NoReturn:
|
|
44
|
+
raise GdiffError(message, hint=" Run 'gdiff --help' for usage.")
|
|
45
|
+
|
|
46
|
+
def print_help(self, file: TextIO | None = None) -> None:
|
|
47
|
+
print(self.help_text, file=file or sys.stdout)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _build_main_help() -> str:
|
|
51
|
+
commands: list[str] = [f" {name:<10}{module.SUMMARY}" for name, module in COMMANDS.items()]
|
|
52
|
+
return "\n".join(
|
|
53
|
+
[
|
|
54
|
+
ui.bold("DESCRIPTION"),
|
|
55
|
+
" Copy your git diff plus a commit-message rule to the clipboard.",
|
|
56
|
+
"",
|
|
57
|
+
ui.bold("USAGE"),
|
|
58
|
+
" gdiff [flags]",
|
|
59
|
+
" gdiff <command> [args]",
|
|
60
|
+
"",
|
|
61
|
+
ui.bold("COMMANDS"),
|
|
62
|
+
*commands,
|
|
63
|
+
"",
|
|
64
|
+
ui.bold("FLAGS"),
|
|
65
|
+
" -c, --commit [REF] Diff of a commit: position, hash or ref (default: 1 = latest)",
|
|
66
|
+
" -r, --rule <file> Use a custom rule file (.txt)",
|
|
67
|
+
" -p, --print Print the output instead of copying to clipboard",
|
|
68
|
+
" -d, --diff-only Copy only the diff, without the rule",
|
|
69
|
+
"",
|
|
70
|
+
ui.bold("GLOBAL FLAGS"),
|
|
71
|
+
" -h, --help Show help information",
|
|
72
|
+
" -v, --version Show version information",
|
|
73
|
+
]
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
78
|
+
parser = _Parser(allow_abbrev=False) # pragma: no mutate
|
|
79
|
+
|
|
80
|
+
parser.help_text = _build_main_help()
|
|
81
|
+
|
|
82
|
+
parser.add_argument("-v", "--version", action="version", version=f"gdiff v{__version__}")
|
|
83
|
+
|
|
84
|
+
generate.add_arguments(parser)
|
|
85
|
+
|
|
86
|
+
sub = parser.add_subparsers(dest="command")
|
|
87
|
+
|
|
88
|
+
for name, module in COMMANDS.items():
|
|
89
|
+
sub_parser = sub.add_parser(name, allow_abbrev=False) # pragma: no mutate
|
|
90
|
+
sub_parser.help_text = module.build_help()
|
|
91
|
+
module.add_arguments(sub_parser)
|
|
92
|
+
|
|
93
|
+
return parser
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _dispatch(argv: list[str]) -> int:
|
|
97
|
+
if argv and not argv[0].startswith("-") and argv[0] not in COMMANDS:
|
|
98
|
+
raise GdiffError(
|
|
99
|
+
f"'{argv[0]}'",
|
|
100
|
+
label="Unknown command:",
|
|
101
|
+
hint=" Run 'gdiff --help' for a list of valid commands.",
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
parser = _build_parser()
|
|
105
|
+
args = parser.parse_args(argv)
|
|
106
|
+
|
|
107
|
+
if args.command is None:
|
|
108
|
+
return generate.run(args)
|
|
109
|
+
|
|
110
|
+
conflicting = generate.passed_flags(args, parser)
|
|
111
|
+
|
|
112
|
+
if conflicting:
|
|
113
|
+
parser.error(f"'{args.command}' cannot be combined with {', '.join(conflicting)}.")
|
|
114
|
+
|
|
115
|
+
return COMMANDS[args.command].run(args)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _configure_streams() -> None:
|
|
119
|
+
# The ✓ and non-ASCII diffs break on Windows consoles that default to cp1252
|
|
120
|
+
for stream in (sys.stdout, sys.stderr):
|
|
121
|
+
reconfigure = getattr(stream, "reconfigure", None)
|
|
122
|
+
if reconfigure:
|
|
123
|
+
reconfigure(encoding="utf-8", errors="replace")
|
gdiff/clipboard.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Copy text to the system clipboard using whatever tool the machine has."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import shutil
|
|
5
|
+
import subprocess
|
|
6
|
+
|
|
7
|
+
from gdiff.errors import GdiffError
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def detect() -> tuple[list[str], str] | None:
|
|
11
|
+
if shutil.which("wl-copy") and os.environ.get("WAYLAND_DISPLAY"):
|
|
12
|
+
return ["wl-copy"], "utf-8"
|
|
13
|
+
if shutil.which("xclip") and os.environ.get("DISPLAY"):
|
|
14
|
+
return ["xclip", "-selection", "clipboard"], "utf-8"
|
|
15
|
+
if shutil.which("xsel") and os.environ.get("DISPLAY"):
|
|
16
|
+
return ["xsel", "--clipboard", "--input"], "utf-8"
|
|
17
|
+
if shutil.which("pbcopy"):
|
|
18
|
+
return ["env", "LC_ALL=en_US.UTF-8", "pbcopy"], "utf-8"
|
|
19
|
+
if shutil.which("clip.exe"):
|
|
20
|
+
return ["clip.exe"], "utf-16le"
|
|
21
|
+
return None
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def copy(text: str) -> None:
|
|
25
|
+
tool = detect()
|
|
26
|
+
if tool is None:
|
|
27
|
+
raise GdiffError(
|
|
28
|
+
"No clipboard tool found (wl-copy, xclip, xsel, pbcopy, clip.exe).",
|
|
29
|
+
hint="Use --print to output to stdout instead.",
|
|
30
|
+
)
|
|
31
|
+
command, encoding = tool
|
|
32
|
+
try:
|
|
33
|
+
# stdout must not be captured: wl-copy and xclip fork a child that keeps
|
|
34
|
+
# the pipe open, so waiting for it to close would hang forever.
|
|
35
|
+
result = subprocess.run(
|
|
36
|
+
command,
|
|
37
|
+
input=text.encode(encoding),
|
|
38
|
+
stdout=subprocess.DEVNULL,
|
|
39
|
+
check=False,
|
|
40
|
+
)
|
|
41
|
+
except OSError:
|
|
42
|
+
raise GdiffError("Failed to copy to clipboard.") from None
|
|
43
|
+
if result.returncode != 0:
|
|
44
|
+
raise GdiffError("Failed to copy to clipboard.")
|
|
File without changes
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""The default command: diff (+ rule) to the clipboard or to stdout."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import sys
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from gdiff import clipboard, git, rules, ui
|
|
8
|
+
from gdiff.errors import GdiffError
|
|
9
|
+
|
|
10
|
+
FLAGS = {"commit": "-c", "rule": "-r", "print_only": "-p", "diff_only": "-d"}
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def add_arguments(parser: argparse.ArgumentParser) -> None:
|
|
14
|
+
parser.add_argument(
|
|
15
|
+
"-c",
|
|
16
|
+
"--commit",
|
|
17
|
+
dest="commit", # pragma: no mutate
|
|
18
|
+
action="store", # pragma: no mutate
|
|
19
|
+
nargs="?",
|
|
20
|
+
const="1",
|
|
21
|
+
default=None, # pragma: no mutate
|
|
22
|
+
)
|
|
23
|
+
parser.add_argument(
|
|
24
|
+
"-p",
|
|
25
|
+
"--print",
|
|
26
|
+
dest="print_only",
|
|
27
|
+
action="store_true",
|
|
28
|
+
default=False, # pragma: no mutate
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
group = parser.add_mutually_exclusive_group(required=False) # pragma: no mutate
|
|
32
|
+
group.add_argument(
|
|
33
|
+
"-r",
|
|
34
|
+
"--rule",
|
|
35
|
+
dest="rule", # pragma: no mutate
|
|
36
|
+
action="store", # takes exactly one value: the rule file # pragma: no mutate
|
|
37
|
+
type=Path,
|
|
38
|
+
nargs=None, # pragma: no mutate
|
|
39
|
+
default=None, # pragma: no mutate
|
|
40
|
+
)
|
|
41
|
+
group.add_argument(
|
|
42
|
+
"-d",
|
|
43
|
+
"--diff-only",
|
|
44
|
+
dest="diff_only", # pragma: no mutate
|
|
45
|
+
action="store_true",
|
|
46
|
+
default=False, # pragma: no mutate
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def passed_flags(args: argparse.Namespace, parser: argparse.ArgumentParser) -> list[str]:
|
|
51
|
+
"""Flags of the default command that the user actually typed."""
|
|
52
|
+
return [flag for dest, flag in FLAGS.items() if getattr(args, dest) != parser.get_default(dest)]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def run(args: argparse.Namespace) -> int:
|
|
56
|
+
# Same order as the bash version: rule problems are reported before git ones
|
|
57
|
+
rule_text = ""
|
|
58
|
+
using_default = False # pragma: no mutate
|
|
59
|
+
|
|
60
|
+
if not args.diff_only:
|
|
61
|
+
rule_path = rules.resolve_rule(args.rule)
|
|
62
|
+
rules.check_rule(rule_path)
|
|
63
|
+
rule_text = rules.read_rule(rule_path)
|
|
64
|
+
using_default = rule_path == rules.default_rule_path()
|
|
65
|
+
|
|
66
|
+
git.ensure_repo()
|
|
67
|
+
if args.commit is None:
|
|
68
|
+
if not git.has_staged():
|
|
69
|
+
raise GdiffError("Use 'git add' to stage your changes first.", label="Nothing staged.")
|
|
70
|
+
diff = git.staged_diff()
|
|
71
|
+
else:
|
|
72
|
+
diff = git.commit_diff(git.resolve_commit(args.commit))
|
|
73
|
+
|
|
74
|
+
payload = f"{diff}\n\n{rule_text}"
|
|
75
|
+
|
|
76
|
+
if args.print_only:
|
|
77
|
+
# Keep the diff's existing CRLF/LF endings instead of translating them on Windows
|
|
78
|
+
reconfigure = getattr(sys.stdout, "reconfigure", None)
|
|
79
|
+
if reconfigure:
|
|
80
|
+
reconfigure(newline="")
|
|
81
|
+
sys.stdout.write(payload)
|
|
82
|
+
return 0
|
|
83
|
+
|
|
84
|
+
clipboard.copy(payload)
|
|
85
|
+
ui.success(_success_message(args.diff_only, using_default))
|
|
86
|
+
return 0
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _success_message(diff_only: bool, using_default: bool) -> str:
|
|
90
|
+
if diff_only:
|
|
91
|
+
return "Diff copied to clipboard"
|
|
92
|
+
if using_default:
|
|
93
|
+
return "Diff with default rule copied to clipboard"
|
|
94
|
+
return "Diff with rule copied to clipboard"
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""gdiff message [REF] [-i]: print a commit message to the terminal."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
from gdiff import git, ui
|
|
7
|
+
|
|
8
|
+
SUMMARY = "Print a commit message (position, hash or ref; default: 1 = latest)"
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def add_arguments(parser: argparse.ArgumentParser) -> None:
|
|
12
|
+
parser.add_argument("ref", nargs="?", default="1")
|
|
13
|
+
parser.add_argument("-i", "--info", action="store_true")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def build_help() -> str:
|
|
17
|
+
return "\n".join(
|
|
18
|
+
[
|
|
19
|
+
ui.bold("DESCRIPTION"),
|
|
20
|
+
" Print a commit message to the terminal, exactly as written.",
|
|
21
|
+
"",
|
|
22
|
+
ui.bold("USAGE"),
|
|
23
|
+
" gdiff message [REF] [-i]",
|
|
24
|
+
"",
|
|
25
|
+
ui.bold("ARGUMENTS"),
|
|
26
|
+
" REF Commit position, hash or ref (default: 1 = latest)",
|
|
27
|
+
"",
|
|
28
|
+
ui.bold("FLAGS"),
|
|
29
|
+
" -i, --info Prepend a header with the commit hash, short hash, author and date",
|
|
30
|
+
"",
|
|
31
|
+
ui.bold("GLOBAL FLAGS"),
|
|
32
|
+
" -h, --help Show help information",
|
|
33
|
+
]
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def run(args: argparse.Namespace) -> int:
|
|
38
|
+
git.ensure_repo()
|
|
39
|
+
commit_hash = git.resolve_commit(args.ref)
|
|
40
|
+
# Keep the message's existing CRLF/LF endings instead of translating them on Windows
|
|
41
|
+
reconfigure = getattr(sys.stdout, "reconfigure", None)
|
|
42
|
+
if reconfigure:
|
|
43
|
+
reconfigure(newline="")
|
|
44
|
+
sys.stdout.write(git.commit_message(commit_hash, args.info))
|
|
45
|
+
return 0
|
gdiff/commands/rule.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""gdiff rule <path|init|reset>: look at and manage the rule file."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import sys
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
|
|
7
|
+
from gdiff import rules, ui
|
|
8
|
+
from gdiff.errors import GdiffError
|
|
9
|
+
|
|
10
|
+
SUMMARY = "Show which rule file is used and manage it"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def add_arguments(parser: argparse.ArgumentParser) -> None:
|
|
14
|
+
parser.add_argument("action", nargs="?")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def build_help() -> str:
|
|
18
|
+
config = rules.config_dir()
|
|
19
|
+
return "\n".join(
|
|
20
|
+
[
|
|
21
|
+
ui.bold("DESCRIPTION"),
|
|
22
|
+
" Show which rule file is used and manage it.",
|
|
23
|
+
"",
|
|
24
|
+
ui.bold("USAGE"),
|
|
25
|
+
" gdiff rule <path|init|reset>",
|
|
26
|
+
"",
|
|
27
|
+
ui.bold("RULE ACTIONS"),
|
|
28
|
+
" path Show which rule file is being used",
|
|
29
|
+
f" init Create an editable copy of the default rule in {config}",
|
|
30
|
+
" reset Overwrite your rule with the default one",
|
|
31
|
+
"",
|
|
32
|
+
ui.bold("LOOKUP ORDER"),
|
|
33
|
+
" 1. gdiff -r <file> (highest)",
|
|
34
|
+
f" 2. {config / 'rule.txt'}",
|
|
35
|
+
" 3. built-in default rule",
|
|
36
|
+
"",
|
|
37
|
+
ui.bold("GLOBAL FLAGS"),
|
|
38
|
+
" -h, --help Show help information",
|
|
39
|
+
]
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def run_path() -> None:
|
|
44
|
+
path = rules.resolve_rule()
|
|
45
|
+
print(path)
|
|
46
|
+
if path == rules.default_rule_path():
|
|
47
|
+
print(
|
|
48
|
+
"Using the built-in default rule. Run 'gdiff rule init' to create an editable copy.",
|
|
49
|
+
file=sys.stderr,
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def run_init() -> None:
|
|
54
|
+
existing = rules.existing_user_rule()
|
|
55
|
+
if existing:
|
|
56
|
+
print(f"A rule file already exists at {existing} (left untouched).")
|
|
57
|
+
return
|
|
58
|
+
try:
|
|
59
|
+
target = rules.write_user_rule(overwrite=False)
|
|
60
|
+
except FileExistsError:
|
|
61
|
+
print(f"A rule file already exists at {rules.user_rule_path()} (left untouched).")
|
|
62
|
+
return
|
|
63
|
+
ui.success(f"Created an editable rule at {target}")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def run_reset() -> None:
|
|
67
|
+
existing = rules.existing_user_rule()
|
|
68
|
+
if existing and not ui.confirm(f"A rule file already exists at {existing}. Overwrite?"):
|
|
69
|
+
print("Operation cancelled.")
|
|
70
|
+
return
|
|
71
|
+
target = rules.write_user_rule()
|
|
72
|
+
ui.success(f"Reset the rule to the built-in default at {target}")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def run(args: argparse.Namespace) -> int:
|
|
76
|
+
names = list(_ACTIONS)
|
|
77
|
+
valid = f"{', '.join(names[:-1])} or {names[-1]}"
|
|
78
|
+
if args.action is None:
|
|
79
|
+
raise GdiffError(f"Command 'rule' requires an action: {valid}.")
|
|
80
|
+
handler = _ACTIONS.get(args.action)
|
|
81
|
+
if handler is None:
|
|
82
|
+
raise GdiffError(f"Unknown rule action: '{args.action}'. Valid actions: {valid}.")
|
|
83
|
+
handler()
|
|
84
|
+
return 0
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
_ACTIONS: dict[str, Callable[[], None]] = {
|
|
88
|
+
"path": run_path,
|
|
89
|
+
"init": run_init,
|
|
90
|
+
"reset": run_reset,
|
|
91
|
+
}
|
gdiff/data/rule.txt
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
Create a conventional commit message in English for the above diff following these strict rules:
|
|
2
|
+
|
|
3
|
+
- First line (subject): MAX 50 characters (hard limit)
|
|
4
|
+
- Use Conventional Commits format → type(scope): description in imperative mood (scope is optional, e.g. type: description)
|
|
5
|
+
Valid types: feat, fix, docs, style, refactor, perf, test, build, ci, chore, revert
|
|
6
|
+
- If a scope is used, do not repeat the scope's name or its keywords inside the description (e.g., avoid "feat(gdiff): add gdiff CLI", prefer "feat(gdiff): add CLI" or "feat: add gdiff CLI")
|
|
7
|
+
- Describe WHAT changed, not WHY — the 'why' belongs in the Pull Request
|
|
8
|
+
- Subject must NOT end with a period
|
|
9
|
+
- If more explanation is needed: leave a blank line and add a body
|
|
10
|
+
- Body: write complete sentences, one per line (MAX 72 characters per line)
|
|
11
|
+
- Each body line MUST end with a period
|
|
12
|
+
- Do NOT break sentences mid-phrase across lines
|
|
13
|
+
- Be professional, concise and clear
|
|
14
|
+
|
|
15
|
+
Examples of perfect commits:
|
|
16
|
+
|
|
17
|
+
Example 1: With scope and with body
|
|
18
|
+
feat(auth): add Apple Sign In support
|
|
19
|
+
|
|
20
|
+
Adds a new login button for Apple authentication on the sign-in screen.
|
|
21
|
+
Configures secure token exchange with Apple authorization servers.
|
|
22
|
+
Updates database schema to store Apple user identifiers.
|
|
23
|
+
|
|
24
|
+
Example 2: Without scope and with body
|
|
25
|
+
feat: add dark mode support
|
|
26
|
+
|
|
27
|
+
Adds a theme switcher component to the main navigation bar.
|
|
28
|
+
Implements CSS custom properties for light and dark color palettes.
|
|
29
|
+
Persists the user's theme selection in localStorage.
|
|
30
|
+
|
|
31
|
+
Example 3: With scope and without body
|
|
32
|
+
refactor(orders): use AutoMapper for DTOs
|
|
33
|
+
|
|
34
|
+
Example 4: Without scope and without body
|
|
35
|
+
fix: prevent double submission on checkout
|
gdiff/errors.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
class GdiffError(Exception):
|
|
2
|
+
"""A user-facing error. Only cli.main() prints it and picks the exit code."""
|
|
3
|
+
|
|
4
|
+
def __init__(
|
|
5
|
+
self,
|
|
6
|
+
message: str,
|
|
7
|
+
*,
|
|
8
|
+
hint: str | None = None,
|
|
9
|
+
label: str = "Error:",
|
|
10
|
+
exit_code: int = 1,
|
|
11
|
+
) -> None:
|
|
12
|
+
super().__init__(message)
|
|
13
|
+
self.hint = hint
|
|
14
|
+
self.label = label
|
|
15
|
+
self.exit_code = exit_code
|
gdiff/git.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import re
|
|
2
|
+
import subprocess
|
|
3
|
+
|
|
4
|
+
from gdiff.errors import GdiffError
|
|
5
|
+
|
|
6
|
+
_OUTPUT_ENCODING = "utf-8" # pragma: no mutate
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def ensure_repo() -> None:
|
|
10
|
+
code, _ = _run("rev-parse", "--git-dir")
|
|
11
|
+
if code != 0:
|
|
12
|
+
raise GdiffError("Not inside a git repository.")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def has_staged() -> bool:
|
|
16
|
+
# `git diff --quiet` exits 0 when there is nothing and 1 when there are changes
|
|
17
|
+
code, _ = _run("diff", "--cached", "--quiet")
|
|
18
|
+
if code not in (0, 1):
|
|
19
|
+
raise GdiffError("git diff failed.")
|
|
20
|
+
return code == 1
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def staged_diff() -> str:
|
|
24
|
+
return _run_checked("diff", "--cached", "--no-color", "--stat", "--patch")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def resolve_commit(target: str) -> str:
|
|
28
|
+
"""Turn a position (1 = latest), hash or ref into a full commit hash."""
|
|
29
|
+
if re.fullmatch(r"\d{1,6}", target, re.ASCII):
|
|
30
|
+
return _resolve_position(target)
|
|
31
|
+
return _resolve_ref(target)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def commit_diff(commit_hash: str) -> str:
|
|
35
|
+
stat = _run_checked("show", "-m", "--first-parent", "--stat", "--format=", commit_hash)
|
|
36
|
+
patch = _run_checked("show", "-m", "--first-parent", "-p", "--format=", commit_hash)
|
|
37
|
+
return f"{stat}\n{patch}"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def commit_message(commit_hash: str, with_info: bool = False) -> str:
|
|
41
|
+
"""The message exactly as written; with_info adds hash, author and date first."""
|
|
42
|
+
message = _run_checked(
|
|
43
|
+
"log",
|
|
44
|
+
"-1",
|
|
45
|
+
"--encoding=UTF-8",
|
|
46
|
+
"--format=%B",
|
|
47
|
+
commit_hash,
|
|
48
|
+
).rstrip("\n")
|
|
49
|
+
if not with_info:
|
|
50
|
+
return f"{message}\n"
|
|
51
|
+
header = _run_checked(
|
|
52
|
+
"log",
|
|
53
|
+
"-1",
|
|
54
|
+
"--encoding=UTF-8",
|
|
55
|
+
"--date=default",
|
|
56
|
+
"--format=Commit: %H%nShort: %h%nAuthor: %an <%ae>%nDate: %ad",
|
|
57
|
+
commit_hash,
|
|
58
|
+
).rstrip("\n")
|
|
59
|
+
return f"{header}\n\n{message}\n"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _run(*args: str) -> tuple[int, str]:
|
|
63
|
+
"""Run git and return (exit code, stdout).
|
|
64
|
+
|
|
65
|
+
Output is decoded by hand instead of using text=True, because text mode
|
|
66
|
+
would turn CRLF into LF and silently alter diffs of Windows files.
|
|
67
|
+
"""
|
|
68
|
+
try:
|
|
69
|
+
result = subprocess.run(["git", *args], capture_output=True, check=False)
|
|
70
|
+
except FileNotFoundError:
|
|
71
|
+
raise GdiffError("git is not installed.") from None
|
|
72
|
+
return result.returncode, result.stdout.decode(_OUTPUT_ENCODING, "replace")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _run_checked(*args: str) -> str:
|
|
76
|
+
code, out = _run(*args)
|
|
77
|
+
if code != 0:
|
|
78
|
+
raise GdiffError(f"git {args[0]} failed.")
|
|
79
|
+
return out
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _resolve_position(target: str) -> str:
|
|
83
|
+
"""Resolve a short all-digit value as a position in git log order.
|
|
84
|
+
|
|
85
|
+
Counts from HEAD. Every reachable commit counts, including merge commits
|
|
86
|
+
and the commits of merged branches.
|
|
87
|
+
"""
|
|
88
|
+
if not re.fullmatch(r"[1-9]\d*", target, re.ASCII):
|
|
89
|
+
raise GdiffError(
|
|
90
|
+
f"Invalid commit position '{target}'. Must be a positive integer (e.g. 1, 2, 3)."
|
|
91
|
+
)
|
|
92
|
+
position = int(target)
|
|
93
|
+
|
|
94
|
+
code, _ = _run("rev-parse", "--verify", "HEAD")
|
|
95
|
+
if code != 0:
|
|
96
|
+
raise GdiffError("No commits found in repository.")
|
|
97
|
+
|
|
98
|
+
total = int(_run_checked("rev-list", "--count", "HEAD").strip())
|
|
99
|
+
if position > total:
|
|
100
|
+
noun = "commit" if total == 1 else "commits"
|
|
101
|
+
raise GdiffError(
|
|
102
|
+
f"Commit at position {position} does not exist (branch only has {total} {noun})."
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
commit_hash = _run_checked(
|
|
106
|
+
"rev-list", f"--skip={position - 1}", "--max-count=1", "HEAD"
|
|
107
|
+
).strip()
|
|
108
|
+
if not commit_hash:
|
|
109
|
+
raise GdiffError(f"Failed to resolve commit at position {target}.")
|
|
110
|
+
return commit_hash
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _resolve_ref(target: str) -> str:
|
|
114
|
+
"""Resolve anything that is not a position as a hash or ref."""
|
|
115
|
+
if not target or target.startswith("-"):
|
|
116
|
+
raise GdiffError(
|
|
117
|
+
f"Invalid commit '{target}'. Use a position (e.g. 1, 2, 3) or a commit hash."
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
code, out = _run("rev-parse", "--verify", "--quiet", f"{target}^{{commit}}")
|
|
121
|
+
commit_hash = out.strip()
|
|
122
|
+
if code != 0 or not commit_hash:
|
|
123
|
+
raise GdiffError(f"Commit '{target}' not found.")
|
|
124
|
+
return commit_hash
|
gdiff/rules.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""Finding, validating and installing the commit-message rule. Never prints or asks."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import shutil
|
|
5
|
+
import sys
|
|
6
|
+
from importlib import resources
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from gdiff.errors import GdiffError
|
|
10
|
+
|
|
11
|
+
ALLOWED_SUFFIXES = (".txt",)
|
|
12
|
+
RULE_FILENAME = "rule.txt"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def config_dir() -> Path:
|
|
16
|
+
override = os.environ.get("GDIFF_CONFIG_HOME")
|
|
17
|
+
|
|
18
|
+
if override:
|
|
19
|
+
return Path(override)
|
|
20
|
+
|
|
21
|
+
if sys.platform == "win32":
|
|
22
|
+
base = os.environ.get("APPDATA") or str(Path.home() / ".config")
|
|
23
|
+
else:
|
|
24
|
+
base = os.environ.get("XDG_CONFIG_HOME") or str(Path.home() / ".config")
|
|
25
|
+
|
|
26
|
+
return Path(base) / "gdiff"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def user_rule_path() -> Path:
|
|
30
|
+
return config_dir() / RULE_FILENAME
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def existing_user_rule() -> Path | None:
|
|
34
|
+
"""The user's own rule, if there is one."""
|
|
35
|
+
candidate = config_dir() / RULE_FILENAME
|
|
36
|
+
return candidate if candidate.is_file() else None
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def default_rule_path() -> Path:
|
|
40
|
+
# A real file on disk: gdiff is installed as loose files, not as a zipapp
|
|
41
|
+
return Path(str(resources.files("gdiff") / "data" / RULE_FILENAME)) # pragma: no mutate
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def resolve_rule(custom: Path | None = None) -> Path:
|
|
45
|
+
"""--rule file > user rule in the config dir > rule shipped with gdiff."""
|
|
46
|
+
if custom is not None:
|
|
47
|
+
if custom.suffix.lower() not in ALLOWED_SUFFIXES:
|
|
48
|
+
raise GdiffError(f"Rule file must have a .txt extension: {custom}")
|
|
49
|
+
|
|
50
|
+
if not custom.is_file():
|
|
51
|
+
raise GdiffError(f"Rule file not found: {custom}")
|
|
52
|
+
|
|
53
|
+
return custom
|
|
54
|
+
|
|
55
|
+
user_rule = existing_user_rule()
|
|
56
|
+
if user_rule:
|
|
57
|
+
return user_rule
|
|
58
|
+
|
|
59
|
+
packaged = default_rule_path()
|
|
60
|
+
if packaged.is_file():
|
|
61
|
+
return packaged
|
|
62
|
+
raise GdiffError(
|
|
63
|
+
f"Built-in rule file is missing: {packaged}",
|
|
64
|
+
hint="The installation looks broken. Try reinstalling gdiff.",
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def check_rule(path: Path) -> None:
|
|
69
|
+
try:
|
|
70
|
+
size = path.stat().st_size
|
|
71
|
+
except OSError as exc:
|
|
72
|
+
raise GdiffError(f"Cannot read rule file {path}: {exc}") from None
|
|
73
|
+
if size == 0:
|
|
74
|
+
raise GdiffError(
|
|
75
|
+
f"Rule file is empty: {path}",
|
|
76
|
+
hint="Please edit the file or run 'gdiff rule reset' to restore the default rule.",
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def read_rule(path: Path) -> str:
|
|
81
|
+
# Read bytes and decode by hand so CRLF in the rule is kept as written
|
|
82
|
+
try:
|
|
83
|
+
return path.read_bytes().decode("utf-8")
|
|
84
|
+
except (OSError, UnicodeDecodeError) as exc:
|
|
85
|
+
raise GdiffError(f"Cannot read rule file {path}: {exc}") from None
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def write_user_rule(*, overwrite: bool = True) -> Path:
|
|
89
|
+
"""Copy the built-in rule to the config dir.
|
|
90
|
+
|
|
91
|
+
With overwrite=False the target is created exclusively and
|
|
92
|
+
FileExistsError is raised if it already exists.
|
|
93
|
+
"""
|
|
94
|
+
source = default_rule_path()
|
|
95
|
+
if not source.is_file():
|
|
96
|
+
raise GdiffError(f"Built-in rule file is missing: {source}")
|
|
97
|
+
target = user_rule_path()
|
|
98
|
+
|
|
99
|
+
# Directory problems are always a GdiffError, never FileExistsError
|
|
100
|
+
try:
|
|
101
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
102
|
+
except OSError as exc:
|
|
103
|
+
raise GdiffError(f"Cannot write {target}: {exc}") from None
|
|
104
|
+
|
|
105
|
+
if overwrite:
|
|
106
|
+
try:
|
|
107
|
+
shutil.copyfile(source, target)
|
|
108
|
+
except OSError as exc:
|
|
109
|
+
raise GdiffError(f"Cannot write {target}: {exc}") from None
|
|
110
|
+
return target
|
|
111
|
+
|
|
112
|
+
created = False # pragma: no mutate
|
|
113
|
+
try:
|
|
114
|
+
with source.open("rb") as src, target.open("xb") as dst:
|
|
115
|
+
created = True
|
|
116
|
+
shutil.copyfileobj(src, dst)
|
|
117
|
+
except OSError as exc:
|
|
118
|
+
if created:
|
|
119
|
+
try:
|
|
120
|
+
target.unlink(missing_ok=True)
|
|
121
|
+
except OSError as cleanup_exc:
|
|
122
|
+
raise GdiffError(
|
|
123
|
+
f"Cannot write {target}: {exc}. "
|
|
124
|
+
f"Also failed to remove the partial file: {cleanup_exc}"
|
|
125
|
+
) from None
|
|
126
|
+
elif isinstance(exc, FileExistsError):
|
|
127
|
+
raise # "xb" rejected an existing target: the caller decides
|
|
128
|
+
raise GdiffError(f"Cannot write {target}: {exc}") from None
|
|
129
|
+
return target
|
gdiff/ui.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Colours and the few messages shared by every command."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import sys
|
|
5
|
+
from typing import TextIO
|
|
6
|
+
|
|
7
|
+
_RED = "\033[0;31m"
|
|
8
|
+
_GREEN = "\033[0;32m"
|
|
9
|
+
_BOLD = "\033[1m"
|
|
10
|
+
_RESET = "\033[0m"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def red(text: str, stream: TextIO | None = None) -> str:
|
|
14
|
+
return _paint(_RED, text, stream or sys.stderr)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def green(text: str, stream: TextIO | None = None) -> str:
|
|
18
|
+
return _paint(_GREEN, text, stream or sys.stdout)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def bold(text: str, stream: TextIO | None = None) -> str:
|
|
22
|
+
return _paint(_BOLD, text, stream or sys.stdout)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def error(label: str, message: str, hint: str | None = None) -> None:
|
|
26
|
+
print(f"{red(label)} {message}", file=sys.stderr)
|
|
27
|
+
if hint:
|
|
28
|
+
print(hint, file=sys.stderr)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def success(message: str) -> None:
|
|
32
|
+
print(f"{green('✓')} {message}")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def confirm(message: str) -> bool:
|
|
36
|
+
"""Ask a y/N question on stdout. Anything but y/yes (or EOF) means no."""
|
|
37
|
+
sys.stdout.write(f"{red('Warning:', sys.stdout)} {message} (y/N): ")
|
|
38
|
+
sys.stdout.flush()
|
|
39
|
+
answer = sys.stdin.readline().strip().lower()
|
|
40
|
+
return answer in ("y", "yes")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _paint(code: str, text: str, stream: TextIO) -> str:
|
|
44
|
+
if os.environ.get("NO_COLOR") or not stream.isatty():
|
|
45
|
+
return text
|
|
46
|
+
|
|
47
|
+
return f"{code}{text}{_RESET}"
|
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: gdiff-cli
|
|
3
|
+
Version: 2.0.0
|
|
4
|
+
Summary: Copy your git diff plus a commit-message rule to the clipboard
|
|
5
|
+
Author-email: crazy <0crazy.dev@gmail.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/0Crazy-0/gdiff
|
|
8
|
+
Project-URL: Issues, https://github.com/0Crazy-0/gdiff/issues
|
|
9
|
+
Project-URL: Changelog, https://github.com/0Crazy-0/gdiff/releases
|
|
10
|
+
Keywords: git,diff,commit,conventional-commits,clipboard,llm,cli
|
|
11
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
12
|
+
Classifier: Environment :: Console
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Topic :: Software Development :: Version Control :: Git
|
|
21
|
+
Classifier: Topic :: Utilities
|
|
22
|
+
Requires-Python: >=3.10
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
Dynamic: license-file
|
|
26
|
+
|
|
27
|
+
# gdiff
|
|
28
|
+
|
|
29
|
+
> **A tiny, 100% local, and free CLI that bridges your git history and any LLM: generate conventional commit messages from your staged changes, or revisit past commits to review or rewrite them.**
|
|
30
|
+
|
|
31
|
+
---
|
|
32
|
+
|
|
33
|
+
[](#windows-installation)
|
|
34
|
+
[](#debian)
|
|
35
|
+
[](#fedora)
|
|
36
|
+
[](#arch)
|
|
37
|
+
[](#linux--macos)
|
|
38
|
+
[](https://opensource.org/licenses/MIT)
|
|
39
|
+
[](https://www.python.org/)
|
|
40
|
+
[](#)
|
|
41
|
+
|
|
42
|
+
Have you ever spent 10 minutes staring at a terminal, trying to figure out what to write in your commit message? Or needed to quickly re-read an old commit, or hand it to an LLM? `gdiff` is built to solve exactly that, without the bloated dependencies, paid API keys, or heavy local setups that other commit-helpers force upon you.
|
|
43
|
+
|
|
44
|
+
---
|
|
45
|
+
|
|
46
|
+
## What Can It Do?
|
|
47
|
+
|
|
48
|
+
`gdiff` has three modes. Pick the one that matches what you are looking at:
|
|
49
|
+
|
|
50
|
+
| Command | Reads | Output | Rule appended |
|
|
51
|
+
| :--- | :--- | :--- | :---: |
|
|
52
|
+
| `gdiff` | your staged changes | clipboard | yes |
|
|
53
|
+
| `gdiff -c [REF]` | the diff of a past commit | clipboard | yes |
|
|
54
|
+
| `gdiff message [REF]` | the message of a past commit | terminal | no |
|
|
55
|
+
|
|
56
|
+
Two modifiers tweak the diff output: `-p` prints instead of copying, and `-d` copies only the diff, without the rule. You can also manage your prompt rule with `gdiff rule <path|init|reset>`.
|
|
57
|
+
|
|
58
|
+
---
|
|
59
|
+
|
|
60
|
+
## The Philosophy Behind gdiff
|
|
61
|
+
|
|
62
|
+
Most AI commit assistants are overly complicated. They demand:
|
|
63
|
+
* **Heavy environments**: Large `npm` installations, heavy dependency trees, and background runtime processes.
|
|
64
|
+
* **Paid API Keys**: Subscriptions to proprietary models (which can get expensive).
|
|
65
|
+
* **Opaque and Static Prompts**: Prompts hardcoded behind the scenes that output generic, dry commit descriptions that do not truly capture the essence or tone of your work.
|
|
66
|
+
|
|
67
|
+
`gdiff` takes a completely different, **human-centric, ultra-lightweight approach**:
|
|
68
|
+
|
|
69
|
+
1. **No API Keys & Completely Free**: It doesn't connect directly to any API. It sends your diffs + prompt guidelines to your system clipboard, so you can paste them anywhere: **any web LLM interface** (Gemini, ChatGPT, Claude), your **IDE-integrated AI chat**, or **any agent CLI** (opencode, Claude Code, Codex, agy). You can also teach your agent to run `gdiff --print` on its own, so it reads your rule and writes the commit for you, for example right after finishing a feature or a refactor.
|
|
70
|
+
2. **100% Customizable Prompts**: Your rules live in a plain text file (`rule.txt`). You can easily tweak the guidelines to fit the way you work: your team's conventions, your project, or your personal style.
|
|
71
|
+
3. **Your Whole History, Not Just What Is Staged**: Write a message for new changes, or grab the diff and message of any past commit to read it, review it, or hand it to an LLM.
|
|
72
|
+
4. **Zero-Dependency & Cross-Platform**: Written in pure Python (3.10+) using only the standard library—no third-party packages required. Runs natively on **Linux**, **macOS**, and **Windows** with only `git` and a system clipboard tool.
|
|
73
|
+
|
|
74
|
+
---
|
|
75
|
+
|
|
76
|
+
## Quick Start
|
|
77
|
+
|
|
78
|
+
### 1. Installation
|
|
79
|
+
|
|
80
|
+
**Requirements:**
|
|
81
|
+
* **Python 3.10+**
|
|
82
|
+
* **Git**
|
|
83
|
+
* On Linux: a clipboard utility (`wl-clipboard` for Wayland, or `xclip` / `xsel` for X11). macOS (`pbcopy`) and Windows (`clip.exe`) have built-in clipboard tools.
|
|
84
|
+
|
|
85
|
+
#### System Package Managers & Universal Installers
|
|
86
|
+
|
|
87
|
+
| OS / Distro | Package Manager | Install Command | Update Command |
|
|
88
|
+
| :--- | :--- | :--- | :--- |
|
|
89
|
+
| <a id="windows-installation"></a>**Windows** (PowerShell / Git Bash / MSYS2) | Universal script | Run in **PowerShell** (also for **Git Bash / MSYS2** users): `irm https://raw.githubusercontent.com/0Crazy-0/gdiff/main/windows-setup.ps1 \| iex` <br> or from **WSL**: `curl -fsSL https://raw.githubusercontent.com/0Crazy-0/gdiff/main/install.sh \| sh` | re-run the same command |
|
|
90
|
+
| <a id="debian"></a>**Debian / Ubuntu** | APT | `curl -fsSL https://raw.githubusercontent.com/0Crazy-0/gdiff/main/debian-setup.sh \| sudo bash` | `sudo apt update && sudo apt install gdiff` |
|
|
91
|
+
| <a id="fedora"></a>**Fedora** | COPR (DNF) | `sudo dnf copr enable crazy/gdiff && sudo dnf install gdiff` | `sudo dnf upgrade gdiff` |
|
|
92
|
+
| <a id="arch"></a>**Arch Linux** | AUR | `yay -S gdiff` <br> `paru -S gdiff` | `yay -S gdiff` <br> `paru -S gdiff` <br> (or simply `yay` / `paru`) |
|
|
93
|
+
| <a id="linux--macos"></a>**Linux / macOS** (any distro) | Universal script | `curl -fsSL https://raw.githubusercontent.com/0Crazy-0/gdiff/main/install.sh \| sh` <br> (**Windows** users: use the PowerShell command in the [Windows Installation](#windows-installation) row instead) | re-run the same command |
|
|
94
|
+
|
|
95
|
+
#### Python Package Managers
|
|
96
|
+
|
|
97
|
+
Install `gdiff` globally using your preferred Python tool manager:
|
|
98
|
+
|
|
99
|
+
```bash
|
|
100
|
+
# Using uv
|
|
101
|
+
uv tool install gdiff-cli
|
|
102
|
+
|
|
103
|
+
# Using pipx
|
|
104
|
+
pipx install gdiff-cli
|
|
105
|
+
|
|
106
|
+
# Using pip
|
|
107
|
+
pip install gdiff-cli
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Or install directly from GitHub:
|
|
111
|
+
|
|
112
|
+
```bash
|
|
113
|
+
uv tool install git+https://github.com/0Crazy-0/gdiff.git
|
|
114
|
+
# or
|
|
115
|
+
pip install git+https://github.com/0Crazy-0/gdiff.git
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
<details>
|
|
119
|
+
<summary>Installing from a local clone (development)</summary>
|
|
120
|
+
|
|
121
|
+
```bash
|
|
122
|
+
git clone https://github.com/0Crazy-0/gdiff.git
|
|
123
|
+
cd gdiff
|
|
124
|
+
|
|
125
|
+
# Using uv (uv does not activate .venv, so prefix commands with "uv run")
|
|
126
|
+
uv sync
|
|
127
|
+
uv run gdiff --version
|
|
128
|
+
|
|
129
|
+
# Using pip
|
|
130
|
+
pip install -e .
|
|
131
|
+
gdiff --version
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
</details>
|
|
135
|
+
|
|
136
|
+
### 2. Prepare Your Changes
|
|
137
|
+
Stage the code changes you want to commit:
|
|
138
|
+
```bash
|
|
139
|
+
git add src/my-feature.js
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
### 3. Run gdiff
|
|
143
|
+
Execute the CLI tool in the root of your Git repository:
|
|
144
|
+
```bash
|
|
145
|
+
gdiff
|
|
146
|
+
```
|
|
147
|
+
*Output:*
|
|
148
|
+
```text
|
|
149
|
+
✓ Diff with default rule copied to clipboard
|
|
150
|
+
```
|
|
151
|
+
*(If you have initialized a custom user rule or passed `-r`, it prints `✓ Diff with rule copied to clipboard`.)*
|
|
152
|
+
|
|
153
|
+
### 4. Ask the AI and Commit!
|
|
154
|
+
Paste the clipboard contents into any AI chat, copy the suggested message, and commit:
|
|
155
|
+
```bash
|
|
156
|
+
git commit -m "feat(core): add authentication gateway"
|
|
157
|
+
```
|
|
158
|
+
---
|
|
159
|
+
|
|
160
|
+
## How-To Guides (Recipes)
|
|
161
|
+
|
|
162
|
+
### How to Customize the Default Prompt Rule
|
|
163
|
+
Out of the box, `gdiff` uses its built-in conventional commits rule. To create your own editable copy in `~/.config/gdiff/rule.txt` (on Windows: `%APPDATA%\gdiff\rule.txt`):
|
|
164
|
+
|
|
165
|
+
```bash
|
|
166
|
+
gdiff rule init
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
Then open and edit the generated file:
|
|
170
|
+
```bash
|
|
171
|
+
nano ~/.config/gdiff/rule.txt
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
The next time you run `gdiff`, your customized prompt will automatically be appended.
|
|
175
|
+
|
|
176
|
+
* Check which rule file is currently active: `gdiff rule path`
|
|
177
|
+
* Reset your rule back to the built-in default: `gdiff rule reset`
|
|
178
|
+
|
|
179
|
+
### How to Use a One-off Rule
|
|
180
|
+
To use a custom `.txt` prompt file for a single execution:
|
|
181
|
+
```bash
|
|
182
|
+
gdiff --rule ./custom-rules.txt
|
|
183
|
+
# or
|
|
184
|
+
gdiff -r ./custom-rules.txt
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
### How to Print Output Without Copying
|
|
188
|
+
If you want to view the exact prompt content that would be copied to the clipboard, or if you want to pipe the prompt output directly to a local terminal command, use the `--print` flag:
|
|
189
|
+
```bash
|
|
190
|
+
gdiff --print
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
### How to Copy the Diff of an Existing Commit
|
|
194
|
+
If you want to copy or review the diff of a commit that has already been made instead of staged changes, use the `-c` or `--commit` flag with an optional position, commit hash, or ref:
|
|
195
|
+
|
|
196
|
+
```bash
|
|
197
|
+
# Copy the diff of the latest commit (HEAD)
|
|
198
|
+
gdiff -c
|
|
199
|
+
|
|
200
|
+
# Copy the diff of the second most recent commit (next in git log)
|
|
201
|
+
gdiff -c 2
|
|
202
|
+
|
|
203
|
+
# Copy the diff of a specific commit by hash
|
|
204
|
+
gdiff -c a1b2c3d
|
|
205
|
+
|
|
206
|
+
# Copy the diff of a specific ref or tag
|
|
207
|
+
gdiff -c v2.0.0
|
|
208
|
+
|
|
209
|
+
# Print the diff of a commit to stdout without the rule
|
|
210
|
+
gdiff -c 2 -d -p
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
> **Note on merge commits:** Numeric positions count in `git log` order, so every reachable commit counts, including merge commits and the commits of merged branches. Regardless of position, for merge commits `gdiff` generates the diff against the first parent (the target branch that received the merge), so the diff shows all the changes introduced by the merge as a whole. The same position semantics apply to `gdiff message`.
|
|
214
|
+
|
|
215
|
+
### How to View an Existing Commit Message
|
|
216
|
+
If you only need to recall the exact message of a past commit (to reuse it, review it, or fix a typo) instead of its diff, use the `message` subcommand. It accepts the same kind of reference as `--commit` (a position, commit hash, or ref) and prints the message to the terminal exactly as it was written:
|
|
217
|
+
|
|
218
|
+
```bash
|
|
219
|
+
# Print the message of the latest commit (HEAD)
|
|
220
|
+
gdiff message
|
|
221
|
+
|
|
222
|
+
# Print the message of the second most recent commit
|
|
223
|
+
gdiff message 2
|
|
224
|
+
|
|
225
|
+
# Print the message of a specific commit by hash or ref
|
|
226
|
+
gdiff message a1b2c3d
|
|
227
|
+
gdiff message v2.0.0
|
|
228
|
+
|
|
229
|
+
# Add a header with hash, author and date above the message
|
|
230
|
+
gdiff message 2 -i
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
*Output of `gdiff message -i`:*
|
|
234
|
+
```text
|
|
235
|
+
Commit: a1b2c3d4e5f6...
|
|
236
|
+
Short: a1b2c3d
|
|
237
|
+
Author: Your Name <you@example.com>
|
|
238
|
+
Date: Sat Nov 7 20:35:55 2026 -0500
|
|
239
|
+
|
|
240
|
+
feat(core): add authentication gateway
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
> **Note:** `gdiff message` prints to the terminal and never touches the clipboard or your rule file, so it skips rule resolution entirely. It cannot be combined with `-c`, `-r`, `-p`, or `-d`.
|
|
244
|
+
|
|
245
|
+
---
|
|
246
|
+
|
|
247
|
+
## Reference
|
|
248
|
+
|
|
249
|
+
### Usage
|
|
250
|
+
```text
|
|
251
|
+
gdiff [flags]
|
|
252
|
+
gdiff <command> [args]
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
### Default Flags (`gdiff [flags]`)
|
|
256
|
+
|
|
257
|
+
| Flag | Long Option | Description |
|
|
258
|
+
| :--- | :--- | :--- |
|
|
259
|
+
| `-c [REF]` | `--commit [REF]` | Diff of a commit: position, hash or ref (default: `1` = latest commit `HEAD`). Positions count from the latest commit in `git log` order, including merge commits and the commits of merged branches. |
|
|
260
|
+
| `-r <file>` | `--rule <file>` | Path to a custom rule file (`.txt`) to append instead of the default. Cannot be combined with `-d`. |
|
|
261
|
+
| `-p` | `--print` | Print the output directly to `stdout` instead of copying to the clipboard. |
|
|
262
|
+
| `-d` | `--diff-only` | Copy only the diff, without appending the rule. Cannot be combined with `-r`. |
|
|
263
|
+
| `-v` | `--version` | Display the installed version. |
|
|
264
|
+
| `-h` | `--help` | Show help information. |
|
|
265
|
+
|
|
266
|
+
### Commands
|
|
267
|
+
|
|
268
|
+
#### `gdiff message [REF] [-i]`
|
|
269
|
+
Print a commit message to the terminal, exactly as written.
|
|
270
|
+
|
|
271
|
+
| Argument / Flag | Description |
|
|
272
|
+
| :--- | :--- |
|
|
273
|
+
| `REF` | Commit position, hash or ref (default: `1` = latest commit `HEAD`). |
|
|
274
|
+
| `-i`, `--info` | Prepend a header with the commit hash, short hash, author and date. |
|
|
275
|
+
| `-h`, `--help` | Show help information for `message`. |
|
|
276
|
+
|
|
277
|
+
#### `gdiff rule <path|init|reset>`
|
|
278
|
+
Show which rule file is used and manage your personal rule file.
|
|
279
|
+
|
|
280
|
+
| Action | Description |
|
|
281
|
+
| :--- | :--- |
|
|
282
|
+
| `path` | Show which rule file is currently being used. |
|
|
283
|
+
| `init` | Create an editable copy of the built-in default rule in your config directory (does not overwrite an existing file). |
|
|
284
|
+
| `reset` | Overwrite your user rule file with the built-in default rule (prompts for confirmation if one exists). |
|
|
285
|
+
|
|
286
|
+
### Rule Precedence Order
|
|
287
|
+
`gdiff` evaluates which rule file to use in the following strict hierarchy (from highest priority to lowest):
|
|
288
|
+
|
|
289
|
+
1. **Command-Line Override**: `--rule <file>` / `-r <file>` (must have a `.txt` extension).
|
|
290
|
+
2. **User Config**: `~/.config/gdiff/rule.txt` on Linux/macOS (respects `$XDG_CONFIG_HOME`), or `%APPDATA%\gdiff\rule.txt` on Windows. You can override the config directory on any OS with `$GDIFF_CONFIG_HOME`.
|
|
291
|
+
3. **Built-in Default Rule**: The default rule packaged inside `gdiff`.
|
|
292
|
+
|
|
293
|
+
### Supported Clipboard Managers
|
|
294
|
+
`gdiff` automatically detects your environment and picks the right clipboard tool:
|
|
295
|
+
* **Wayland**: `wl-copy` (from `wl-clipboard`, when `WAYLAND_DISPLAY` is set)
|
|
296
|
+
* **X11 (Xorg)**: `xclip` or `xsel` (when `DISPLAY` is set)
|
|
297
|
+
* **macOS**: `pbcopy` (built-in)
|
|
298
|
+
* **Windows / WSL / Git Bash**: `clip.exe` (built-in)
|
|
299
|
+
|
|
300
|
+
---
|
|
301
|
+
|
|
302
|
+
## Explanation
|
|
303
|
+
|
|
304
|
+
### Why Separating Prompt Logic from API Orchestration is Better
|
|
305
|
+
Many tools in the modern ecosystem execute API requests directly. While convenient, this introduces several flaws:
|
|
306
|
+
* **Privacy & API Keys**: It forces the user to buy API credits, expose sensitive credentials in configuration environments, or trust the CLI tool not to leak keys.
|
|
307
|
+
* **Obsolescence**: As models are deprecated, the client must be continuously updated.
|
|
308
|
+
* **Ineffective Prompts**: Hardcoded prompts cannot easily adapt to diverse workspaces.
|
|
309
|
+
|
|
310
|
+
By decoupling context gathering (`git diff`, `git show`, `git log`) and instruction formatting (`rule.txt`) from AI querying, `gdiff` remains resilient. The clipboard acts as a universal bridge, allowing you to use cutting-edge web models, local desktop clients, agent CLIs, or your workplace's AI endpoints seamlessly and at zero cost.
|
|
311
|
+
|
|
312
|
+
---
|
|
313
|
+
|
|
314
|
+
## License
|
|
315
|
+
|
|
316
|
+
This project is licensed under the [MIT License](LICENSE).
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
gdiff/__init__.py,sha256=_7OlQdbVkK4jad0CLdpI0grT-zEAb-qgFmH5mFzDXiA,22
|
|
2
|
+
gdiff/__main__.py,sha256=WeUIi6i5MsKFGvEhHZVkHBkMF5yrpUNBZhsG5VQnB7M,57
|
|
3
|
+
gdiff/cli.py,sha256=5fSQWi5WUUDR5Oo3zMumU52xTnL556Gmf6Ci94_qgOY,3870
|
|
4
|
+
gdiff/clipboard.py,sha256=PYHY4wBBYXQSn4yEtKwwvY0DtOQOpo7rrdIeIIP0gU0,1519
|
|
5
|
+
gdiff/errors.py,sha256=l99L9KemtqdblDkHCJKnYy1GMIYYWg6nmnARabIXWE0,405
|
|
6
|
+
gdiff/git.py,sha256=1fuT3R5pXYGc5ohrHxscYaInlhytNjRgzr76GJOHax4,4015
|
|
7
|
+
gdiff/rules.py,sha256=Sk68ujKGmHxH8_EyTbsRE2_fk43920e_DTIsqVaPTjk,4076
|
|
8
|
+
gdiff/ui.py,sha256=tVwKWFcBFJBt0ZhHNG30o1WbxSGckV3_J1gA0wt-QHs,1247
|
|
9
|
+
gdiff/commands/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
10
|
+
gdiff/commands/generate.py,sha256=aBVHvI_Oq31khDfFLkddngLZ1V6s1Venj1qkfQSsiVA,2974
|
|
11
|
+
gdiff/commands/message.py,sha256=0FdkrvWo90ifOwXHR7njGj1DUeZtXjN068FKmtUzqQs,1435
|
|
12
|
+
gdiff/commands/rule.py,sha256=EGKJjyAG_bbRRXA-9oEr9y8lEN1SZD4y9k_KUEBsffw,2762
|
|
13
|
+
gdiff/data/rule.txt,sha256=78s3WY0HBYOWGTt5UpmtjbR-zZNH7FBpI_DDNKRCPVg,1704
|
|
14
|
+
gdiff_cli-2.0.0.dist-info/licenses/LICENSE,sha256=riE6GqnwfD6ZPxSXdPB4Jg3HevmR7CEgBLCI58iOr5A,1062
|
|
15
|
+
gdiff_cli-2.0.0.dist-info/METADATA,sha256=VTbzWTe2BhCun7lHarZm9zUxFrah9xZG744CUhUMflY,14659
|
|
16
|
+
gdiff_cli-2.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
17
|
+
gdiff_cli-2.0.0.dist-info/entry_points.txt,sha256=blYy1XPI7Mth8hg-2udX9evU4-zDqtCNZTdEekN2tgY,41
|
|
18
|
+
gdiff_cli-2.0.0.dist-info/top_level.txt,sha256=Tr_T_u5NMYo5w5YJlQ58pPii3--Kkh4DzdQ_Pe80-Rs,6
|
|
19
|
+
gdiff_cli-2.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Crazy
|
|
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.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
gdiff
|