git-custom-cli 2.4.0

Fast, keyboard-driven terminal UI for dated Git commits
//! How much confirmation a git operation needs. Modes ask `check` and pass the verdict to
//! `ui::gate`, so the rules live in one place:
//!
//! | Op                                         | confirm_destructive on | off     |
//! |--------------------------------------------|------------------------|---------|
//! | Plain                                      | Allow                  | Allow   |
//! | CreatesCommit, DeleteBranch{merged:true}   | Confirm                | Allow   |
//! | ResetHard, DeleteBranch{merged:false},     | Danger                 | Allow   |
//! |   DropStash, DeleteTag, Abort,             |                        |         |
//! |   RewriteHistory{published:false}          |                        |         |
//! | DiscardUnstaged, DiscardUntracked          | Danger                 | Danger  |
//! | RewriteHistory{published:true}             | Danger (Typed(branch) on a protected branch) |
//! | ForcePush, DeleteRemoteBranch              | Danger (Deny on a protected branch)          |
//!
//! Protection never depends on `confirm_destructive`. Callers still back up (see `safety`)
//! before ResetHard / DeleteBranch / DropStash / RewriteHistory even when the verdict is Allow.

use crate::model::Config;

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Op<'a> {
    ForcePush {
        remote: &'a str,
        branch: &'a str,
    },
    #[allow(dead_code)] // reserved for remote-branch deletes in a later round
    DeleteRemoteBranch {
        remote: &'a str,
        branch: &'a str,
    },
    RewriteHistory {
        branch: &'a str,
        published: bool,
    },
    ResetHard,
    DeleteBranch {
        branch: &'a str,
        merged: bool,
    },
    DiscardUnstaged,
    DiscardUntracked,
    DropStash,
    DeleteTag {
        remote: bool,
    },
    Abort,
    CreatesCommit,
    Plain,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Verdict {
    /// Run without asking.
    Allow,
    /// Plain yes/no, default Yes.
    Confirm,
    /// Red warning, default No.
    Danger,
    /// The user must type this text (the branch name).
    Typed(String),
    /// Refused, with the reason.
    Deny(String),
}

/// True when `branch` matches one of `cfg.protected_branches`. A pattern ending in '*' matches
/// by prefix ("release/*"); any other pattern must match exactly.
pub fn is_protected(cfg: &Config, branch: &str) -> bool {
    cfg.protected_branches.iter().any(|pattern| {
        let pattern = pattern.trim();
        match pattern.strip_suffix('*') {
            Some(prefix) => branch.starts_with(prefix),
            None => !pattern.is_empty() && pattern == branch,
        }
    })
}

pub fn check(cfg: &Config, op: &Op) -> Verdict {
    // Tiers the user may switch off with confirm_destructive = false.
    let ask = |verdict: Verdict| {
        if cfg.confirm_destructive {
            verdict
        } else {
            Verdict::Allow
        }
    };
    match op {
        Op::Plain => Verdict::Allow,
        Op::CreatesCommit | Op::DeleteBranch { merged: true, .. } => ask(Verdict::Confirm),
        Op::ResetHard
        | Op::DeleteBranch { merged: false, .. }
        | Op::DropStash
        | Op::DeleteTag { .. }
        | Op::Abort
        | Op::RewriteHistory {
            published: false, ..
        } => ask(Verdict::Danger),
        Op::DiscardUnstaged | Op::DiscardUntracked => Verdict::Danger,
        Op::RewriteHistory {
            branch,
            published: true,
        } => {
            if is_protected(cfg, branch) {
                Verdict::Typed((*branch).to_string())
            } else {
                Verdict::Danger
            }
        }
        Op::ForcePush { branch, .. } | Op::DeleteRemoteBranch { branch, .. } => {
            if is_protected(cfg, branch) {
                Verdict::Deny(format!(
                    "{branch} is protected; run git by hand if you really must"
                ))
            } else {
                Verdict::Danger
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn cfg(confirm: bool) -> Config {
        Config {
            confirm_destructive: confirm,
            protected_branches: vec!["main".into(), "release/*".into(), " ".into()],
            ..Config::default()
        }
    }

    #[test]
    fn protection_patterns() {
        let c = cfg(true);
        assert!(is_protected(&c, "main"));
        assert!(is_protected(&c, "release/1.0"));
        assert!(!is_protected(&c, "main2"));
        assert!(!is_protected(&c, "mai"));
        assert!(!is_protected(&c, "release"));
        assert!(!is_protected(&c, ""));
        assert!(is_protected(&Config::default(), "master"));
        let all = Config {
            protected_branches: vec!["*".into()],
            ..Config::default()
        };
        assert!(is_protected(&all, "anything"));
    }

    #[test]
    fn verdict_table() {
        use Verdict::*;
        let deny = Deny("main is protected; run git by hand if you really must".into());
        // (op, confirm_destructive on, off)
        let table: Vec<(Op, Verdict, Verdict)> = vec![
            (Op::Plain, Allow, Allow),
            (Op::CreatesCommit, Confirm, Allow),
            (
                Op::DeleteBranch {
                    branch: "x",
                    merged: true,
                },
                Confirm,
                Allow,
            ),
            (
                Op::DeleteBranch {
                    branch: "x",
                    merged: false,
                },
                Danger,
                Allow,
            ),
            (Op::ResetHard, Danger, Allow),
            (Op::DropStash, Danger, Allow),
            (Op::DeleteTag { remote: false }, Danger, Allow),
            (Op::DeleteTag { remote: true }, Danger, Allow),
            (Op::Abort, Danger, Allow),
            (
                Op::RewriteHistory {
                    branch: "main",
                    published: false,
                },
                Danger,
                Allow,
            ),
            (
                Op::RewriteHistory {
                    branch: "x",
                    published: false,
                },
                Danger,
                Allow,
            ),
            (Op::DiscardUnstaged, Danger, Danger),
            (Op::DiscardUntracked, Danger, Danger),
            (
                Op::RewriteHistory {
                    branch: "x",
                    published: true,
                },
                Danger,
                Danger,
            ),
            (
                Op::RewriteHistory {
                    branch: "main",
                    published: true,
                },
                Typed("main".into()),
                Typed("main".into()),
            ),
            (
                Op::ForcePush {
                    remote: "origin",
                    branch: "x",
                },
                Danger,
                Danger,
            ),
            (
                Op::ForcePush {
                    remote: "origin",
                    branch: "main",
                },
                deny.clone(),
                deny.clone(),
            ),
            (
                Op::DeleteRemoteBranch {
                    remote: "origin",
                    branch: "x",
                },
                Danger,
                Danger,
            ),
            (
                Op::DeleteRemoteBranch {
                    remote: "origin",
                    branch: "main",
                },
                deny.clone(),
                deny,
            ),
        ];
        for (op, on, off) in table {
            assert_eq!(check(&cfg(true), &op), on, "{op:?} on");
            assert_eq!(check(&cfg(false), &op), off, "{op:?} off");
        }
    }
}