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::{Command, 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 = Command::new("git");
537    cmd.arg("-C")
538        .arg(cwd)
539        .args(args)
540        .stdin(Stdio::null())
541        .stdout(Stdio::piped())
542        .stderr(Stdio::null());
543    crate::apply_git_command_env(&mut cmd);
544    let out = cmd.output().ok()?;
545    if !out.status.success() {
546        return None;
547    }
548    Some(
549        String::from_utf8_lossy(&out.stdout)
550            .trim_end_matches(['\r', '\n'])
551            .to_string(),
552    )
553}
554
555fn has_subst(s: &str) -> bool {
556    if s.contains('`') {
557        return true;
558    }
559    let bytes = s.as_bytes();
560    bytes.iter().enumerate().any(|(i, c)| {
561        if *c != b'$' {
562            return false;
563        }
564        matches!(
565            bytes.get(i + 1).copied().unwrap_or(0),
566            b'(' | b'{' | b'_' | b'a'..=b'z' | b'A'..=b'Z'
567        )
568    })
569}
570
571pub(crate) fn is_dry(args: &[String]) -> bool {
572    args.iter().any(|a| {
573        a == "--dry-run"
574            || a == "-n"
575            || (a.starts_with('-') && !a.starts_with("--") && a.chars().skip(1).any(|c| c == 'n'))
576    })
577}
578
579fn positionals(args: &[String]) -> Vec<String> {
580    let mut out = Vec::new();
581    let mut i = 0;
582    while i < args.len() {
583        let a = &args[i];
584        if a == "--" {
585            out.extend(args[i + 1..].iter().cloned());
586            break;
587        }
588        if matches!(
589            a.as_str(),
590            "-o" | "--push-option" | "--receive-pack" | "--exec" | "--repo"
591        ) {
592            i += 2;
593            continue;
594        }
595        if a.starts_with('-') {
596            i += 1;
597            continue;
598        }
599        out.push(a.clone());
600        i += 1;
601    }
602    out
603}
604
605fn invocations(line: &str, base: &Path, depth: u8) -> Vec<Inv> {
606    let mut cwd = base.to_path_buf();
607    let mut out = Vec::new();
608    for sub in super::nested_lines(line, 0) {
609        for seg in super::raw_segments(&sub) {
610            let words = super::shell_words(&seg);
611            if words.is_empty() {
612                continue;
613            }
614            let (at, _) = super::prefix_end(&words);
615            if at >= words.len() {
616                continue;
617            }
618            let cmd = words[at..].to_vec();
619            if cmd.is_empty() {
620                continue;
621            }
622            if super::base_name(&cmd[0]) == "cd" {
623                if let Some(d) = cmd.get(1) {
624                    if d != "-" && !d.starts_with('-') {
625                        cwd = join_dir(&cwd, d);
626                    }
627                }
628                continue;
629            }
630            out.push(Inv {
631                cwd: cwd.clone(),
632                words: cmd,
633                depth,
634            });
635        }
636    }
637    out
638}
639
640fn join_dir(base: &Path, dir: &str) -> PathBuf {
641    let path = Path::new(dir);
642    if path.is_absolute() {
643        path.to_path_buf()
644    } else {
645        base.join(path)
646    }
647}
648
649fn parse_git(inv: &Inv) -> Option<GitCmd> {
650    if super::base_name(&inv.words[0]) != "git" {
651        return None;
652    }
653    let mut i = 1;
654    let mut cwd = inv.cwd.clone();
655    let mut config = Vec::new();
656    while i < inv.words.len() {
657        let w = inv.words[i].as_str();
658        if w == "--" {
659            i += 1;
660            break;
661        }
662        if w == "-C" {
663            if let Some(d) = inv.words.get(i + 1) {
664                cwd = join_dir(&cwd, d);
665            }
666            i += 2;
667            continue;
668        }
669        if w == "-c" {
670            if let Some((k, v)) = inv.words.get(i + 1).and_then(|kv| kv.split_once('=')) {
671                config.push((k.to_string(), v.to_string()));
672            }
673            i += 2;
674            continue;
675        }
676        if let Some((k, v)) = w
677            .strip_prefix("-c")
678            .filter(|s| !s.is_empty() && s.contains('='))
679            .and_then(|kv| kv.split_once('='))
680        {
681            config.push((k.to_string(), v.to_string()));
682            i += 1;
683            continue;
684        }
685        if matches!(
686            w,
687            "--git-dir"
688                | "--work-tree"
689                | "--namespace"
690                | "--config-env"
691                | "--exec-path"
692                | "--super-prefix"
693        ) {
694            i += 2;
695            continue;
696        }
697        if w.starts_with("--git-dir=")
698            || w.starts_with("--work-tree=")
699            || w.starts_with("--namespace=")
700            || w.starts_with("--config-env=")
701            || w.starts_with("--exec-path=")
702            || w.starts_with("--super-prefix=")
703        {
704            i += 1;
705            continue;
706        }
707        if w.starts_with('-') {
708            i += 1;
709            continue;
710        }
711        break;
712    }
713    let sub = inv.words.get(i)?.clone();
714    let args = inv.words.get(i + 1..).unwrap_or(&[]).to_vec();
715    Some(GitCmd {
716        cwd,
717        config,
718        sub,
719        args,
720        shell: None,
721    })
722}
723
724fn git_of(inv: &Inv) -> Option<GitCmd> {
725    let mut git = parse_git(inv)?;
726    let mut seen = std::collections::HashSet::new();
727    while let Some(value) = alias_of(&git) {
728        if !seen.insert(git.sub.clone()) {
729            break;
730        }
731        if let Some(shell) = value.strip_prefix('!') {
732            git.shell = Some(shell.trim().to_string());
733            break;
734        }
735        let mut parts: Vec<String> = value.split_whitespace().map(str::to_string).collect();
736        if parts.is_empty() {
737            break;
738        }
739        git.sub = parts.remove(0);
740        parts.append(&mut git.args);
741        git.args = parts;
742    }
743    Some(git)
744}
745
746fn alias_of(git: &GitCmd) -> Option<String> {
747    if matches!(
748        git.sub.as_str(),
749        "commit"
750            | "push"
751            | "merge"
752            | "checkout"
753            | "switch"
754            | "status"
755            | "diff"
756            | "add"
757            | "log"
758            | "show"
759            | "fetch"
760            | "pull"
761            | "rebase"
762            | "stash"
763            | "branch"
764            | "tag"
765            | "remote"
766            | "init"
767            | "clone"
768            | "restore"
769            | "reset"
770            | "clean"
771            | "rev-parse"
772            | "config"
773            | "help"
774            | "version"
775            | "blame"
776            | "grep"
777            | "mv"
778            | "rm"
779            | "apply"
780            | "cherry-pick"
781            | "revert"
782            | "bisect"
783            | "reflog"
784    ) {
785        return None;
786    }
787    let key = format!("alias.{}", git.sub);
788    if let Some((_, value)) = git.config.iter().rev().find(|(k, _)| k == &key) {
789        return Some(value.clone());
790    }
791    git_config(&git.cwd, &key)
792}
793
794#[cfg(test)]
795mod tests {
796    use super::*;
797
798    const AUTHOR_NAME: &str = "Ada Lovelace";
799    const AUTHOR_EMAIL: &str = "ada@example.com";
800
801    fn git(dir: &Path, args: &[&str]) {
802        let output = Command::new("git")
803            .arg("-C")
804            .arg(dir)
805            .args(args)
806            .env("GIT_AUTHOR_NAME", AUTHOR_NAME)
807            .env("GIT_AUTHOR_EMAIL", AUTHOR_EMAIL)
808            .env("GIT_COMMITTER_NAME", AUTHOR_NAME)
809            .env("GIT_COMMITTER_EMAIL", AUTHOR_EMAIL)
810            .output()
811            .unwrap();
812        assert!(
813            output.status.success(),
814            "git {args:?}: {}",
815            String::from_utf8_lossy(&output.stderr)
816        );
817    }
818
819    /// The checkout, and the environment lock. Gate tests read the process
820    /// home: a temp home suspends the guard. Another test sets that home
821    /// for its own case, so this lock is held until the checkout is dropped.
822    struct Held {
823        _env: crate::EnvLock,
824        dir: tempfile::TempDir,
825    }
826
827    impl std::ops::Deref for Held {
828        type Target = tempfile::TempDir;
829
830        fn deref(&self) -> &Self::Target {
831            &self.dir
832        }
833    }
834
835    fn repo() -> Held {
836        let env = crate::test_env_lock();
837        let dir = tempfile::tempdir().unwrap();
838        git(dir.path(), &["init", "-q", "-b", "main"]);
839        git(dir.path(), &["config", "user.name", AUTHOR_NAME]);
840        git(dir.path(), &["config", "user.email", AUTHOR_EMAIL]);
841        git(dir.path(), &["config", "commit.gpgsign", "false"]);
842        git(
843            dir.path(),
844            &[
845                "remote",
846                "add",
847                "origin",
848                "https://example.com/acme/widgets.git",
849            ],
850        );
851        Held { _env: env, dir }
852    }
853
854    fn seed(dir: &Path) {
855        std::fs::write(dir.join("f.txt"), "one\n").unwrap();
856        git(dir, &["add", "f.txt"]);
857        git(dir, &["commit", "-q", "-m", "note the seat"]);
858    }
859
860    fn gates(dir: &Path, body: &str) {
861        std::fs::create_dir_all(dir.join(".ljos")).unwrap();
862        std::fs::write(dir.join(".ljos").join("gates.toml"), body).unwrap();
863    }
864
865    #[test]
866    fn git_calls_follow_dirs_shells_and_aliases() {
867        let dir = repo();
868        let root = dir.path();
869        std::fs::create_dir_all(root.join("sub")).unwrap();
870        git(root, &["config", "alias.ci", "commit -q"]);
871        git(
872            root,
873            &["config", "alias.ship", "!git add . && git push origin HEAD"],
874        );
875        let calls = git_calls(
876            "cd sub && git -C .. ci -m x; sh -c 'git ship'; echo $(git cherry-pick abc)",
877            Some(root),
878        )
879        .unwrap();
880        let subs: Vec<&str> = calls.iter().map(|c| c.sub.as_str()).collect();
881        assert_eq!(subs, ["commit", "add", "push", "cherry-pick"], "{calls:?}");
882        assert_eq!(calls[0].args, ["-q", "-m", "x"]);
883        assert_eq!(calls[0].cwd, root.join("sub").join(".."));
884        assert_eq!(calls[2].args, ["origin", "HEAD"]);
885        assert!(git_calls("ls -la", Some(root)).unwrap().is_empty());
886
887        for (name, next) in [("a", "b"), ("b", "c"), ("c", "d"), ("d", "e")] {
888            git(
889                root,
890                &["config", &format!("alias.{name}"), &format!("!git {next}")],
891            );
892        }
893        let deep = git_calls("git a", Some(root)).unwrap_err();
894        assert!(deep.contains("too deep"), "{deep}");
895    }
896
897    struct Layers;
898
899    impl Drop for Layers {
900        fn drop(&mut self) {
901            LAYER_HOME.with(|slot| *slot.borrow_mut() = None);
902            LAYER_SEAT.with(|slot| *slot.borrow_mut() = None);
903        }
904    }
905
906    fn layers(home: &Path, seat: Option<&str>) -> Layers {
907        LAYER_HOME.with(|slot| *slot.borrow_mut() = Some(home.to_path_buf()));
908        LAYER_SEAT.with(|slot| *slot.borrow_mut() = seat.map(str::to_string));
909        Layers
910    }
911
912    fn write_toml(path: &Path, body: &str) {
913        if let Some(parent) = path.parent() {
914            std::fs::create_dir_all(parent).unwrap();
915        }
916        std::fs::write(path, body).unwrap();
917    }
918
919    #[test]
920    fn the_person_sets_the_consensus_push_and_a_checkout_only_tightens_it() {
921        let dir = repo();
922        let cwd = dir.path();
923        let home = tempfile::tempdir().unwrap();
924        let _layers = layers(home.path(), Some("box"));
925        let read = || consensus_push(Some(cwd)).unwrap();
926        let names = |all: &[&str]| all.iter().map(|b| (*b).to_string()).collect::<Vec<_>>();
927        assert_eq!(read().quorum, 2);
928        assert_eq!(read().branches, names(&["develop", "main"]));
929        write_toml(
930            &home.path().join("ljos/ljos.toml"),
931            "[gates]\nquorum = 3\nconsensus_branches = [\"main\", \"release\"]\n",
932        );
933        assert_eq!(read().quorum, 3);
934        assert_eq!(read().branches, names(&["main", "release"]));
935        write_toml(
936            &home.path().join("ljos/seats/box/ljos.toml"),
937            "quorum = 1\n",
938        );
939        assert_eq!(read().quorum, 1, "the seat file is the person's too");
940        write_toml(
941            &cwd.join("ljos.toml"),
942            "quorum = 1\nconsensus_branches = []\n",
943        );
944        gates(
945            cwd,
946            "quorum = 2\nconsensus_branches = [\"refs/heads/stable\"]\n",
947        );
948        assert_eq!(read().quorum, 2, "a checkout raises the quorum");
949        assert_eq!(read().branches, names(&["main", "release", "stable"]));
950        write_toml(&cwd.join("ljos.toml"), "quorum = 0\n");
951        let zero = consensus_push(Some(cwd)).unwrap_err();
952        assert!(zero.contains("`quorum`"), "{zero}");
953        write_toml(&cwd.join("ljos.toml"), "quorum = [\n");
954        let broken = consensus_push(Some(cwd)).unwrap_err();
955        assert!(broken.contains("does not parse"), "{broken}");
956    }
957
958    #[test]
959    fn a_push_lands_where_git_would_put_it_and_an_unread_one_is_protected() {
960        let dir = repo();
961        let cwd = dir.path();
962        seed(cwd);
963        git(cwd, &["checkout", "-q", "-b", "topic"]);
964        let branches = ["develop".to_string(), "main".to_string()];
965        let lands = |line: &str| {
966            let calls = git_calls(line, Some(cwd)).unwrap();
967            let push = calls.iter().find(|c| c.sub == "push").unwrap();
968            protected_push(push, line, &branches)
969        };
970        let unread = |line: &str| {
971            lands(line).is_some_and(|d| d.starts_with("a branch the guard cannot tell"))
972        };
973        for line in [
974            "git push",
975            "git push origin",
976            "git push origin topic",
977            "git push -u origin HEAD",
978            "git push origin topic:refs/heads/topic",
979            "git push origin v1:refs/tags/develop",
980            "git push origin 'refs/tags/*:refs/tags/*'",
981            "git push develop topic",
982        ] {
983            assert_eq!(lands(line), None, "{line}");
984        }
985        for (line, dest) in [
986            ("git push origin HEAD:develop", "`develop`"),
987            ("git push origin topic:refs/heads/develop", "`develop`"),
988            ("git push origin +topic:heads/develop", "`develop`"),
989            ("git push origin :develop", "`develop`"),
990            ("git push --delete origin develop", "`develop`"),
991            ("git push origin topic HEAD:Main", "`main`"),
992            (
993                "git push https://example.com/acme/widgets.git main",
994                "`main`",
995            ),
996            ("git push --all origin", "every branch `--all` reaches"),
997            (
998                "git push origin 'refs/heads/*:refs/heads/*'",
999                "the branches `refs/heads/*:refs/heads/*` matches",
1000            ),
1001        ] {
1002            assert_eq!(lands(line).as_deref(), Some(dest), "{line}");
1003        }
1004        for line in [
1005            "git checkout develop && git push",
1006            "GIT_DIR=../other git push origin topic",
1007            "git -c remote.origin.push=refs/heads/topic:refs/heads/develop push origin topic",
1008            "git push origin $BRANCH",
1009            "git push --repo=origin topic",
1010            "git push origin topic:HEAD",
1011        ] {
1012            assert!(unread(line), "{line}: {:?}", lands(line));
1013        }
1014
1015        git(cwd, &["config", "branch.topic.merge", "refs/heads/develop"]);
1016        assert_eq!(lands("git push").as_deref(), Some("`develop`"));
1017        assert_eq!(lands("git push origin HEAD").as_deref(), Some("`develop`"));
1018        assert_eq!(
1019            lands("git push origin topic"),
1020            None,
1021            "simple names the branch"
1022        );
1023        git(cwd, &["config", "push.default", "upstream"]);
1024        assert_eq!(lands("git push origin topic").as_deref(), Some("`develop`"));
1025        git(cwd, &["config", "push.default", "current"]);
1026        assert_eq!(lands("git push"), None);
1027        git(cwd, &["config", "push.default", "nothing"]);
1028        assert_eq!(lands("git push"), None);
1029        git(cwd, &["config", "push.default", "matching"]);
1030        assert!(lands("git push")
1031            .unwrap()
1032            .starts_with("every branch both sides have"));
1033        git(cwd, &["config", "--unset", "push.default"]);
1034        git(
1035            cwd,
1036            &[
1037                "config",
1038                "remote.origin.push",
1039                "refs/heads/topic:refs/heads/develop",
1040            ],
1041        );
1042        assert!(unread("git push origin topic"));
1043        git(cwd, &["config", "--unset", "remote.origin.push"]);
1044        git(cwd, &["checkout", "-q", "--detach"]);
1045        assert!(unread("git push origin HEAD"));
1046        assert_eq!(lands("git push origin HEAD:refs/heads/topic"), None);
1047    }
1048}