Skip to main content

greengate_runtime/
setup.rs

1//! `amont setup` — choose what `commit-msg` enforces, once.
2//!
3//! The keys in [`crate::commit_style`] are the answer to "these defaults do not
4//! suit me". This is the answer to "I did not know there were any". An adoption
5//! feature is only half built if the dial exists and nobody finds it, so the
6//! same four settings are offered here, each with its current value as the
7//! default and one line saying what it is for.
8//!
9//! **Input is stdin, not `/dev/tty`.** `trust::confirm` opens `/dev/tty`
10//! because it prompts from inside a *hook*, where git owns stdin and reading it
11//! would consume a pre-push ref list. That reasoning does not reach here: this
12//! is a subcommand somebody typed, and its stdin IS the terminal. The general
13//! rule, worth stating once: `/dev/tty` for a prompt inside a hook, stdin for a
14//! prompt inside a subcommand. Reading stdin also works on Windows — where
15//! `confirm` is hard-coded to decline — and can be driven by a heredoc, which
16//! is how this is tested without a pty.
17//!
18//! Nothing is written until every question has been answered, and what does get
19//! written is printed as the `git config` commands that would produce it. A
20//! wizard that reports "saved" has told you nothing you can check, paste into
21//! your dotfiles, or hand to a teammate.
22
23use crate::commit_style::{
24    self, Gitmoji, Style, KEY_BODY_WRAP, KEY_DESCRIPTION_MAX, KEY_GITMOJI, KEY_SUBJECT_MAX,
25};
26use crate::git;
27use crate::names::BIN;
28use crate::ui::highlight;
29use std::io::{BufRead, IsTerminal, Write};
30
31/// Where the answers are written.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum Where {
34    Local,
35    Global,
36}
37
38impl Where {
39    fn flag(self) -> &'static str {
40        match self {
41            Where::Local => "--local",
42            Where::Global => "--global",
43        }
44    }
45    fn word(self) -> &'static str {
46        match self {
47            Where::Local => "local",
48            Where::Global => "global",
49        }
50    }
51}
52
53/// One decided setting: the key, and the value to write — or `None` to unset,
54/// which is how a setting returns to the shipped default.
55struct Answer {
56    key: &'static str,
57    value: Option<String>,
58    changed: bool,
59}
60
61pub fn command(args: &[std::ffi::OsString]) -> Result<(), String> {
62    // INVARIANT: policy installed immediately after every manifest::load —
63    // setup DISPLAYS effective values, and without the policy it would show
64    // pre-policy state as "current" and offer to re-write it. What setup
65    // WRITES is --local/--global git config, so the ladder stays correct
66    // either way; only the display needed the truth.
67    // Outside a repository there is no manifest and so no policy — the same
68    // state the global store used to be in when nothing had installed it.
69    let settings = match crate::hooks::common::repo_root_checked() {
70        Ok(root) => {
71            // Builds no check, so it resolves no trigger: it reads only the
72            // policy, to display effective values.
73            let manifest = crate::manifest::load(std::path::Path::new(&root));
74            crate::config::Settings::new(manifest.policy.clone())
75        }
76        Err(_) => crate::config::Settings::default(),
77    };
78    let dry_run = args.iter().any(|a| a == "--dry-run");
79    let asked_local = args.iter().any(|a| a == "--local");
80    let asked_global = args.iter().any(|a| a == "--global");
81    if asked_local && asked_global {
82        return Err(format!(
83            "{BIN} setup: --local and --global contradict each other"
84        ));
85    }
86    if let Some(bad) = args.iter().find(|a| {
87        !matches!(
88            a.to_str(),
89            Some("--dry-run") | Some("--local") | Some("--global")
90        )
91    }) {
92        return Err(format!(
93            "{BIN} setup: unknown argument {:?}\nusage: {BIN} setup [--local|--global] [--dry-run]",
94            bad.to_string_lossy()
95        ));
96    }
97
98    // `--local` needs a repository, and refusing beats falling back to `.` —
99    // the same reasoning `trust::command` records: a fallback would write a
100    // setting into whatever directory somebody happened to be standing in.
101    if asked_local && git::stdout(&["rev-parse", "--show-toplevel"]).is_none() {
102        return Err(format!("{BIN} setup --local: not inside a git repository"));
103    }
104
105    let (style, _) = commit_style::describe(&settings);
106
107    if !std::io::stdin().is_terminal() {
108        return offer_the_commands(
109            &style,
110            if asked_local {
111                Where::Local
112            } else {
113                Where::Global
114            },
115        );
116    }
117
118    let stdin = std::io::stdin();
119    let mut input = stdin.lock();
120    let forced = match (asked_local, asked_global) {
121        (true, _) => Some(Where::Local),
122        (_, true) => Some(Where::Global),
123        _ => None,
124    };
125    match ask_all(&mut input, &style, forced)? {
126        Some((scope, answers)) => apply(&answers, scope, dry_run),
127        None => quit(),
128    }
129}
130
131/// Every question, in order. `None` means the reader quit and nothing should be
132/// written.
133///
134/// Takes its input as a `BufRead` rather than reaching for stdin itself, which
135/// is what lets the whole flow — defaults, re-asking on a bad answer, quitting
136/// — be tested without a pseudo-terminal.
137fn ask_all(
138    input: &mut impl BufRead,
139    style: &Style,
140    forced_scope: Option<Where>,
141) -> Result<Option<(Where, Vec<Answer>)>, String> {
142    println!("{BIN} setup — what `commit-msg` enforces, and how it decorates.");
143    println!("Nothing here disables a check; it changes what the check asks for.");
144    println!("Enter keeps the current value. `q` quits without writing anything.");
145
146    let scope = match forced_scope {
147        Some(s) => s,
148        None => match ask_scope(input)? {
149            Some(s) => s,
150            None => return Ok(None),
151        },
152    };
153
154    let mut answers = Vec::new();
155    match ask_gitmoji(input, style.gitmoji)? {
156        Some(a) => answers.push(a),
157        None => return Ok(None),
158    }
159    for (key, label, why, current, default) in [
160        (
161            KEY_SUBJECT_MAX,
162            "Maximum length of the whole subject line",
163            "72 is git's own convention, and what `git log --oneline` fits",
164            style.subject_max,
165            commit_style::DEFAULT_SUBJECT_MAX,
166        ),
167        (
168            KEY_DESCRIPTION_MAX,
169            "Maximum length of the description, after the `type: `",
170            "50 is the strict end of the convention; 68 still fits a 72-column \
171             subject with a short type and no scope",
172            style.description_max,
173            commit_style::DEFAULT_DESCRIPTION_MAX,
174        ),
175        (
176            KEY_BODY_WRAP,
177            "Hard-wrap the body at how many columns",
178            "0 leaves the body exactly as written — what keeps a pasted stack \
179             trace or a fenced code block intact",
180            style.body_wrap,
181            commit_style::DEFAULT_BODY_WRAP,
182        ),
183    ] {
184        match ask_number(input, key, label, why, current, default)? {
185            Some(a) => answers.push(a),
186            None => return Ok(None),
187        }
188    }
189
190    Ok(Some((scope, answers)))
191}
192
193fn quit() -> Result<(), String> {
194    println!("\nnothing written.");
195    Ok(())
196}
197
198/// Write the answers, and print exactly what was written.
199fn apply(answers: &[Answer], scope: Where, dry_run: bool) -> Result<(), String> {
200    let changed: Vec<&Answer> = answers.iter().filter(|a| a.changed).collect();
201    println!();
202    if changed.is_empty() {
203        println!("nothing to change — every setting is already what you chose.");
204    } else {
205        println!(
206            "{} ({}):",
207            if dry_run { "would write" } else { "wrote" },
208            scope.word()
209        );
210        for a in &changed {
211            match &a.value {
212                Some(v) => println!("  git config {} {} {v}", scope.flag(), a.key),
213                // Unsetting is how a setting goes back to the shipped default,
214                // which is a state `git config <key> <default>` cannot express:
215                // one is "I chose this", the other is "I have no opinion".
216                None => println!("  git config {} --unset {}", scope.flag(), a.key),
217            }
218        }
219        if !dry_run {
220            for a in &changed {
221                let ok = match &a.value {
222                    Some(v) => git::succeeds(&["config", scope.flag(), a.key, v]),
223                    None => {
224                        // Exit 5 is "nothing to unset", which is success here.
225                        git::succeeds(&["config", scope.flag(), "--unset", a.key])
226                            || matches!(
227                                git::output(&["config", scope.flag(), "--get", a.key]),
228                                Some(o) if o.code == 1
229                            )
230                    }
231                };
232                if !ok {
233                    return Err(format!("{BIN} setup: could not write {}", a.key));
234                }
235            }
236        }
237    }
238
239    let unchanged: Vec<&Answer> = answers.iter().filter(|a| !a.changed).collect();
240    if !unchanged.is_empty() {
241        println!("\nunchanged:");
242        for a in unchanged {
243            println!("  {}", a.key);
244        }
245    }
246
247    // Hints for the person, not the answer: on stderr.
248    eprintln!("\nTwo more, per repository rather than per person:");
249    eprintln!("  git config greengate.fix true             # let a check fix what it finds");
250    eprintln!("  git config greengate.testPushedTree true  # test what you push, not your tree");
251    eprintln!("\nRead it all back with:  {BIN} list");
252    Ok(())
253}
254
255/// Not a terminal: print the keys and their current values as commands, and
256/// exit **0**.
257///
258/// `amont setup > setup.sh` in a provisioning script should produce
259/// something usable rather than an error. The refusal goes to stderr so it does
260/// not end up in that file.
261fn offer_the_commands(style: &Style, scope: Where) -> Result<(), String> {
262    eprintln!("{BIN} setup: not a terminal — nothing to ask. The keys, with their current values:");
263    println!(
264        "git config {} {KEY_GITMOJI} {}",
265        scope.flag(),
266        style.gitmoji.as_str()
267    );
268    println!(
269        "git config {} {KEY_SUBJECT_MAX} {}",
270        scope.flag(),
271        style.subject_max
272    );
273    println!(
274        "git config {} {KEY_DESCRIPTION_MAX} {}",
275        scope.flag(),
276        style.description_max
277    );
278    println!(
279        "git config {} {KEY_BODY_WRAP} {}",
280        scope.flag(),
281        style.body_wrap
282    );
283    Ok(())
284}
285
286/// Read one answer. `None` means quit — `q`, or end of input.
287fn prompt(input: &mut impl BufRead, question: &str, why: &str, current: &str) -> Option<String> {
288    println!("\n{question}");
289    if !why.is_empty() {
290        println!("  {why}");
291    }
292    print!("  [{}] > ", highlight(current));
293    let _ = std::io::stdout().flush();
294    let mut line = String::new();
295    if input.read_line(&mut line).ok()? == 0 {
296        return None; // EOF
297    }
298    let answer = line.trim().to_string();
299    if answer.eq_ignore_ascii_case("q") {
300        return None;
301    }
302    Some(answer)
303}
304
305fn ask_scope(input: &mut impl BufRead) -> Result<Option<Where>, String> {
306    loop {
307        let Some(answer) = prompt(
308            input,
309            "Where should these settings go?",
310            "global is usually right — how you write commit messages is the same \
311             statement in every repository you have",
312            "global",
313        ) else {
314            return Ok(None);
315        };
316        match answer.as_str() {
317            "" | "global" => return Ok(Some(Where::Global)),
318            "local" => {
319                if git::stdout(&["rev-parse", "--show-toplevel"]).is_none() {
320                    println!("  not inside a git repository — `local` has nowhere to go.");
321                    continue;
322                }
323                return Ok(Some(Where::Local));
324            }
325            other => println!("  {other:?} is neither `global` nor `local`."),
326        }
327    }
328}
329
330fn ask_gitmoji(input: &mut impl BufRead, current: Gitmoji) -> Result<Option<Answer>, String> {
331    println!("\nWhere should the type's gitmoji go?");
332    for g in Gitmoji::ALL {
333        println!("  {:<9} {:<22} {}", g.as_str(), g.example(), g.explain());
334    }
335    loop {
336        print!("  [{}] > ", highlight(current.as_str()));
337        let _ = std::io::stdout().flush();
338        let mut line = String::new();
339        if input.read_line(&mut line).map_err(|e| e.to_string())? == 0 {
340            return Ok(None);
341        }
342        let answer = line.trim();
343        if answer.eq_ignore_ascii_case("q") {
344            return Ok(None);
345        }
346        let chosen = if answer.is_empty() {
347            current
348        } else {
349            match Gitmoji::parse(&answer.to_ascii_lowercase()) {
350                Some(g) => g,
351                None => {
352                    println!("  {answer:?} is not one of the four above.");
353                    continue;
354                }
355            }
356        };
357        return Ok(Some(answer_for(
358            KEY_GITMOJI,
359            chosen.as_str().to_string(),
360            commit_style::DEFAULT_GITMOJI.as_str().to_string(),
361            current.as_str().to_string(),
362        )));
363    }
364}
365
366fn ask_number(
367    input: &mut impl BufRead,
368    key: &'static str,
369    label: &str,
370    why: &str,
371    current: usize,
372    default: usize,
373) -> Result<Option<Answer>, String> {
374    loop {
375        let Some(answer) = prompt(input, label, why, &current.to_string()) else {
376            return Ok(None);
377        };
378        let chosen = if answer.is_empty() {
379            current
380        } else {
381            match answer.parse::<usize>() {
382                Ok(n) => n,
383                Err(_) => {
384                    println!("  {answer:?} is not a number.");
385                    continue;
386                }
387            }
388        };
389        return Ok(Some(answer_for(
390            key,
391            chosen.to_string(),
392            default.to_string(),
393            current.to_string(),
394        )));
395    }
396}
397
398/// A chosen value, as a write instruction.
399///
400/// Choosing the shipped default writes an **unset**, not the value: the two
401/// are different statements, and a config file full of keys set to what they
402/// already were is noise somebody else has to read.
403fn answer_for(key: &'static str, chosen: String, default: String, current: String) -> Answer {
404    let changed = chosen != current;
405    Answer {
406        key,
407        value: if chosen == default {
408            None
409        } else {
410            Some(chosen)
411        },
412        changed,
413    }
414}
415
416#[cfg(test)]
417mod tests {
418    use super::*;
419
420    /// Choosing the default means the key goes away, not that it gets written
421    /// with a value equal to the default.
422    #[test]
423    fn choosing_the_default_unsets_the_key() {
424        let a = answer_for(KEY_SUBJECT_MAX, "72".into(), "72".into(), "100".into());
425        assert!(a.value.is_none(), "should unset");
426        assert!(a.changed);
427
428        let b = answer_for(KEY_SUBJECT_MAX, "100".into(), "72".into(), "72".into());
429        assert_eq!(b.value.as_deref(), Some("100"));
430        assert!(b.changed);
431    }
432
433    /// Answering with what is already in effect is not a change, so the wizard
434    /// writes nothing and says so. That is what makes re-running it safe.
435    #[test]
436    fn keeping_the_current_value_changes_nothing() {
437        let a = answer_for(KEY_SUBJECT_MAX, "100".into(), "72".into(), "100".into());
438        assert!(!a.changed);
439    }
440
441    #[test]
442    fn the_two_scopes_spell_themselves_for_git() {
443        assert_eq!(Where::Local.flag(), "--local");
444        assert_eq!(Where::Global.flag(), "--global");
445    }
446
447    /// A quit at any prompt writes nothing — a half-applied wizard is the worst
448    /// outcome available.
449    #[test]
450    fn q_and_eof_both_mean_quit() {
451        let mut q = std::io::Cursor::new(b"q\n".to_vec());
452        assert!(prompt(&mut q, "x", "", "d").is_none());
453        let mut eof = std::io::Cursor::new(Vec::new());
454        assert!(prompt(&mut eof, "x", "", "d").is_none());
455        let mut enter = std::io::Cursor::new(b"\n".to_vec());
456        assert_eq!(prompt(&mut enter, "x", "", "d").as_deref(), Some(""));
457    }
458
459    fn answers(input: &str, style: &Style) -> Option<(Where, Vec<Answer>)> {
460        let mut cursor = std::io::Cursor::new(input.as_bytes().to_vec());
461        ask_all(&mut cursor, style, None).expect("the flow does not fail")
462    }
463
464    fn value(list: &[Answer], key: &str) -> Option<String> {
465        list.iter()
466            .find(|a| a.key == key)
467            .and_then(|a| a.value.clone())
468    }
469
470    /// The whole flow, answered.
471    #[test]
472    fn every_answer_reaches_its_key() {
473        let (scope, list) = answers("global\nsuffix\n100\n68\n0\n", &Style::default()).unwrap();
474        assert_eq!(scope, Where::Global);
475        assert_eq!(value(&list, KEY_GITMOJI).as_deref(), Some("suffix"));
476        assert_eq!(value(&list, KEY_SUBJECT_MAX).as_deref(), Some("100"));
477        assert_eq!(value(&list, KEY_DESCRIPTION_MAX).as_deref(), Some("68"));
478        assert_eq!(value(&list, KEY_BODY_WRAP).as_deref(), Some("0"));
479    }
480
481    /// PROPERTY: pressing Enter through the whole wizard writes nothing.
482    ///
483    /// That is what makes re-running it safe — the brackets show what is in
484    /// effect, so accepting them all is by definition a no-op.
485    #[test]
486    fn accepting_every_default_changes_nothing() {
487        let (_, list) = answers("\n\n\n\n\n", &Style::default()).unwrap();
488        assert!(
489            list.iter().all(|a| !a.changed),
490            "something was marked changed: {:?}",
491            list.iter().map(|a| a.key).collect::<Vec<_>>()
492        );
493    }
494
495    /// The brackets show the CURRENT value, not the shipped one, so a reader
496    /// who already configured something is not quietly offered a reset.
497    #[test]
498    fn the_offered_default_is_what_is_in_effect() {
499        let configured = Style {
500            gitmoji: Gitmoji::Prefix,
501            subject_max: 100,
502            ..Style::default()
503        };
504        let (_, list) = answers("\n\n\n\n\n", &configured).unwrap();
505        assert!(list.iter().all(|a| !a.changed));
506        // Keeping a non-default value keeps it WRITTEN, not unset.
507        assert_eq!(value(&list, KEY_GITMOJI).as_deref(), Some("prefix"));
508        assert_eq!(value(&list, KEY_SUBJECT_MAX).as_deref(), Some("100"));
509    }
510
511    /// Answering with the shipped default removes the key rather than pinning
512    /// it — "I have no opinion" is a different statement from "I chose this".
513    #[test]
514    fn returning_to_the_default_unsets_rather_than_pins() {
515        let configured = Style {
516            subject_max: 100,
517            ..Style::default()
518        };
519        let (_, list) = answers("\nnone\n72\n\n\n", &configured).unwrap();
520        let subject = list
521            .iter()
522            .find(|a| a.key == KEY_SUBJECT_MAX)
523            .expect("asked");
524        assert!(subject.changed);
525        assert!(subject.value.is_none(), "should unset, not write 72");
526    }
527
528    /// A bad answer re-asks rather than aborting or silently taking a default.
529    #[test]
530    fn an_unusable_answer_is_asked_again() {
531        let (_, list) = answers(
532            "sideways\nglobal\nnope\nsuffix\nlots\n80\n\n\n",
533            &Style::default(),
534        )
535        .unwrap();
536        assert_eq!(value(&list, KEY_GITMOJI).as_deref(), Some("suffix"));
537        assert_eq!(value(&list, KEY_SUBJECT_MAX).as_deref(), Some("80"));
538    }
539
540    /// Quitting partway writes nothing at all.
541    #[test]
542    fn quitting_midway_discards_the_answers_already_given() {
543        assert!(answers("global\nsuffix\nq\n", &Style::default()).is_none());
544        // And end of input is the same thing.
545        assert!(answers("global\nsuffix\n", &Style::default()).is_none());
546    }
547}