Skip to main content

mortise_core/modules/
git.rs

1//! What git knows about an app: the branch, and how often each module changed.
2//!
3//! Mortise runs the `git` program and only reads. Without git, or outside a
4//! repository, this data is absent and nothing else is affected.
5
6use std::collections::BTreeMap;
7use std::path::{Path, PathBuf};
8use std::process::Stdio;
9
10use serde::{Deserialize, Serialize};
11
12/// The window for "commits in 30 days".
13pub const CHURN_DAYS: u32 = 30;
14
15/// The git state of an app folder.
16#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
17pub enum Git {
18    /// The folder is in a repository.
19    Repository {
20        /// The branch that is checked out. `None` when HEAD is detached.
21        branch: Option<String>,
22        /// The short id of the commit that is checked out. `None` before the first commit.
23        commit: Option<String>,
24    },
25    /// The folder is not in a git repository.
26    NotARepository,
27    /// The `git` program could not be started.
28    NoGit,
29}
30
31/// How often a folder changed.
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
33pub struct Churn {
34    /// Commits that touched the folder in the last [`CHURN_DAYS`] days.
35    pub commits: u32,
36    /// When the folder was last touched by a commit, in seconds since 1970.
37    /// `None` when no commit ever touched it.
38    pub last_commit: Option<i64>,
39}
40
41/// Runs git in `root` and gives its output, or `None` when it fails.
42pub(crate) fn git(root: &Path, args: &[&str]) -> Option<String> {
43    let output = crate::program::command("git")
44        .arg("-C")
45        .arg(root)
46        // Paths as they are, not quoted and escaped.
47        .args(["--no-pager", "-c", "core.quotepath=false"])
48        // Never start a file system monitor that the repository configures.
49        .args(["-c", "core.fsmonitor=false"])
50        .args(args)
51        // Never take a lock or write the index: Mortise only reads.
52        .env("GIT_OPTIONAL_LOCKS", "0")
53        .env("GIT_TERMINAL_PROMPT", "0")
54        .stderr(Stdio::null())
55        .output()
56        .ok()?;
57    output
58        .status
59        .success()
60        .then(|| String::from_utf8_lossy(&output.stdout).into_owned())
61}
62
63/// Reads the branch and commit of the app in `root`.
64pub(crate) fn read(root: &Path) -> Git {
65    let started = crate::program::command("git")
66        .arg("--version")
67        .stdout(Stdio::null())
68        .stderr(Stdio::null())
69        .status()
70        .is_ok();
71    if !started {
72        return Git::NoGit;
73    }
74    if git(root, &["rev-parse", "--is-inside-work-tree"])
75        .as_deref()
76        .map(str::trim)
77        != Some("true")
78    {
79        return Git::NotARepository;
80    }
81    let text = |args: &[&str]| {
82        git(root, args)
83            .map(|out| out.trim().to_owned())
84            .filter(|out| !out.is_empty())
85    };
86    Git::Repository {
87        // Works before the first commit too, and fails for a detached HEAD.
88        branch: text(&["symbolic-ref", "--short", "-q", "HEAD"]),
89        commit: text(&["rev-parse", "--short", "-q", "--verify", "HEAD"]),
90    }
91}
92
93/// Counts the commits of the last [`CHURN_DAYS`] days for each folder, and finds
94/// when each was last touched. `folders` are paths relative to `root`, with `/`.
95pub(crate) fn churn(root: &Path, folders: &[String]) -> BTreeMap<String, Churn> {
96    let mut churn: BTreeMap<String, Churn> = BTreeMap::new();
97    if folders.is_empty() {
98        return churn;
99    }
100
101    // One call for the window: each commit as a marker line with its time, then
102    // the files it touched, relative to the app folder.
103    let since = format!("--since={CHURN_DAYS}.days");
104    let mut args = vec![
105        "log",
106        &since,
107        "--format=%x01%ct",
108        "--name-only",
109        "--relative",
110        "--",
111    ];
112    args.extend(folders.iter().map(String::as_str));
113    let log = git(root, &args).unwrap_or_default();
114    for commit in log.split('\u{1}').skip(1) {
115        let mut lines = commit.lines();
116        let Some(time) = lines
117            .next()
118            .and_then(|time| time.trim().parse::<i64>().ok())
119        else {
120            continue;
121        };
122        let mut touched: Vec<&String> = lines
123            .filter(|file| !file.is_empty())
124            .filter_map(|file| {
125                folders.iter().find(|folder| {
126                    file.strip_prefix(folder.as_str())
127                        .is_some_and(|rest| rest.starts_with('/'))
128                })
129            })
130            .collect();
131        touched.sort();
132        touched.dedup();
133        for folder in touched {
134            let entry = churn.entry(folder.clone()).or_default();
135            entry.commits += 1;
136            // The log is newest first, but a merge can bring an older time.
137            entry.last_commit = entry.last_commit.max(Some(time));
138        }
139    }
140
141    // A folder that was quiet in the window: when was it touched at all?
142    for folder in folders {
143        if churn.contains_key(folder) {
144            continue;
145        }
146        let last = git(root, &["log", "-1", "--format=%ct", "--", folder])
147            .and_then(|time| time.trim().parse().ok());
148        churn.insert(
149            folder.clone(),
150            Churn {
151                commits: 0,
152                last_commit: last,
153            },
154        );
155    }
156    churn
157}
158
159/// For each folder in `dirs`, the files git cannot restore: changed, staged,
160/// added, deleted and untracked. Ignored files are left out. `None` for a folder
161/// git cannot tell about: outside the repository of `root`, a repository of its
162/// own such as a submodule, or every folder when git fails.
163pub(crate) fn uncommitted(root: &Path, dirs: &[PathBuf]) -> Vec<Option<u32>> {
164    let unknown = vec![None; dirs.len()];
165    let Some(top) = git(root, &["rev-parse", "--show-toplevel"])
166        .and_then(|top| std::fs::canonicalize(top.trim_end_matches(['\n', '\r'])).ok())
167    else {
168        return unknown;
169    };
170    // Each folder relative to the top of the repository, with `/`, as git prints
171    // the paths of a status. A folder in a repository of its own, such as a
172    // submodule, has a `.git` in it or above it below the top: this status does not
173    // list its files.
174    let relative: Vec<Option<String>> = dirs
175        .iter()
176        .map(|dir| {
177            let dir = std::fs::canonicalize(dir).ok()?;
178            let nested = dir
179                .ancestors()
180                .take_while(|folder| *folder != top)
181                .any(|folder| folder.join(".git").exists());
182            if nested {
183                return None;
184            }
185            let parts: Vec<String> = dir
186                .strip_prefix(&top)
187                .ok()?
188                .components()
189                .map(|part| part.as_os_str().to_string_lossy().into_owned())
190                .collect();
191            (!parts.is_empty()).then(|| parts.join("/"))
192        })
193        .collect();
194    let mut counts: Vec<Option<u32>> = relative
195        .iter()
196        .map(|folder| folder.as_ref().map(|_| 0))
197        .collect();
198    let mut args = vec![
199        "status",
200        "--porcelain=v1",
201        "-z",
202        "--untracked-files=all",
203        "--no-renames",
204        "--",
205    ];
206    args.extend(relative.iter().flatten().map(String::as_str));
207    if args.len() == 6 {
208        return counts;
209    }
210    let Some(status) = git(&top, &args) else {
211        return unknown;
212    };
213    for entry in status.split('\0') {
214        // `XY path`: two status letters, a space, the path from the top.
215        let Some(path) = entry.get(3..) else {
216            continue;
217        };
218        for (folder, count) in relative.iter().zip(counts.iter_mut()) {
219            let Some(rest) = folder
220                .as_deref()
221                .and_then(|folder| path.strip_prefix(folder))
222            else {
223                continue;
224            };
225            match rest {
226                // The folder itself is listed: it is a repository of its own, whose
227                // files this status does not list.
228                "" | "/" => *count = None,
229                _ if rest.starts_with('/') => {
230                    if let Some(count) = count {
231                        *count += 1;
232                    }
233                }
234                _ => {}
235            }
236        }
237    }
238    counts
239}