Skip to main content

ljos_cli/
gates.rs

1//! Git call reading for the one push check.
2//!
3//! A push onto a protected branch asks when the ticket has no settled
4//! consensus. That check lives in the sitting gate and reads
5//! [`consensus_push`] and [`protected_push`] here. Commit, merge, evidence
6//! and foreign-owner gates are gone.
7
8use std::path::{Path, PathBuf};
9use std::process::Stdio;
10
11/// Nothing left for a push to warn about. The evidence gate is gone.
12#[must_use]
13pub fn take_push_warning() -> Option<String> {
14    None
15}
16
17#[cfg(test)]
18thread_local! {
19    /// User and seat config for this thread, instead of [`super::config_base`].
20    static LAYER_HOME: std::cell::RefCell<Option<PathBuf>> = const { std::cell::RefCell::new(None) };
21    /// `LJOS_SEAT` for this thread, so a test can name a seat file without
22    /// changing the process environment.
23    static LAYER_SEAT: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
24}
25
26/// No commit, merge, or evidence gate remains. Always `None`.
27#[must_use]
28pub fn command_gate(_line: &str, _cwd: Option<&Path>) -> Option<super::Rule> {
29    None
30}
31
32/// One git call a shell line runs, its aliases expanded: the checkout it
33/// runs in, the subcommand, its arguments, and each `-c KEY=VALUE`.
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub struct GitCall {
36    pub cwd: PathBuf,
37    pub sub: String,
38    pub args: Vec<String>,
39    pub config: Vec<(String, String)>,
40}
41
42/// Every git call `line` runs from `cwd`, the process directory when
43/// absent. `cd DIR`, `git -C DIR`, `sh -c`, `$(...)` and a `!` alias's
44/// shell are followed the way [`command_gate`] follows them.
45///
46/// # Errors
47///
48/// The aliases nest too deep to read, so what the line runs is not known.
49pub fn git_calls(line: &str, cwd: Option<&Path>) -> Result<Vec<GitCall>, String> {
50    let mut out = Vec::new();
51    if !line.to_ascii_lowercase().contains("git") {
52        return Ok(out);
53    }
54    let found = std::env::current_dir().ok();
55    let base = cwd.or(found.as_deref()).unwrap_or_else(|| Path::new("."));
56    let mut queue = invocations(line, base, 0);
57    let mut i = 0;
58    while i < queue.len() {
59        let inv = queue[i].clone();
60        i += 1;
61        if inv.depth > 3 {
62            return Err("its git aliases nest too deep to read".into());
63        }
64        let Some(git) = git_of(&inv) else {
65            continue;
66        };
67        match git.shell {
68            Some(shell) => {
69                let extras = invocations(&shell, &git.cwd, inv.depth.saturating_add(1));
70                queue.splice(i..i, extras);
71            }
72            None => out.push(GitCall {
73                cwd: git.cwd,
74                sub: git.sub,
75                args: git.args,
76                config: git.config,
77            }),
78        }
79    }
80    Ok(out)
81}
82
83/// The static guard and then the pack's rules. `None` lets the line run.
84#[must_use]
85pub fn guard_verdict(line: &str, cwd: Option<&Path>, rules: &[super::Rule]) -> Option<super::Rule> {
86    let fast = super::static_guard_in(line, cwd);
87    let here = cwd.and_then(Path::to_str).map(str::to_string).or_else(|| {
88        std::env::current_dir()
89            .ok()
90            .and_then(|dir| dir.into_os_string().into_string().ok())
91    });
92    let gated = super::redirect_seat_verb(
93        super::gate_push(
94            super::ruled_verdict(rules, line).as_ref(),
95            line,
96            here.as_deref(),
97        ),
98        line,
99    );
100    if gated.as_ref().is_some_and(|rule| rule.verdict == "deny") {
101        return gated;
102    }
103    fast.or(gated)
104}
105
106#[derive(Debug, Clone)]
107struct Inv {
108    cwd: PathBuf,
109    words: Vec<String>,
110    depth: u8,
111}
112
113#[derive(Debug, Clone)]
114struct GitCmd {
115    cwd: PathBuf,
116    config: Vec<(String, String)>,
117    sub: String,
118    args: Vec<String>,
119    shell: Option<String>,
120}
121
122#[derive(Debug, Clone, Default)]
123struct GateConfig {
124    protected: Vec<String>,
125}
126
127fn branch_of(name: &str) -> String {
128    name.trim().trim_start_matches("refs/heads/").to_string()
129}
130
131/// User `ljos.toml`, then the seat's, then the repository's `ljos.toml`,
132/// then `LJOS_CONFIG`, then `.ljos/gates.toml`. A later file overrides the
133/// keys it sets. Identity is whatever the last of these files names. With
134/// none of them naming a person, there is no identity gate.
135fn config_layers(root: &Path) -> Vec<PathBuf> {
136    let mut paths = person_layers();
137    paths.push(root.join("ljos.toml"));
138    if let Some(path) = std::env::var_os("LJOS_CONFIG").filter(|path| !path.is_empty()) {
139        paths.push(PathBuf::from(path));
140    }
141    paths.push(root.join(".ljos").join("gates.toml"));
142    paths
143}
144
145fn user_config_base() -> Option<PathBuf> {
146    #[cfg(test)]
147    if let Some(path) = LAYER_HOME.with(|slot| slot.borrow().clone()) {
148        return Some(path);
149    }
150    super::config_base()
151}
152
153fn configured_seat() -> Option<String> {
154    #[cfg(test)]
155    if let Some(name) = LAYER_SEAT.with(|slot| slot.borrow().clone()) {
156        return clean_seat(&name);
157    }
158    std::env::var("LJOS_SEAT")
159        .ok()
160        .and_then(|name| clean_seat(&name))
161}
162
163fn clean_seat(name: &str) -> Option<String> {
164    let name = name.trim();
165    if name.is_empty() || name.contains('/') || name.contains('\\') || name.contains("..") {
166        return None;
167    }
168    Some(name.to_string())
169}
170
171fn read_layer(path: &Path) -> Result<Option<toml::map::Map<String, toml::Value>>, String> {
172    let text = std::fs::read_to_string(path).map_err(|e| {
173        format!(
174            "`{}` cannot be read ({e}). Fix the file, then retry.",
175            path.display()
176        )
177    })?;
178    if text.trim().is_empty() {
179        return Ok(None);
180    }
181    let value: toml::Value = toml::from_str(&text).map_err(|e| {
182        format!(
183            "`{}` does not parse ({e}). Fix the file, then retry.",
184            path.display()
185        )
186    })?;
187    match value {
188        toml::Value::Table(root) => Ok(Some(root)),
189        _ => Err(format!(
190            "`{}` is not a table. Fix the file, then retry.",
191            path.display()
192        )),
193    }
194}
195
196fn apply_gate_file(cfg: &mut GateConfig, path: &Path) -> Result<(), String> {
197    let Some(root) = read_layer(path)? else {
198        return Ok(());
199    };
200    let gates = root.get("gates").and_then(toml::Value::as_table);
201    let src = gates.unwrap_or(&root);
202    if src.contains_key("protected_branches") {
203        cfg.protected = req_strings(src, "protected_branches", path)?
204            .into_iter()
205            .map(|name| branch_of(&name))
206            .filter(|name| !name.is_empty())
207            .collect();
208    }
209    Ok(())
210}
211
212fn req_strings(
213    table: &toml::map::Map<String, toml::Value>,
214    key: &str,
215    path: &Path,
216) -> Result<Vec<String>, String> {
217    let Some(items) = table.get(key).and_then(toml::Value::as_array) else {
218        return Err(format!(
219            "`{}` key `{key}` must be a list of strings. Fix the file, then retry.",
220            path.display()
221        ));
222    };
223    let mut out = Vec::new();
224    for item in items {
225        let Some(text) = item.as_str() else {
226            return Err(format!(
227                "`{}` key `{key}` must be a list of strings. Fix the file, then retry.",
228                path.display()
229            ));
230        };
231        out.push(text.to_string());
232    }
233    Ok(out)
234}
235
236/// The branches a `--force-with-lease` push asks before it replaces:
237/// `main`, `master` and `develop`, and every branch `protected_branches`
238/// names in the config layers [`config_layers`] reads (the user and seat
239/// `ljos.toml`, the repository's `ljos.toml`, `LJOS_CONFIG` and
240/// `.ljos/gates.toml`). Outside a checkout the user and seat files and
241/// `LJOS_CONFIG` still count. `None` when one of them does not parse, so
242/// the caller asks.
243pub(crate) fn lease_protected(cwd: Option<&Path>) -> Option<Vec<String>> {
244    let mut cfg = GateConfig::default();
245    let layers = match cwd.and_then(repo_root) {
246        Some(root) => config_layers(&root),
247        None => user_layers(),
248    };
249    for path in layers {
250        if path.is_file() {
251            apply_gate_file(&mut cfg, &path).ok()?;
252        }
253    }
254    let mut out: Vec<String> = ["main", "master", "develop"].map(String::from).to_vec();
255    out.extend(cfg.protected);
256    Some(out)
257}
258
259/// The config layers that do not live in a checkout: the user and seat
260/// `ljos.toml`, then `LJOS_CONFIG`.
261fn user_layers() -> Vec<PathBuf> {
262    let mut paths = person_layers();
263    if let Some(path) = std::env::var_os("LJOS_CONFIG").filter(|path| !path.is_empty()) {
264        paths.push(PathBuf::from(path));
265    }
266    paths
267}
268
269/// The user and seat `ljos.toml`: the person's own files, which the seat
270/// guard keeps a runner from writing.
271fn person_layers() -> Vec<PathBuf> {
272    let mut paths = Vec::new();
273    if let Some(base) = user_config_base() {
274        paths.push(base.join("ljos").join("ljos.toml"));
275        if let Some(seat) = configured_seat() {
276            paths.push(base.join("ljos").join("seats").join(seat).join("ljos.toml"));
277        }
278    }
279    paths
280}
281
282/// What a runner's push onto one of `branches` waits for: `quorum` seats
283/// agreeing on the ticket it sits on.
284#[derive(Debug, Clone, PartialEq, Eq)]
285pub struct ConsensusPush {
286    pub quorum: usize,
287    pub branches: Vec<String>,
288}
289
290/// The [`ConsensusPush`] settings: `quorum` (2 seats unless set) and
291/// `consensus_branches` (`develop` and `main` unless set), under `[gates]`
292/// or at the top of a file. The user and seat `ljos.toml` set either. The
293/// repository's `ljos.toml`, `LJOS_CONFIG` and `.ljos/gates.toml` only
294/// raise the quorum and add branches, since a runner can write them.
295///
296/// # Errors
297///
298/// A layer that does not parse, or a key of the wrong kind.
299pub fn consensus_push(cwd: Option<&Path>) -> Result<ConsensusPush, String> {
300    let mut out = ConsensusPush {
301        quorum: 2,
302        branches: vec!["develop".into(), "main".into()],
303    };
304    for path in person_layers() {
305        let (quorum, branches) = consensus_keys(&path)?;
306        out.quorum = quorum.unwrap_or(out.quorum);
307        out.branches = branches.unwrap_or(out.branches);
308    }
309    let root = cwd.and_then(repo_root);
310    let mut rest: Vec<PathBuf> = root.iter().map(|r| r.join("ljos.toml")).collect();
311    if let Some(path) = std::env::var_os("LJOS_CONFIG").filter(|path| !path.is_empty()) {
312        rest.push(PathBuf::from(path));
313    }
314    rest.extend(root.iter().map(|r| r.join(".ljos").join("gates.toml")));
315    for path in rest {
316        let (quorum, branches) = consensus_keys(&path)?;
317        out.quorum = out.quorum.max(quorum.unwrap_or(0));
318        for branch in branches.unwrap_or_default() {
319            if !out.branches.contains(&branch) {
320                out.branches.push(branch);
321            }
322        }
323    }
324    Ok(out)
325}
326
327fn consensus_keys(path: &Path) -> Result<(Option<usize>, Option<Vec<String>>), String> {
328    if !path.is_file() {
329        return Ok((None, None));
330    }
331    let Some(root) = read_layer(path)? else {
332        return Ok((None, None));
333    };
334    let src = root
335        .get("gates")
336        .and_then(toml::Value::as_table)
337        .unwrap_or(&root);
338    let quorum = match src.get("quorum") {
339        None => None,
340        Some(toml::Value::Integer(n)) if *n >= 1 => Some(usize::try_from(*n).unwrap_or(usize::MAX)),
341        Some(_) => {
342            return Err(format!(
343                "`{}` key `quorum` must be a whole number of seats, 1 or more. Fix the file, then retry.",
344                path.display()
345            ))
346        }
347    };
348    let branches = if src.contains_key("consensus_branches") {
349        let names = req_strings(src, "consensus_branches", path)?;
350        Some(
351            names
352                .iter()
353                .map(|name| branch_of(name))
354                .filter(|name| !name.is_empty())
355                .collect(),
356        )
357    } else {
358        None
359    };
360    Ok((quorum, branches))
361}
362
363/// The config layers a command run in `cwd` reads: [`config_layers`] in a
364/// checkout, and the files outside one otherwise.
365pub(crate) fn rewrite_layers(cwd: Option<&Path>) -> Vec<PathBuf> {
366    match cwd.and_then(repo_root) {
367        Some(root) => config_layers(&root),
368        None => user_layers(),
369    }
370}
371
372/// What `path` sets `rewrite` to, under `[gates]` or at the top of the
373/// file, and `None` when it does not set it. A repository sets it to
374/// `false` to have its lines run as they were written.
375///
376/// # Errors
377///
378/// The file cannot be read or does not parse, or `rewrite` is not a
379/// true-or-false value.
380pub(crate) fn rewrite_key(path: &Path) -> Result<Option<bool>, String> {
381    let Some(root) = read_layer(path)? else {
382        return Ok(None);
383    };
384    let src = root
385        .get("gates")
386        .and_then(toml::Value::as_table)
387        .unwrap_or(&root);
388    match src.get("rewrite") {
389        None => Ok(None),
390        Some(toml::Value::Boolean(on)) => Ok(Some(*on)),
391        Some(_) => Err(format!(
392            "`{}` key `rewrite` must be true or false. Fix the file, then retry.",
393            path.display()
394        )),
395    }
396}
397
398/// Where `call`, a `git push` on `line`, lands that needs a consensus: a
399/// branch in `branches`, in backticks, or why the push cannot be told
400/// from one that does. `None` when each ref it updates is read and none
401/// is in `branches`. The push is read the way git reads it: the first
402/// positional is the repository; a bare push lands on the current branch
403/// and its upstream unless `push.default` says otherwise; a branch named
404/// alone lands on its upstream under `push.default=upstream`. A tag, or
405/// any ref outside `refs/heads/`, is not a branch.
406#[must_use]
407pub fn protected_push(call: &GitCall, line: &str, branches: &[String]) -> Option<String> {
408    let unread = |why: String| {
409        Some(format!(
410            "a branch the guard cannot tell from a protected one, since {why}"
411        ))
412    };
413    let cwd = call.cwd.as_path();
414    let args = &call.args;
415    for word in [
416        "GIT_CONFIG",
417        "GIT_DIR",
418        "--git-dir",
419        "GIT_NAMESPACE",
420        "--namespace",
421    ] {
422        if line.contains(word) {
423            return unread(format!("the line sets `{word}`"));
424        }
425    }
426    for (key, _) in &call.config {
427        let key = key.to_ascii_lowercase();
428        if ["remote.", "push.", "branch."]
429            .iter()
430            .any(|p| key.starts_with(p))
431        {
432            return unread(format!("it sets `{key}` for this push"));
433        }
434    }
435    if args.iter().any(|a| has_subst(a)) {
436        return unread("an argument is filled in when the line runs".into());
437    }
438    if let Some(all) = args
439        .iter()
440        .find(|a| matches!(a.as_str(), "--all" | "--mirror" | "--branches" | "--prune"))
441    {
442        return Some(format!("every branch `{all}` reaches"));
443    }
444    if let Some(flag) = args.iter().find(|a| {
445        a.starts_with("--repo")
446            || (a.starts_with("--recurse-submodules")
447                && !a.ends_with("=check")
448                && !a.ends_with("=no"))
449    }) {
450        return unread(format!("`{flag}` moves where it goes"));
451    }
452    if git_text(cwd, &["config", "--get-regexp", r"^remote\..*\.push$"]).is_some() {
453        return unread("a remote in this checkout sets its own push refspecs".into());
454    }
455    let mode = git_config(cwd, "push.default")
456        .unwrap_or_default()
457        .to_ascii_lowercase();
458    let upstream = |branch: &str| git_config(cwd, &format!("branch.{branch}.merge"));
459    let here = || -> Result<Vec<String>, String> {
460        if ["checkout", "switch", "symbolic-ref"]
461            .iter()
462            .any(|w| line.contains(w))
463        {
464            return Err("the line may change branch before it pushes".into());
465        }
466        let head = git_text(cwd, &["symbolic-ref", "-q", "--short", "HEAD"])
467            .filter(|head| !head.is_empty())
468            .ok_or_else(|| "HEAD names no branch".to_string())?;
469        let up = upstream(&head).filter(|_| mode != "current");
470        Ok(std::iter::once(head).chain(up).collect())
471    };
472    let pos = positionals(args);
473    let specs = pos.get(1..).unwrap_or_default();
474    let mut dests = Vec::new();
475    if specs.is_empty() {
476        match mode.as_str() {
477            "nothing" => return None,
478            "matching" => {
479                return Some("every branch both sides have, under `push.default=matching`".into())
480            }
481            _ => match here() {
482                Ok(here) => dests.extend(here),
483                Err(why) => return unread(why),
484            },
485        }
486    }
487    for spec in specs {
488        let spec = spec.strip_prefix('+').unwrap_or(spec);
489        if spec.contains('*') {
490            let dst = spec.rsplit(':').next().unwrap_or(spec);
491            if !dst.starts_with("refs/") || dst.starts_with("refs/heads/") {
492                return Some(format!("the branches `{spec}` matches"));
493            }
494            continue;
495        }
496        match spec.split_once(':') {
497            Some((_, "HEAD" | "@")) => {
498                return unread(format!("`{spec}` lands on what the far side's HEAD names"))
499            }
500            Some((src, "")) => dests.push(src.to_string()),
501            Some((_, dst)) => dests.push(dst.to_string()),
502            None if matches!(spec, "HEAD" | "@") => match here() {
503                Ok(here) => dests.extend(here),
504                Err(why) => return unread(why),
505            },
506            None => {
507                dests.push(spec.to_string());
508                if matches!(mode.as_str(), "upstream" | "tracking") {
509                    dests.extend(upstream(spec));
510                }
511            }
512        }
513    }
514    dests.iter().find_map(|dest| {
515        let name = dest
516            .strip_prefix("refs/heads/")
517            .or_else(|| dest.strip_prefix("heads/"))
518            .unwrap_or(dest);
519        branches
520            .iter()
521            .find(|b| b.eq_ignore_ascii_case(name))
522            .map(|b| format!("`{b}`"))
523    })
524}
525
526fn repo_root(cwd: &Path) -> Option<PathBuf> {
527    git_text(cwd, &["rev-parse", "--show-toplevel"]).map(PathBuf::from)
528}
529
530fn git_config(cwd: &Path, key: &str) -> Option<String> {
531    let value = git_text(cwd, &["config", "--get", key])?;
532    (!value.is_empty()).then_some(value)
533}
534
535fn git_text(cwd: &Path, args: &[&str]) -> Option<String> {
536    let mut cmd = crate::git_cmd();
537    // An exported GIT_DIR would answer for another repository. The
538    // directory this command is judged in is the one named here.
539    crate::clear_git_repo_env(&mut cmd);
540    cmd.arg("-C")
541        .arg(cwd)
542        .args(args)
543        .stdin(Stdio::null())
544        .stdout(Stdio::piped())
545        .stderr(Stdio::null());
546    crate::apply_git_command_env(&mut cmd);
547    let out = cmd.output().ok()?;
548    if !out.status.success() {
549        return None;
550    }
551    Some(
552        String::from_utf8_lossy(&out.stdout)
553            .trim_end_matches(['\r', '\n'])
554            .to_string(),
555    )
556}
557
558fn has_subst(s: &str) -> bool {
559    if s.contains('`') {
560        return true;
561    }
562    let bytes = s.as_bytes();
563    bytes.iter().enumerate().any(|(i, c)| {
564        if *c != b'$' {
565            return false;
566        }
567        matches!(
568            bytes.get(i + 1).copied().unwrap_or(0),
569            b'(' | b'{' | b'_' | b'a'..=b'z' | b'A'..=b'Z'
570        )
571    })
572}
573
574pub(crate) fn is_dry(args: &[String]) -> bool {
575    args.iter().any(|a| {
576        a == "--dry-run"
577            || a == "-n"
578            || (a.starts_with('-') && !a.starts_with("--") && a.chars().skip(1).any(|c| c == 'n'))
579    })
580}
581
582fn positionals(args: &[String]) -> Vec<String> {
583    let mut out = Vec::new();
584    let mut i = 0;
585    while i < args.len() {
586        let a = &args[i];
587        if a == "--" {
588            out.extend(args[i + 1..].iter().cloned());
589            break;
590        }
591        if matches!(
592            a.as_str(),
593            "-o" | "--push-option" | "--receive-pack" | "--exec" | "--repo"
594        ) {
595            i += 2;
596            continue;
597        }
598        if a.starts_with('-') {
599            i += 1;
600            continue;
601        }
602        out.push(a.clone());
603        i += 1;
604    }
605    out
606}
607
608fn invocations(line: &str, base: &Path, depth: u8) -> Vec<Inv> {
609    let mut cwd = base.to_path_buf();
610    let mut out = Vec::new();
611    for sub in super::nested_lines(line, 0) {
612        for seg in super::raw_segments(&sub) {
613            let words = super::shell_words(&seg);
614            if words.is_empty() {
615                continue;
616            }
617            let (at, _) = super::prefix_end(&words);
618            if at >= words.len() {
619                continue;
620            }
621            let cmd = words[at..].to_vec();
622            if cmd.is_empty() {
623                continue;
624            }
625            if super::base_name(&cmd[0]) == "cd" {
626                if let Some(d) = cmd.get(1) {
627                    if d != "-" && !d.starts_with('-') {
628                        cwd = join_dir(&cwd, d);
629                    }
630                }
631                continue;
632            }
633            out.push(Inv {
634                cwd: cwd.clone(),
635                words: cmd,
636                depth,
637            });
638        }
639    }
640    out
641}
642
643fn join_dir(base: &Path, dir: &str) -> PathBuf {
644    let path = Path::new(dir);
645    if path.is_absolute() {
646        path.to_path_buf()
647    } else {
648        base.join(path)
649    }
650}
651
652fn parse_git(inv: &Inv) -> Option<GitCmd> {
653    if super::base_name(&inv.words[0]) != "git" {
654        return None;
655    }
656    let mut i = 1;
657    let mut cwd = inv.cwd.clone();
658    let mut config = Vec::new();
659    while i < inv.words.len() {
660        let w = inv.words[i].as_str();
661        if w == "--" {
662            i += 1;
663            break;
664        }
665        if w == "-C" {
666            if let Some(d) = inv.words.get(i + 1) {
667                cwd = join_dir(&cwd, d);
668            }
669            i += 2;
670            continue;
671        }
672        if w == "-c" {
673            if let Some((k, v)) = inv.words.get(i + 1).and_then(|kv| kv.split_once('=')) {
674                config.push((k.to_string(), v.to_string()));
675            }
676            i += 2;
677            continue;
678        }
679        if let Some((k, v)) = w
680            .strip_prefix("-c")
681            .filter(|s| !s.is_empty() && s.contains('='))
682            .and_then(|kv| kv.split_once('='))
683        {
684            config.push((k.to_string(), v.to_string()));
685            i += 1;
686            continue;
687        }
688        if matches!(
689            w,
690            "--git-dir"
691                | "--work-tree"
692                | "--namespace"
693                | "--config-env"
694                | "--exec-path"
695                | "--super-prefix"
696        ) {
697            i += 2;
698            continue;
699        }
700        if w.starts_with("--git-dir=")
701            || w.starts_with("--work-tree=")
702            || w.starts_with("--namespace=")
703            || w.starts_with("--config-env=")
704            || w.starts_with("--exec-path=")
705            || w.starts_with("--super-prefix=")
706        {
707            i += 1;
708            continue;
709        }
710        if w.starts_with('-') {
711            i += 1;
712            continue;
713        }
714        break;
715    }
716    let sub = inv.words.get(i)?.clone();
717    let args = inv.words.get(i + 1..).unwrap_or(&[]).to_vec();
718    Some(GitCmd {
719        cwd,
720        config,
721        sub,
722        args,
723        shell: None,
724    })
725}
726
727fn git_of(inv: &Inv) -> Option<GitCmd> {
728    let mut git = parse_git(inv)?;
729    let mut seen = std::collections::HashSet::new();
730    while let Some(value) = alias_of(&git) {
731        if !seen.insert(git.sub.clone()) {
732            break;
733        }
734        if let Some(shell) = value.strip_prefix('!') {
735            git.shell = Some(shell.trim().to_string());
736            break;
737        }
738        let mut parts: Vec<String> = value.split_whitespace().map(str::to_string).collect();
739        if parts.is_empty() {
740            break;
741        }
742        git.sub = parts.remove(0);
743        parts.append(&mut git.args);
744        git.args = parts;
745    }
746    Some(git)
747}
748
749fn alias_of(git: &GitCmd) -> Option<String> {
750    if matches!(
751        git.sub.as_str(),
752        "commit"
753            | "push"
754            | "merge"
755            | "checkout"
756            | "switch"
757            | "status"
758            | "diff"
759            | "add"
760            | "log"
761            | "show"
762            | "fetch"
763            | "pull"
764            | "rebase"
765            | "stash"
766            | "branch"
767            | "tag"
768            | "remote"
769            | "init"
770            | "clone"
771            | "restore"
772            | "reset"
773            | "clean"
774            | "rev-parse"
775            | "config"
776            | "help"
777            | "version"
778            | "blame"
779            | "grep"
780            | "mv"
781            | "rm"
782            | "apply"
783            | "cherry-pick"
784            | "revert"
785            | "bisect"
786            | "reflog"
787    ) {
788        return None;
789    }
790    let key = format!("alias.{}", git.sub);
791    if let Some((_, value)) = git.config.iter().rev().find(|(k, _)| k == &key) {
792        return Some(value.clone());
793    }
794    git_config(&git.cwd, &key)
795}
796
797#[cfg(test)]
798mod tests {
799    use super::*;
800
801    const AUTHOR_NAME: &str = "Ada Lovelace";
802    const AUTHOR_EMAIL: &str = "ada@example.com";
803
804    fn git(dir: &Path, args: &[&str]) {
805        let output = crate::git_cmd()
806            .arg("-C")
807            .arg(dir)
808            .args(args)
809            .env("GIT_AUTHOR_NAME", AUTHOR_NAME)
810            .env("GIT_AUTHOR_EMAIL", AUTHOR_EMAIL)
811            .env("GIT_COMMITTER_NAME", AUTHOR_NAME)
812            .env("GIT_COMMITTER_EMAIL", AUTHOR_EMAIL)
813            .output()
814            .unwrap();
815        assert!(
816            output.status.success(),
817            "git {args:?}: {}",
818            String::from_utf8_lossy(&output.stderr)
819        );
820    }
821
822    /// The checkout, and the environment lock. Gate tests read the process
823    /// home: a temp home suspends the guard. Another test sets that home
824    /// for its own case, so this lock is held until the checkout is dropped.
825    struct Held {
826        _env: crate::EnvLock,
827        dir: tempfile::TempDir,
828    }
829
830    impl std::ops::Deref for Held {
831        type Target = tempfile::TempDir;
832
833        fn deref(&self) -> &Self::Target {
834            &self.dir
835        }
836    }
837
838    fn repo() -> Held {
839        let env = crate::test_env_lock();
840        let dir = tempfile::tempdir().unwrap();
841        git(dir.path(), &["init", "-q", "-b", "main"]);
842        git(dir.path(), &["config", "user.name", AUTHOR_NAME]);
843        git(dir.path(), &["config", "user.email", AUTHOR_EMAIL]);
844        git(dir.path(), &["config", "commit.gpgsign", "false"]);
845        git(
846            dir.path(),
847            &[
848                "remote",
849                "add",
850                "origin",
851                "https://example.com/acme/widgets.git",
852            ],
853        );
854        Held { _env: env, dir }
855    }
856
857    fn seed(dir: &Path) {
858        std::fs::write(dir.join("f.txt"), "one\n").unwrap();
859        git(dir, &["add", "f.txt"]);
860        git(dir, &["commit", "-q", "-m", "note the seat"]);
861    }
862
863    fn gates(dir: &Path, body: &str) {
864        std::fs::create_dir_all(dir.join(".ljos")).unwrap();
865        std::fs::write(dir.join(".ljos").join("gates.toml"), body).unwrap();
866    }
867
868    #[test]
869    fn git_calls_follow_dirs_shells_and_aliases() {
870        let dir = repo();
871        let root = dir.path();
872        std::fs::create_dir_all(root.join("sub")).unwrap();
873        git(root, &["config", "alias.ci", "commit -q"]);
874        git(
875            root,
876            &["config", "alias.ship", "!git add . && git push origin HEAD"],
877        );
878        let calls = git_calls(
879            "cd sub && git -C .. ci -m x; sh -c 'git ship'; echo $(git cherry-pick abc)",
880            Some(root),
881        )
882        .unwrap();
883        let subs: Vec<&str> = calls.iter().map(|c| c.sub.as_str()).collect();
884        assert_eq!(subs, ["commit", "add", "push", "cherry-pick"], "{calls:?}");
885        assert_eq!(calls[0].args, ["-q", "-m", "x"]);
886        assert_eq!(calls[0].cwd, root.join("sub").join(".."));
887        assert_eq!(calls[2].args, ["origin", "HEAD"]);
888        assert!(git_calls("ls -la", Some(root)).unwrap().is_empty());
889
890        for (name, next) in [("a", "b"), ("b", "c"), ("c", "d"), ("d", "e")] {
891            git(
892                root,
893                &["config", &format!("alias.{name}"), &format!("!git {next}")],
894            );
895        }
896        let deep = git_calls("git a", Some(root)).unwrap_err();
897        assert!(deep.contains("too deep"), "{deep}");
898    }
899
900    struct Layers;
901
902    impl Drop for Layers {
903        fn drop(&mut self) {
904            LAYER_HOME.with(|slot| *slot.borrow_mut() = None);
905            LAYER_SEAT.with(|slot| *slot.borrow_mut() = None);
906        }
907    }
908
909    fn layers(home: &Path, seat: Option<&str>) -> Layers {
910        LAYER_HOME.with(|slot| *slot.borrow_mut() = Some(home.to_path_buf()));
911        LAYER_SEAT.with(|slot| *slot.borrow_mut() = seat.map(str::to_string));
912        Layers
913    }
914
915    fn write_toml(path: &Path, body: &str) {
916        if let Some(parent) = path.parent() {
917            std::fs::create_dir_all(parent).unwrap();
918        }
919        std::fs::write(path, body).unwrap();
920    }
921
922    #[test]
923    fn the_person_sets_the_consensus_push_and_a_checkout_only_tightens_it() {
924        let dir = repo();
925        let cwd = dir.path();
926        let home = tempfile::tempdir().unwrap();
927        let _layers = layers(home.path(), Some("box"));
928        let read = || consensus_push(Some(cwd)).unwrap();
929        let names = |all: &[&str]| all.iter().map(|b| (*b).to_string()).collect::<Vec<_>>();
930        assert_eq!(read().quorum, 2);
931        assert_eq!(read().branches, names(&["develop", "main"]));
932        write_toml(
933            &home.path().join("ljos/ljos.toml"),
934            "[gates]\nquorum = 3\nconsensus_branches = [\"main\", \"release\"]\n",
935        );
936        assert_eq!(read().quorum, 3);
937        assert_eq!(read().branches, names(&["main", "release"]));
938        write_toml(
939            &home.path().join("ljos/seats/box/ljos.toml"),
940            "quorum = 1\n",
941        );
942        assert_eq!(read().quorum, 1, "the seat file is the person's too");
943        write_toml(
944            &cwd.join("ljos.toml"),
945            "quorum = 1\nconsensus_branches = []\n",
946        );
947        gates(
948            cwd,
949            "quorum = 2\nconsensus_branches = [\"refs/heads/stable\"]\n",
950        );
951        assert_eq!(read().quorum, 2, "a checkout raises the quorum");
952        assert_eq!(read().branches, names(&["main", "release", "stable"]));
953        write_toml(&cwd.join("ljos.toml"), "quorum = 0\n");
954        let zero = consensus_push(Some(cwd)).unwrap_err();
955        assert!(zero.contains("`quorum`"), "{zero}");
956        write_toml(&cwd.join("ljos.toml"), "quorum = [\n");
957        let broken = consensus_push(Some(cwd)).unwrap_err();
958        assert!(broken.contains("does not parse"), "{broken}");
959    }
960
961    #[test]
962    fn a_tight_protected_branch_list_keeps_each_name() {
963        let dir = repo();
964        let home = tempfile::tempdir().unwrap();
965        let _layers = layers(home.path(), None);
966        let cwd = dir.path();
967        let want = ["main", "master", "develop", "feat", "y"]
968            .map(str::to_string)
969            .to_vec();
970        for body in [
971            "protected_branches = [\"feat\",\"y\"]\n",
972            "protected_branches = [\"feat\", \"y\"]\n",
973            "protected_branches = [ \"feat\" , \"y\" ]\n",
974            "protected_branches = ['feat','y']\n",
975            "protected_branches = [\"feat\",\"y\",]\n",
976            "protected_branches = [\"feat\",\"y\"]\r\n",
977        ] {
978            gates(cwd, body);
979            assert_eq!(lease_protected(Some(cwd)).as_ref(), Some(&want), "{body:?}");
980        }
981        gates(cwd, "protected_branches = \"release\"\n");
982        assert!(
983            lease_protected(Some(cwd)).is_none(),
984            "a value that is not a list asks"
985        );
986    }
987
988    #[test]
989    fn a_push_lands_where_git_would_put_it_and_an_unread_one_is_protected() {
990        let dir = repo();
991        let cwd = dir.path();
992        seed(cwd);
993        git(cwd, &["checkout", "-q", "-b", "topic"]);
994        let branches = ["develop".to_string(), "main".to_string()];
995        let lands = |line: &str| {
996            let calls = git_calls(line, Some(cwd)).unwrap();
997            let push = calls.iter().find(|c| c.sub == "push").unwrap();
998            protected_push(push, line, &branches)
999        };
1000        let unread = |line: &str| {
1001            lands(line).is_some_and(|d| d.starts_with("a branch the guard cannot tell"))
1002        };
1003        for line in [
1004            "git push",
1005            "git push origin",
1006            "git push origin topic",
1007            "git push -u origin HEAD",
1008            "git push origin topic:refs/heads/topic",
1009            "git push origin v1:refs/tags/develop",
1010            "git push origin 'refs/tags/*:refs/tags/*'",
1011            "git push develop topic",
1012        ] {
1013            assert_eq!(lands(line), None, "{line}");
1014        }
1015        for (line, dest) in [
1016            ("git push origin HEAD:develop", "`develop`"),
1017            ("git push origin topic:refs/heads/develop", "`develop`"),
1018            ("git push origin +topic:heads/develop", "`develop`"),
1019            ("git push origin :develop", "`develop`"),
1020            ("git push --delete origin develop", "`develop`"),
1021            ("git push origin topic HEAD:Main", "`main`"),
1022            (
1023                "git push https://example.com/acme/widgets.git main",
1024                "`main`",
1025            ),
1026            ("git push --all origin", "every branch `--all` reaches"),
1027            (
1028                "git push origin 'refs/heads/*:refs/heads/*'",
1029                "the branches `refs/heads/*:refs/heads/*` matches",
1030            ),
1031        ] {
1032            assert_eq!(lands(line).as_deref(), Some(dest), "{line}");
1033        }
1034        for line in [
1035            "git checkout develop && git push",
1036            "GIT_DIR=../other git push origin topic",
1037            "git -c remote.origin.push=refs/heads/topic:refs/heads/develop push origin topic",
1038            "git push origin $BRANCH",
1039            "git push --repo=origin topic",
1040            "git push origin topic:HEAD",
1041        ] {
1042            assert!(unread(line), "{line}: {:?}", lands(line));
1043        }
1044
1045        git(cwd, &["config", "branch.topic.merge", "refs/heads/develop"]);
1046        assert_eq!(lands("git push").as_deref(), Some("`develop`"));
1047        assert_eq!(lands("git push origin HEAD").as_deref(), Some("`develop`"));
1048        assert_eq!(
1049            lands("git push origin topic"),
1050            None,
1051            "simple names the branch"
1052        );
1053        git(cwd, &["config", "push.default", "upstream"]);
1054        assert_eq!(lands("git push origin topic").as_deref(), Some("`develop`"));
1055        git(cwd, &["config", "push.default", "current"]);
1056        assert_eq!(lands("git push"), None);
1057        git(cwd, &["config", "push.default", "nothing"]);
1058        assert_eq!(lands("git push"), None);
1059        git(cwd, &["config", "push.default", "matching"]);
1060        assert!(lands("git push")
1061            .unwrap()
1062            .starts_with("every branch both sides have"));
1063        git(cwd, &["config", "--unset", "push.default"]);
1064        git(
1065            cwd,
1066            &[
1067                "config",
1068                "remote.origin.push",
1069                "refs/heads/topic:refs/heads/develop",
1070            ],
1071        );
1072        assert!(unread("git push origin topic"));
1073        git(cwd, &["config", "--unset", "remote.origin.push"]);
1074        git(cwd, &["checkout", "-q", "--detach"]);
1075        assert!(unread("git push origin HEAD"));
1076        assert_eq!(lands("git push origin HEAD:refs/heads/topic"), None);
1077    }
1078}