Skip to main content

jouet_git/
commit.rs

1//! `jouet commit PATH... -m MSG`: commit only the named paths.
2//!
3//! In a checkout shared by several sessions, `git add -A` or `git commit -a`
4//! sweeps up whatever else is there: untracked caches, build output, another
5//! session's half-done work. This commits exactly the paths given, as they
6//! are in the working tree, with `git commit --only`, so anything else
7//! already staged stays staged and out of the commit. Untracked files are
8//! added only when a named path covers them, and are unstaged again if the
9//! commit fails.
10//!
11//! Hooks run as they would for `git commit`; `--no-verify` is never passed.
12//! git's output, hooks included, goes to a log, and a failed commit reports
13//! the end of it.
14//!
15//! A [`Scanner`] may look at the content first: [`run_scanned`] builds a
16//! temporary index holding HEAD plus the named paths, exactly what `git
17//! commit --only` will record, and refuses the commit when the scanner
18//! finds a secret there. The real index is never touched.
19
20use crate::conventional::{self, Policy};
21use crate::{Error, Git, nul_fields};
22use jouet_output::exit::Exit;
23use serde::Serialize;
24use std::io::Write as _;
25use std::path::{Path, PathBuf};
26
27/// Lines of git's output shown when a commit fails.
28const HOOK_TAIL: usize = 40;
29
30#[derive(Debug, Clone, Default)]
31pub struct Request {
32    pub paths: Vec<String>,
33    pub message: String,
34    /// `Key: value` lines to append, already expanded.
35    pub trailers: Vec<String>,
36    pub conventional: Policy,
37    /// The allowed conventional-commit types.
38    pub types: Vec<String>,
39    pub dry_run: bool,
40    /// Where a failed commit's full output is kept.
41    pub log_dir: PathBuf,
42}
43
44#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
45pub struct File {
46    pub path: String,
47    /// `added`, `modified`, `deleted` or `type_changed`.
48    pub status: &'static str,
49    /// Lines added and removed; absent for binary files and, in a dry run,
50    /// for files not yet tracked.
51    #[serde(skip_serializing_if = "Option::is_none")]
52    pub added: Option<u64>,
53    #[serde(skip_serializing_if = "Option::is_none")]
54    pub removed: Option<u64>,
55}
56
57/// The output of a commit that git refused, usually because a hook failed.
58#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
59pub struct Failure {
60    #[serde(skip_serializing_if = "Option::is_none")]
61    pub exit_code: Option<i32>,
62    /// The last lines of git's output, hooks included.
63    pub output: Vec<String>,
64    /// How many lines came before `output`.
65    #[serde(skip_serializing_if = "is_zero")]
66    pub lines_omitted: usize,
67    pub log_path: String,
68}
69
70#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
71pub struct Report {
72    #[serde(skip_serializing_if = "std::ops::Not::not")]
73    pub committed: bool,
74    #[serde(skip_serializing_if = "std::ops::Not::not")]
75    pub dry_run: bool,
76    #[serde(skip_serializing_if = "Option::is_none")]
77    pub sha: Option<String>,
78    #[serde(skip_serializing_if = "Option::is_none")]
79    pub branch: Option<String>,
80    pub subject: String,
81    /// The whole message, trailers included.
82    pub message: String,
83    pub files: Vec<File>,
84    /// Untracked files a named path covered, added by this commit.
85    #[serde(skip_serializing_if = "Vec::is_empty")]
86    pub newly_tracked: Vec<String>,
87    #[serde(skip_serializing_if = "Vec::is_empty")]
88    pub warnings: Vec<String>,
89    #[serde(skip_serializing_if = "Option::is_none")]
90    pub failure: Option<Failure>,
91    /// What the secret scan found, when one ran or was skipped.
92    #[serde(skip_serializing_if = "Option::is_none")]
93    pub secret_scan: Option<SecretScan>,
94    /// What is still uncommitted after a commit: changed, staged or untracked
95    /// paths, as git's status names them. None before a commit, or when git
96    /// could not say. Agents ran `git status` after each commit to learn it.
97    #[serde(skip_serializing_if = "Option::is_none")]
98    pub left: Option<Vec<String>>,
99}
100
101impl Report {
102    /// Whether the secret scan found a secret, so nothing was committed.
103    pub fn secret_found(&self) -> bool {
104        self.secret_scan
105            .as_ref()
106            .is_some_and(|s| s.status == ScanStatus::Found)
107    }
108}
109
110/// A secret scan of the content a commit would record.
111#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
112pub struct SecretScan {
113    /// What scanned: `jouet` (gitleaks' rules), `fnox`, or `jouet+fnox`.
114    pub tool: String,
115    pub status: ScanStatus,
116    /// How many files it read.
117    #[serde(skip_serializing_if = "Option::is_none")]
118    pub files_scanned: Option<u64>,
119    /// Where a secret was found. Never the secret itself.
120    #[serde(skip_serializing_if = "Vec::is_empty")]
121    pub findings: Vec<SecretFinding>,
122    /// Why the scan, or a part of it, was skipped.
123    #[serde(skip_serializing_if = "Option::is_none")]
124    pub reason: Option<String>,
125    /// What the scanner warned about, such as secrets it could not check.
126    #[serde(skip_serializing_if = "Vec::is_empty")]
127    pub notes: Vec<String>,
128}
129
130#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
131#[serde(rename_all = "snake_case")]
132pub enum ScanStatus {
133    Clean,
134    Found,
135    Skipped,
136}
137
138/// One secret, found in one file: a fnox secret's value, named by
139/// `secret`, or what a gitleaks rule matched, named by `rule`.
140#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
141pub struct SecretFinding {
142    /// The fnox secret's name.
143    #[serde(skip_serializing_if = "String::is_empty")]
144    pub secret: String,
145    /// The gitleaks rule.
146    #[serde(skip_serializing_if = "Option::is_none")]
147    pub rule: Option<String>,
148    pub path: String,
149    pub line: u64,
150    /// The rule's match, with the secret cut to its first characters.
151    #[serde(skip_serializing_if = "Option::is_none")]
152    pub redacted: Option<String>,
153}
154
155/// Scans the content a commit would record.
156pub trait Scanner {
157    /// `index` is a git index file holding exactly what the commit will
158    /// record: HEAD plus the named paths. Point `GIT_INDEX_FILE` at it and
159    /// read the staged content.
160    fn scan(&self, top: &Path, index: &Path) -> Result<SecretScan, Error>;
161}
162
163fn is_zero(n: &usize) -> bool {
164    *n == 0
165}
166
167/// Checks the request, then commits (or, for a dry run, reports what would
168/// be committed). A commit git refuses is `Ok` with `failure` set.
169pub fn run(git: &Git, req: &Request) -> Result<Report, Error> {
170    run_scanned(git, req, None)
171}
172
173/// [`run`], with `scanner` reading the content before it is committed. A
174/// secret it finds is `Ok` with `secret_scan` saying so, and nothing is
175/// committed or left staged. A dry run does not scan.
176pub fn run_scanned(
177    git: &Git,
178    req: &Request,
179    scanner: Option<&dyn Scanner>,
180) -> Result<Report, Error> {
181    let top = git.toplevel()?;
182    if req.paths.is_empty() {
183        return Err(no_paths());
184    }
185    let message = req.message.trim_end();
186    if message.trim().is_empty() {
187        return Err(Error::new(Exit::Usage, "the commit message is empty"));
188    }
189    for path in &req.paths {
190        check_path(&top, &git.resolve(path), path)?;
191    }
192    // Untracked files are listed relative to the top, so they are added
193    // from there.
194    let at_top = Git::new(&top);
195    let head = git.head();
196    let mut files = Vec::new();
197    let mut untracked = Vec::new();
198    for path in &req.paths {
199        let (changed, new) = changes(git, head.as_deref(), path)?;
200        if changed.is_empty() && new.is_empty() {
201            return Err(unchanged(git, path));
202        }
203        files.extend(changed);
204        untracked.extend(new);
205    }
206    dedupe(&mut files, |f| f.path.clone());
207    dedupe(&mut untracked, Clone::clone);
208    for path in &untracked {
209        if !files.iter().any(|f| &f.path == path) {
210            files.push(File {
211                path: path.clone(),
212                status: "added",
213                added: None,
214                removed: None,
215            });
216        }
217    }
218    files.sort_by(|a, b| a.path.cmp(&b.path));
219
220    let mut warnings = Vec::new();
221    if req.conventional != Policy::Off
222        && let Some(source) = conventional::detect(&top)
223    {
224        let problems = conventional::lint(message, &req.types);
225        if !problems.is_empty() {
226            let why = format!(
227                "the subject is not a conventional commit, which {source} asks for: {}",
228                problems.join("; ")
229            );
230            if req.conventional == Policy::Refuse {
231                return Err(Error::new(Exit::Precondition, why)
232                    .hint("fix the subject, or set [commit] conventional = \"warn\""));
233            }
234            warnings.push(why);
235        }
236    }
237    let message = with_trailers(git, message, &req.trailers)?;
238    let subject = message.lines().next().unwrap_or_default().to_string();
239    let mut report = Report {
240        dry_run: req.dry_run,
241        branch: git.branch(),
242        subject,
243        message,
244        files,
245        newly_tracked: untracked.clone(),
246        warnings,
247        ..Report::default()
248    };
249    if req.dry_run {
250        return Ok(report);
251    }
252    if let Some(scanner) = scanner {
253        let scan = scan(git, &top, head.as_deref(), &req.paths, scanner)?;
254        report.secret_scan = Some(scan);
255        if report.secret_found() {
256            return Ok(report);
257        }
258    }
259
260    if !untracked.is_empty() {
261        let mut args = vec!["add".to_string(), "--".to_string()];
262        args.extend(untracked.iter().cloned());
263        at_top.text(&args)?;
264    }
265    match commit(git, &req.paths, &report.message, &req.log_dir) {
266        Ok(None) => {}
267        Ok(Some(failure)) => {
268            unstage(&at_top, head.as_deref(), &untracked);
269            report.failure = Some(failure);
270            return Ok(report);
271        }
272        Err(e) => {
273            unstage(&at_top, head.as_deref(), &untracked);
274            return Err(e);
275        }
276    }
277    report.committed = true;
278    report.sha = git.head();
279    report.files = committed_files(git)?;
280    report.left = left(git);
281    // A commit-msg hook may have changed the message.
282    if let Some(message) = git.line(&["log", "-1", "--format=%B", "HEAD"]) {
283        report.subject = message.lines().next().unwrap_or_default().to_string();
284        report.message = message;
285    }
286    Ok(report)
287}
288
289/// The paths `git status` still reports, changed, staged or untracked.
290fn left(git: &Git) -> Option<Vec<String>> {
291    let out = git
292        .text(&["status", "--porcelain=v1", "-z", "--untracked-files=normal"])
293        .ok()?;
294    let mut paths = Vec::new();
295    let mut fields = crate::nul_fields(&out);
296    while let Some(entry) = fields.next() {
297        let Some(path) = entry.get(3..) else { continue };
298        // A rename is followed by the name it had.
299        if entry.starts_with('R') || entry.starts_with('C') {
300            fields.next();
301        }
302        paths.push(path.to_string());
303    }
304    Some(paths)
305}
306
307fn no_paths() -> Error {
308    Error::new(Exit::Usage, "name the paths to commit")
309        .hint("jouet commit stages only the paths it is given, never everything: jouet commit src/a.rs src/b.rs -m MSG")
310}
311
312/// Refuses a path that names the whole tree, or lies outside it. `full` is
313/// `path` made absolute.
314fn check_path(top: &Path, full: &Path, path: &str) -> Result<(), Error> {
315    if path.is_empty() {
316        return Err(Error::new(Exit::Usage, "an empty path names nothing"));
317    }
318    let full = normalize(full);
319    // Canonicalize what exists, so symlinked checkouts (macOS's /tmp) still
320    // compare equal to git's top.
321    let top = top.canonicalize().unwrap_or_else(|_| top.to_path_buf());
322    let full = existing_prefix_canonical(&full);
323    if full == top {
324        return Err(
325            Error::new(Exit::Usage, format!("`{path}` is the whole repository")).hint(
326                "name the files or directories to commit; jouet commit never sweeps up everything",
327            ),
328        );
329    }
330    if !full.starts_with(&top) {
331        return Err(Error::new(
332            Exit::Usage,
333            format!("`{path}` is outside the repository at {}", top.display()),
334        ));
335    }
336    Ok(())
337}
338
339/// Removes `.` and folds `..` without touching the filesystem.
340fn normalize(path: &Path) -> PathBuf {
341    let mut out = PathBuf::new();
342    for part in path.components() {
343        match part {
344            std::path::Component::CurDir => {}
345            std::path::Component::ParentDir => {
346                out.pop();
347            }
348            other => out.push(other),
349        }
350    }
351    out
352}
353
354/// Canonicalizes the longest existing prefix of `path` and appends the rest,
355/// so a deleted file still resolves through a symlinked parent.
356fn existing_prefix_canonical(path: &Path) -> PathBuf {
357    let mut rest = Vec::new();
358    let mut cur = path.to_path_buf();
359    loop {
360        if let Ok(real) = cur.canonicalize() {
361            let mut out = real;
362            for part in rest.iter().rev() {
363                out.push(part);
364            }
365            return out;
366        }
367        match (cur.file_name().map(ToOwned::to_owned), cur.parent()) {
368            (Some(name), Some(parent)) => {
369                rest.push(name);
370                cur = parent.to_path_buf();
371            }
372            _ => return path.to_path_buf(),
373        }
374    }
375}
376
377/// The tracked files under `path` that differ from HEAD (the working tree
378/// against HEAD, staged or not), and the untracked, not ignored files under
379/// it.
380fn changes(git: &Git, head: Option<&str>, path: &str) -> Result<(Vec<File>, Vec<String>), Error> {
381    let mut files = Vec::new();
382    match head {
383        Some(head) => {
384            let status = git.text(&[
385                "diff",
386                "--no-renames",
387                "--name-status",
388                "-z",
389                head,
390                "--",
391                path,
392            ])?;
393            let numstat =
394                git.text(&["diff", "--no-renames", "--numstat", "-z", head, "--", path])?;
395            let counts = parse_numstat(&numstat);
396            let mut fields = nul_fields(&status);
397            while let (Some(code), Some(name)) = (fields.next(), fields.next()) {
398                let (added, removed) = counts.get(name).copied().unwrap_or((None, None));
399                files.push(File {
400                    path: name.to_string(),
401                    status: status_name(code),
402                    added,
403                    removed,
404                });
405            }
406        }
407        None => {
408            // An unborn branch: every tracked file is new.
409            let cached = git.text(&["ls-files", "-z", "--cached", "--full-name", "--", path])?;
410            for name in nul_fields(&cached) {
411                files.push(File {
412                    path: name.to_string(),
413                    status: "added",
414                    added: None,
415                    removed: None,
416                });
417            }
418        }
419    }
420    let others = git.text(&[
421        "ls-files",
422        "-z",
423        "--others",
424        "--exclude-standard",
425        "--full-name",
426        "--",
427        path,
428    ])?;
429    let untracked = nul_fields(&others).map(str::to_string).collect();
430    Ok((files, untracked))
431}
432
433fn parse_numstat(text: &str) -> std::collections::HashMap<&str, (Option<u64>, Option<u64>)> {
434    let mut out = std::collections::HashMap::new();
435    for field in nul_fields(text) {
436        let mut parts = field.splitn(3, '\t');
437        if let (Some(a), Some(r), Some(name)) = (parts.next(), parts.next(), parts.next()) {
438            out.insert(name, (a.parse().ok(), r.parse().ok()));
439        }
440    }
441    out
442}
443
444fn status_name(code: &str) -> &'static str {
445    match code.chars().next() {
446        Some('A') => "added",
447        Some('D') => "deleted",
448        Some('T') => "type_changed",
449        _ => "modified",
450    }
451}
452
453/// Why a named path has nothing to commit.
454fn unchanged(git: &Git, path: &str) -> Error {
455    if git.ignores(path) {
456        return Error::new(
457            Exit::Precondition,
458            format!("`{path}` is ignored by git, so it cannot be committed"),
459        );
460    }
461    let tracked = git.line(&["ls-files", "--", path]).is_some();
462    if !tracked && std::fs::symlink_metadata(git.resolve(path)).is_err() {
463        return Error::new(
464            Exit::NotFound,
465            format!("`{path}`: no such file or directory"),
466        );
467    }
468    Error::new(
469        Exit::Precondition,
470        format!("`{path}` has no changes to commit"),
471    )
472    .hint("name only the paths you changed")
473}
474
475fn dedupe<T, K: PartialEq>(items: &mut Vec<T>, key: impl Fn(&T) -> K) {
476    let mut seen: Vec<K> = Vec::new();
477    items.retain(|item| {
478        let k = key(item);
479        if seen.contains(&k) {
480            false
481        } else {
482            seen.push(k);
483            true
484        }
485    });
486}
487
488/// The message with `trailers` appended by `git interpret-trailers`, which
489/// joins an existing trailer block and skips a trailer already present. One
490/// the message already gives in its own words is skipped too: a co-author
491/// with the same address, or a second AI disclosure.
492fn with_trailers(git: &Git, message: &str, trailers: &[String]) -> Result<String, Error> {
493    // Check every configured trailer, including one the message makes
494    // redundant, so a bad setting fails whatever the message says.
495    for t in trailers {
496        match t.split_once(':') {
497            Some((key, value))
498                if !key.trim().is_empty()
499                    && !key.contains(char::is_whitespace)
500                    && !value.trim().is_empty() => {}
501            _ => {
502                return Err(Error::new(
503                    Exit::Usage,
504                    format!("a trailer is `Key: value`, not `{t}`"),
505                ));
506            }
507        }
508    }
509    let given = given_trailers(message);
510    let trailers: Vec<&String> = trailers
511        .iter()
512        .filter(|t| !given.iter().any(|g| same_trailer(g, t)))
513        .collect();
514    if trailers.is_empty() {
515        return Ok(format!("{message}\n"));
516    }
517    let mut args = vec![
518        "-c".to_string(),
519        "trailer.ifexists=addIfDifferent".to_string(),
520        "-c".to_string(),
521        "trailer.where=end".to_string(),
522        "interpret-trailers".to_string(),
523    ];
524    for t in trailers {
525        args.push("--trailer".into());
526        args.push(t.to_string());
527    }
528    let mut child = git
529        .command(&args)
530        .stdin(std::process::Stdio::piped())
531        .stdout(std::process::Stdio::piped())
532        .stderr(std::process::Stdio::piped())
533        .spawn()
534        .map_err(|e| Error::new(Exit::Failed, format!("running git: {e}")))?;
535    if let Some(mut stdin) = child.stdin.take() {
536        stdin
537            .write_all(format!("{message}\n").as_bytes())
538            .map_err(|e| Error::new(Exit::Failed, format!("writing to git: {e}")))?;
539    }
540    let out = child
541        .wait_with_output()
542        .map_err(|e| Error::new(Exit::Failed, format!("running git: {e}")))?;
543    if !out.status.success() {
544        return Err(Error::new(
545            Exit::Failed,
546            format!(
547                "git interpret-trailers failed: {}",
548                String::from_utf8_lossy(&out.stderr).trim()
549            ),
550        ));
551    }
552    Ok(String::from_utf8_lossy(&out.stdout).into_owned())
553}
554
555/// The `Key: value` lines of the message's last paragraph, when it has
556/// one after the subject. Blank lines split paragraphs whatever the line
557/// ending.
558fn given_trailers(message: &str) -> Vec<&str> {
559    let lines: Vec<&str> = message.trim_end().lines().collect();
560    let Some(blank) = lines.iter().rposition(|l| l.trim().is_empty()) else {
561        return Vec::new();
562    };
563    let lines = &lines[blank + 1..];
564    let trailer = |l: &&str| {
565        l.split_once(':')
566            .is_some_and(|(k, _)| !k.is_empty() && !k.contains(char::is_whitespace))
567    };
568    if lines.iter().all(trailer) {
569        lines.to_vec()
570    } else {
571        Vec::new()
572    }
573}
574
575/// Whether `given` already says what `trailer` would: the same key and
576/// address (`Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>` gives
577/// `Co-Authored-By: Claude <noreply@anthropic.com>`), or an `AI-Assisted`
578/// disclosure, which a commit carries once.
579fn same_trailer(given: &str, trailer: &str) -> bool {
580    let split = |t: &str| {
581        t.split_once(':')
582            .map(|(k, v)| (k.trim().to_ascii_lowercase(), v.trim().to_string()))
583    };
584    let (Some((key, value)), Some((wanted_key, wanted))) = (split(given), split(trailer)) else {
585        return false;
586    };
587    let address = |v: &str| {
588        let (_, rest) = v.rsplit_once('<')?;
589        Some(rest.strip_suffix('>')?.to_ascii_lowercase())
590    };
591    key == wanted_key
592        && (key == "ai-assisted" || address(&value).is_some_and(|a| address(&wanted) == Some(a)))
593}
594
595/// Runs `scanner` over a temporary index of HEAD plus `paths` as they are in
596/// the working tree, which is what `git commit --only` records.
597fn scan(
598    git: &Git,
599    top: &Path,
600    head: Option<&str>,
601    paths: &[String],
602    scanner: &dyn Scanner,
603) -> Result<SecretScan, Error> {
604    let io =
605        |e: std::io::Error| Error::new(Exit::Failed, format!("preparing the secret scan: {e}"));
606    let dir = tempfile::tempdir().map_err(io)?;
607    let index = dir.path().join("index");
608    let run = |args: &[String]| -> Result<(), Error> {
609        let out = git
610            .command(args)
611            .env("GIT_INDEX_FILE", &index)
612            .output()
613            .map_err(|e| Error::new(Exit::Failed, format!("running git: {e}")))?;
614        if out.status.success() {
615            return Ok(());
616        }
617        Err(Error::new(
618            Exit::Failed,
619            format!(
620                "git {} failed: {}",
621                args.join(" "),
622                String::from_utf8_lossy(&out.stderr).trim()
623            ),
624        ))
625    };
626    match head {
627        Some(head) => run(&["read-tree".into(), head.into()])?,
628        None => run(&["read-tree".into(), "--empty".into()])?,
629    }
630    let mut add = vec!["add".to_string(), "--".to_string()];
631    add.extend(paths.iter().cloned());
632    run(&add)?;
633    scanner.scan(top, &index)
634}
635
636/// `git commit --only -F MESSAGE -- PATHS`, its output to a log. `None`
637/// when it succeeded.
638fn commit(
639    git: &Git,
640    paths: &[String],
641    message: &str,
642    log_dir: &Path,
643) -> Result<Option<Failure>, Error> {
644    let io = |e: std::io::Error| Error::new(Exit::Failed, format!("writing the commit log: {e}"));
645    let mut file = tempfile::NamedTempFile::new().map_err(io)?;
646    file.write_all(message.as_bytes()).map_err(io)?;
647    let (log_path, log) = crate::new_log(log_dir, "commit").map_err(io)?;
648    let mut args: Vec<std::ffi::OsString> = vec![
649        "commit".into(),
650        "--only".into(),
651        "--cleanup=whitespace".into(),
652        "-F".into(),
653        file.path().as_os_str().to_owned(),
654        "--".into(),
655    ];
656    args.extend(paths.iter().map(|p| crate::literal(p).into()));
657    // Not `--literal-pathspecs`, which would reach the hooks.
658    let status = git
659        .hooked_command(&args)
660        .stdout(log.try_clone().map_err(io)?)
661        .stderr(log)
662        .status()
663        .map_err(|e| Error::new(Exit::Failed, format!("running git commit: {e}")))?;
664    if status.success() {
665        let _ = std::fs::remove_file(&log_path);
666        // A hook that fixed and staged a path (hk's fixers) changed the
667        // commit, but git wrote the path into the real index as it was
668        // before the hook. The commit is what the index should hold.
669        let mut reset = vec!["reset".to_string(), "-q".into(), "--".into()];
670        reset.extend(paths.iter().cloned());
671        let _ = git.text(&reset);
672        return Ok(None);
673    }
674    let text = String::from_utf8_lossy(&std::fs::read(&log_path).unwrap_or_default()).into_owned();
675    let (output, lines_omitted) = crate::tail(&text, HOOK_TAIL);
676    Ok(Some(Failure {
677        exit_code: status.code(),
678        output,
679        lines_omitted,
680        log_path: log_path.display().to_string(),
681    }))
682}
683
684/// Unstages the untracked files this commit added, after it failed.
685fn unstage(git: &Git, head: Option<&str>, paths: &[String]) {
686    if paths.is_empty() {
687        return;
688    }
689    let mut args: Vec<String> = match head {
690        Some(_) => vec!["reset".into(), "-q".into()],
691        None => vec!["rm".into(), "-q".into(), "--cached".into()],
692    };
693    args.push("--".into());
694    args.extend(paths.iter().cloned());
695    let _ = git.text(&args);
696}
697
698/// The files in HEAD's commit, with line counts.
699fn committed_files(git: &Git) -> Result<Vec<File>, Error> {
700    let base = [
701        "diff-tree",
702        "-r",
703        "--root",
704        "--no-commit-id",
705        "--no-renames",
706        "-z",
707    ];
708    let status = git.text(&[&base[..], &["--name-status", "HEAD"]].concat())?;
709    let numstat = git.text(&[&base[..], &["--numstat", "HEAD"]].concat())?;
710    let counts = parse_numstat(&numstat);
711    let mut files = Vec::new();
712    let mut fields = nul_fields(&status);
713    while let (Some(code), Some(name)) = (fields.next(), fields.next()) {
714        let (added, removed) = counts.get(name).copied().unwrap_or((None, None));
715        files.push(File {
716            path: name.to_string(),
717            status: status_name(code),
718            added,
719            removed,
720        });
721    }
722    Ok(files)
723}
724
725#[cfg(test)]
726#[path = "commit_tests.rs"]
727mod tests;