-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathgit-install-conventional-commit-hook
More file actions
executable file
·221 lines (192 loc) · 6.44 KB
/
git-install-conventional-commit-hook
File metadata and controls
executable file
·221 lines (192 loc) · 6.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
#!/usr/bin/env rust-script
//! ```cargo
//! [dependencies]
//! clap = { version = "4.5.48", features = ["derive"] }
//! ```
//!
//! Install a commit-msg hook that validates commit messages with git-validate-conventional-commit
use clap::Parser;
#[cfg(not(unix))]
use std::ffi::OsStr;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, exit};
const EXIT_OK: i32 = 0;
const EXIT_DATAERR: i32 = 65; // bad input / not found
const EXIT_SOFTWARE: i32 = 70; // unexpected internal failure
#[derive(Parser, Debug)]
#[command(name = "git-install-conventional-commit-hook")]
#[command(
about = "Install a commit-msg hook that enforces git-conventional-commit message rules",
long_about = None
)]
struct Args {
/// Overwrite an existing hook file
#[arg(long)]
force: bool,
/// Install into a custom hooks directory (defaults to core.hooksPath, else .git/hooks)
#[arg(long, value_name = "DIR")]
hooks_dir: Option<PathBuf>,
/// Validator executable to run from the hook (defaults to git-validate-conventional-commit found in PATH)
#[arg(long, value_name = "PATH")]
validator: Option<PathBuf>,
}
fn main() {
// Handle --help in raw args before clap parsing
let raw_args: Vec<String> = std::env::args().collect();
if raw_args.iter().any(|arg| arg == "--help" || arg == "-h") {
Args::parse_from(&["git-install-conventional-commit-hook", "--help"]);
return;
}
let args = Args::parse();
// Check we're in a git repository
if !Command::new("git")
.args(&["rev-parse", "--git-dir"])
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.unwrap_or_else(|e| {
eprintln!("✗ ERROR: Failed to execute git rev-parse");
eprintln!("DETAILS: {}", e);
exit(EXIT_SOFTWARE);
})
.success()
{
eprintln!("✗ ERROR: Not a git repository (or any of the parent directories).");
eprintln!("NEXT: cd into a repo, or run: git init");
exit(EXIT_DATAERR);
}
let hooks_dir = args
.hooks_dir
.unwrap_or_else(|| detect_hooks_dir().unwrap_or_else(|e| die(EXIT_SOFTWARE, &e)));
let validator = args
.validator
.or_else(|| find_in_path("git-validate-conventional-commit"))
.unwrap_or_else(|| {
die(
EXIT_DATAERR,
"Unable to find git-validate-conventional-commit in PATH.\nNEXT: Add git-tools to PATH or pass --validator <path>.",
)
});
if !validator.exists() {
die(
EXIT_DATAERR,
&format!("Validator not found: {}", validator.display()),
);
}
fs::create_dir_all(&hooks_dir).unwrap_or_else(|e| {
die(
EXIT_SOFTWARE,
&format!(
"Failed to create hooks directory {}: {}",
hooks_dir.display(),
e
),
)
});
let hook_path = hooks_dir.join("commit-msg");
if hook_path.exists() && !args.force {
die(
EXIT_DATAERR,
&format!(
"Hook already exists: {}\nNEXT: Rerun with --force to overwrite.",
hook_path.display()
),
);
}
let validator_quoted = sh_single_quote(&validator.to_string_lossy());
let hook_contents = format!(
"#!/bin/sh\nset -eu\nexec {} \"$1\"\n",
validator_quoted
);
fs::write(&hook_path, hook_contents).unwrap_or_else(|e| {
die(
EXIT_SOFTWARE,
&format!("Failed to write hook {}: {}", hook_path.display(), e),
)
});
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mut perms = fs::metadata(&hook_path)
.unwrap_or_else(|e| die(EXIT_SOFTWARE, &format!("Failed to stat hook: {}", e)))
.permissions();
perms.set_mode(0o755);
fs::set_permissions(&hook_path, perms)
.unwrap_or_else(|e| die(EXIT_SOFTWARE, &format!("Failed to chmod hook: {}", e)));
}
println!("✓ Installed commit-msg hook: {}", hook_path.display());
println!(" → Validator: {}", validator.display());
exit(EXIT_OK);
}
fn die(code: i32, message: &str) -> ! {
eprintln!("✗ ERROR: {}", message);
exit(code);
}
fn detect_hooks_dir() -> Result<PathBuf, String> {
let hooks_path = git_output_optional(&["config", "--get", "core.hooksPath"]);
if let Some(value) = hooks_path {
let path = PathBuf::from(value);
if path.is_absolute() {
return Ok(path);
}
let root = git_output(&["rev-parse", "--show-toplevel"])?;
return Ok(PathBuf::from(root).join(path));
}
let hooks = git_output(&["rev-parse", "--git-path", "hooks"])?;
Ok(PathBuf::from(hooks))
}
fn git_output(args: &[&str]) -> Result<String, String> {
let output = Command::new("git")
.args(args)
.output()
.map_err(|e| format!("Failed to execute git {}: {}", args.join(" "), e))?;
if !output.status.success() {
return Err(format!("git {} failed", args.join(" ")));
}
Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}
fn git_output_optional(args: &[&str]) -> Option<String> {
let output = Command::new("git").args(args).output().ok()?;
if !output.status.success() {
return None;
}
let value = String::from_utf8_lossy(&output.stdout).trim().to_string();
if value.is_empty() {
None
} else {
Some(value)
}
}
fn find_in_path(name: &str) -> Option<PathBuf> {
let path_env = std::env::var_os("PATH")?;
for dir in std::env::split_paths(&path_env) {
let candidate = dir.join(name);
if is_executable_file(&candidate) {
return Some(candidate);
}
}
None
}
fn is_executable_file(path: &Path) -> bool {
if !path.is_file() {
return false;
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
return fs::metadata(path)
.map(|m| (m.permissions().mode() & 0o111) != 0)
.unwrap_or(false);
}
#[cfg(not(unix))]
{
// Best-effort on non-Unix platforms: allow common executable extensions.
let ext = path.extension().and_then(OsStr::to_str).unwrap_or("");
return matches!(ext.to_ascii_lowercase().as_str(), "exe" | "bat" | "cmd" | "ps1");
}
}
fn sh_single_quote(raw: &str) -> String {
let escaped = raw.replace('\'', "'\"'\"'");
format!("'{}'", escaped)
}