release-kit 0.9.15

A canonical release workflow: a technology-agnostic method, per-technology bindings, and the rk CLI that lands and serves them.
Documentation
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//! What rk reads about a project's git hooks, for its reports alone.
//!
//! rk runs no hook manager. `rk integrate` asks git to run the clone's
//! `pre-merge-commit` hook, and git runs whatever the project installed.
//! This module only reads: which hook manager wrote each installed hook,
//! for `rk doctor`, and which nested hook configuration prek would run as a
//! project of its own, for `rk status`. Neither answer changes what any
//! verb runs.
//!
//! SATISFIES tool-requirements:the-doctor-reports-the-hook-runner
//! SATISFIES tool-requirements:a-nested-hook-configuration-is-reported

use std::path::{Path, PathBuf};
use std::process::Command;

use crate::maintenance::GIT_HOOK_VARS;

/// The hook events the landed block and the integration gate use.
pub const EVENTS: [&str; 4] = ["pre-commit", "commit-msg", "pre-push", "pre-merge-commit"];

/// Who wrote one installed hook, read from the header its manager writes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Writer {
    /// prek: `# File generated by prek`.
    Prek,
    /// pre-commit: `# File generated by pre-commit`.
    PreCommit,
    /// No known manager: the project's own hook.
    Own,
    /// A hook git's configuration defines, by `hook.<name>.event`, which
    /// git 2.54 and newer run beside the hooks directory.
    Configured,
}

impl Writer {
    /// The manager's binary, where a known one wrote the hook.
    #[must_use]
    pub const fn manager(self) -> Option<&'static str> {
        match self {
            Self::Prek => Some("prek"),
            Self::PreCommit => Some("pre-commit"),
            Self::Own | Self::Configured => None,
        }
    }
}

/// One installed hook: its event and who wrote it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Installed {
    /// The hook event, for example `pre-merge-commit`.
    pub event: &'static str,
    /// Who wrote it.
    pub writer: Writer,
}

/// A git call in `dir`, with the hook variables scrubbed and git's own
/// words untranslated, because `git hook list` translates the name it
/// gives the hooks directory's file; `None` where git does not answer.
fn git(dir: &Path, args: &[&str]) -> Option<std::process::Output> {
    let mut command = Command::new(crate::probes::git_bin());
    for var in GIT_HOOK_VARS {
        command.env_remove(var);
    }
    command.env("LC_ALL", "C");
    command
        .arg("-C")
        .arg(dir)
        .args(args)
        .output()
        .ok()
        .filter(|output| output.status.success())
}

/// The hooks installed in the repository at `dir`, through git's own path
/// to its hooks directory, `core.hooksPath` included; `None` outside a
/// repository.
#[must_use]
pub fn installed(dir: &Path) -> Option<Vec<Installed>> {
    git(dir, &["rev-parse", "--is-inside-work-tree"])?;
    let mut found = Vec::new();
    for event in EVENTS {
        let Some(answer) = git(dir, &["rev-parse", "--git-path", &format!("hooks/{event}")]) else {
            continue;
        };
        let path = PathBuf::from(String::from_utf8_lossy(&answer.stdout).trim());
        let path = if path.is_relative() {
            dir.join(path)
        } else {
            path
        };
        if !executable(&path) {
            continue;
        }
        let head: String = std::fs::read_to_string(&path)
            .unwrap_or_default()
            .lines()
            .take(5)
            .collect::<Vec<_>>()
            .join("\n");
        let writer = if head.contains("# File generated by prek") {
            Writer::Prek
        } else if head.contains("# File generated by pre-commit") {
            Writer::PreCommit
        } else {
            Writer::Own
        };
        found.push(Installed { event, writer });
    }
    for event in EVENTS {
        for _ in configured(dir, event) {
            found.push(Installed {
                event,
                writer: Writer::Configured,
            });
        }
    }
    Some(found)
}

/// The hooks git's configuration defines for `event` and runs, by name.
/// `git hook list` names each, names the hooks directory's own file as
/// `hook from hookdir`, which [`installed`] already read, and marks a
/// hook that `hook.<name>.enabled` turns off with `disabled` and a tab,
/// which git does not run. A git older than 2.54 has no `list` and
/// defines none.
fn configured(dir: &Path, event: &str) -> Vec<String> {
    git(dir, &["hook", "list", event]).map_or_else(Vec::new, |listed| {
        String::from_utf8_lossy(&listed.stdout)
            .lines()
            .filter(|line| !line.starts_with("disabled\t"))
            .map(str::trim)
            .filter(|name| !name.is_empty() && *name != "hook from hookdir")
            .map(str::to_owned)
            .collect()
    })
}

/// Whether `path` is a file git would run as a hook.
fn executable(path: &Path) -> bool {
    std::fs::metadata(path).is_ok_and(|meta| {
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt as _;
            meta.is_file() && meta.permissions().mode() & 0o111 != 0
        }
        #[cfg(not(unix))]
        {
            meta.is_file()
        }
    })
}

/// The nested hook configurations of `target` that prek would run.
///
/// Every tracked `.pre-commit-config.yaml` below the root whose every
/// directory prek's walk enters. prek judges each directory by three
/// layers of ignore rules, the first that names it winning: the
/// `.prekignore` files of the root and of each directory above it, then
/// the `.ignore` files, then git's own rules, `.gitignore`,
/// `info/exclude`, and the global excludes. A hidden directory is skipped
/// unless a rule keeps it, and a Cookiecutter template directory always.
/// git's own matcher judges each layer: the two custom layers in a
/// scratch repository that holds their files as `.gitignore`, and git's
/// rules in the target.
#[must_use]
pub fn unexcluded_nested_configs(target: &Path) -> Vec<String> {
    let target = std::path::absolute(target).unwrap_or_else(|_| target.to_path_buf());
    let Some(listed) = git(
        &target,
        &["ls-files", "-z", "--", ":(glob)**/.pre-commit-config.yaml"],
    ) else {
        return Vec::new();
    };
    let nested: Vec<String> = String::from_utf8_lossy(&listed.stdout)
        .split('\0')
        .filter(|path| path.contains('/'))
        .map(str::to_owned)
        .collect();
    if nested.is_empty() {
        return nested;
    }
    // Every directory a nested configuration sits in or below, in walk
    // order, each judged once.
    let mut dirs: Vec<String> = Vec::new();
    for path in &nested {
        let parts: Vec<&str> = path.split('/').collect();
        for depth in 1..parts.len() {
            let dir = parts[..depth].join("/");
            if !dirs.contains(&dir) {
                dirs.push(dir);
            }
        }
    }
    let custom = layer(&target, &dirs, ".prekignore");
    let ignore = layer(&target, &dirs, ".ignore");
    let git_rules = judged(&target, &dirs, &[]);
    let entered = |dir: &str| {
        let name = dir.rsplit('/').next().unwrap_or(dir);
        if name.starts_with("{{") && name.ends_with("}}") && name.contains("cookiecutter") {
            return false;
        }
        let matched = custom
            .get(dir)
            .or_else(|| ignore.get(dir))
            .or_else(|| git_rules.get(dir))
            .copied();
        match matched {
            Some(Rule::Ignore) => false,
            Some(Rule::Keep) => true,
            None => !name.starts_with('.'),
        }
    };
    nested
        .into_iter()
        .filter(|path| {
            let parts: Vec<&str> = path.split('/').collect();
            (1..parts.len()).all(|depth| entered(&parts[..depth].join("/")))
        })
        .collect()
}

/// What a rule says of a directory.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Rule {
    /// A pattern ignores it.
    Ignore,
    /// A negated pattern keeps it.
    Keep,
}

/// The directories of `dirs` that one custom layer names: every `name`
/// file of the root and of the directories above each one, copied as
/// `.gitignore` into a scratch repository that also holds each
/// directory, so git judges the patterns, the directory-only ones too,
/// with no other rule of the host's.
fn layer(target: &Path, dirs: &[String], name: &str) -> std::collections::HashMap<String, Rule> {
    let mut sources: Vec<&str> = vec![""];
    sources.extend(dirs.iter().map(String::as_str));
    if !sources
        .iter()
        .any(|dir| target.join(dir).join(name).is_file())
    {
        return std::collections::HashMap::new();
    }
    let Some(scratch) = Scratch::new() else {
        return std::collections::HashMap::new();
    };
    if git(scratch.path(), &["init", "-q"]).is_none() {
        return std::collections::HashMap::new();
    }
    for dir in &sources {
        let _ = std::fs::create_dir_all(scratch.path().join(dir));
        let rules = target.join(dir).join(name);
        if rules.is_file() {
            let _ = std::fs::copy(&rules, scratch.path().join(dir).join(".gitignore"));
        }
    }
    let empty = scratch.path().join(".git/rk-no-excludes");
    let _ = std::fs::write(&empty, "");
    let _ = std::fs::write(scratch.path().join(".git/info/exclude"), "");
    let excludes = format!("core.excludesFile={}", empty.display());
    judged(scratch.path(), dirs, &["-c", &excludes])
}

/// A scratch directory under the system's temporary directory, removed
/// on drop.
struct Scratch(PathBuf);

impl Scratch {
    fn new() -> Option<Self> {
        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_or(0, |since| since.as_nanos());
        let path =
            std::env::temp_dir().join(format!("rk-prekignore-{}-{nanos}", std::process::id()));
        std::fs::create_dir(&path).ok()?;
        Some(Self(path))
    }

    fn path(&self) -> &Path {
        &self.0
    }
}

impl Drop for Scratch {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}

/// The directories of `dirs` that the ignore rules of the repository at
/// `repo` name, with `config` before the command: each matched one, as
/// ignored or kept by a negated pattern.
fn judged(
    repo: &Path,
    dirs: &[String],
    config: &[&str],
) -> std::collections::HashMap<String, Rule> {
    let mut command = Command::new(crate::probes::git_bin());
    for var in GIT_HOOK_VARS {
        command.env_remove(var);
    }
    let checked = command
        .arg("-C")
        .arg(repo)
        .args(config)
        .args(["check-ignore", "--no-index", "-v", "-n", "-z", "--stdin"])
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::null())
        .spawn()
        .and_then(|mut child| {
            use std::io::Write as _;
            // The names go in from a thread of their own while the answer
            // is read, so neither pipe can fill while the other waits.
            // No trailing slash: git then matches a negated directory
            // pattern too, and it judges the path as a directory because
            // the directory exists.
            let input: Vec<u8> = dirs
                .iter()
                .flat_map(|dir| dir.bytes().chain(std::iter::once(0)))
                .collect();
            let writer = child.stdin.take().map(|mut stdin| {
                std::thread::spawn(move || {
                    let _ = stdin.write_all(&input);
                })
            });
            let output = child.wait_with_output();
            if let Some(writer) = writer {
                let _ = writer.join();
            }
            output
        });
    let Ok(output) = checked else {
        return std::collections::HashMap::new();
    };
    // Each record is the source, the line, the pattern, and the path.
    let fields: Vec<String> = String::from_utf8_lossy(&output.stdout)
        .split('\0')
        .map(str::to_owned)
        .collect();
    let mut found = std::collections::HashMap::new();
    for record in fields.as_chunks::<4>().0 {
        let (source, pattern, path) = (&record[0], &record[2], &record[3]);
        if source.is_empty() {
            continue;
        }
        let rule = if pattern.starts_with('!') {
            Rule::Keep
        } else {
            Rule::Ignore
        };
        found.insert(path.trim_end_matches('/').to_owned(), rule);
    }
    found
}

#[cfg(test)]
mod tests {
    use super::{Rule, configured, judged};
    use std::process::Command;

    fn git_in(dir: &std::path::Path, args: &[&str]) {
        let mut command = Command::new(crate::probes::git_bin());
        for var in crate::maintenance::GIT_HOOK_VARS {
            command.env_remove(var);
        }
        let status = command
            .arg("-C")
            .arg(dir)
            .args(args)
            .status()
            .expect("git runs");
        assert!(status.success(), "{args:?}");
    }

    /// A configured hook that `hook.<name>.enabled` turns off is no hook
    /// git runs.
    #[test]
    fn a_disabled_configured_hook_is_not_counted() {
        let repo = tempfile::tempdir().expect("a scratch repository");
        git_in(repo.path(), &["init", "-q"]);
        git_in(
            repo.path(),
            &["config", "hook.review.event", "pre-merge-commit"],
        );
        git_in(repo.path(), &["config", "hook.review.command", "false"]);
        git_in(repo.path(), &["config", "hook.review.enabled", "false"]);
        assert!(configured(repo.path(), "pre-merge-commit").is_empty());
        git_in(repo.path(), &["config", "hook.review.enabled", "true"]);
        assert_eq!(configured(repo.path(), "pre-merge-commit"), vec!["review"]);
    }

    /// A list of directories whose names and answer each pass the size of
    /// a pipe is judged to the end.
    #[test]
    fn a_long_list_is_judged_without_a_stall() {
        let repo = tempfile::tempdir().expect("a scratch repository");
        git_in(repo.path(), &["init", "-q"]);
        std::fs::write(repo.path().join(".gitignore"), "skip-*/\n").expect("writes");
        let dirs: Vec<String> = (0..20_000)
            .map(|n| format!("project-directory-{n:05}"))
            .chain(std::iter::once("skip-me".to_owned()))
            .collect();
        std::fs::create_dir(repo.path().join("skip-me")).expect("the dir creates");
        let path = repo.path().to_path_buf();
        let (sender, receiver) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let _ = sender.send(judged(&path, &dirs, &[]));
        });
        let found = receiver
            .recv_timeout(std::time::Duration::from_secs(60))
            .expect("the judgment finishes");
        assert_eq!(found.get("skip-me"), Some(&Rule::Ignore));
        assert_eq!(found.len(), 1);
    }
}