1use 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#[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
53struct Answer {
56 key: &'static str,
57 value: Option<String>,
58 changed: bool,
59}
60
61pub fn command(args: &[std::ffi::OsString]) -> Result<(), String> {
62 let settings = match crate::hooks::common::repo_root_checked() {
70 Ok(root) => {
71 let manifest = crate::manifest::load(std::path::Path::new(&root));
72 crate::config::Settings::new(manifest.policy.clone())
73 }
74 Err(_) => crate::config::Settings::default(),
75 };
76 let dry_run = args.iter().any(|a| a == "--dry-run");
77 let asked_local = args.iter().any(|a| a == "--local");
78 let asked_global = args.iter().any(|a| a == "--global");
79 if asked_local && asked_global {
80 return Err(format!(
81 "{BIN} setup: --local and --global contradict each other"
82 ));
83 }
84 if let Some(bad) = args.iter().find(|a| {
85 !matches!(
86 a.to_str(),
87 Some("--dry-run") | Some("--local") | Some("--global")
88 )
89 }) {
90 return Err(format!(
91 "{BIN} setup: unknown argument {:?}\nusage: {BIN} setup [--local|--global] [--dry-run]",
92 bad.to_string_lossy()
93 ));
94 }
95
96 if asked_local && git::stdout(&["rev-parse", "--show-toplevel"]).is_none() {
100 return Err(format!("{BIN} setup --local: not inside a git repository"));
101 }
102
103 let (style, _) = commit_style::describe(&settings);
104
105 if !std::io::stdin().is_terminal() {
106 return offer_the_commands(
107 &style,
108 if asked_local {
109 Where::Local
110 } else {
111 Where::Global
112 },
113 );
114 }
115
116 let stdin = std::io::stdin();
117 let mut input = stdin.lock();
118 let forced = match (asked_local, asked_global) {
119 (true, _) => Some(Where::Local),
120 (_, true) => Some(Where::Global),
121 _ => None,
122 };
123 match ask_all(&mut input, &style, forced)? {
124 Some((scope, answers)) => apply(&answers, scope, dry_run),
125 None => quit(),
126 }
127}
128
129fn ask_all(
136 input: &mut impl BufRead,
137 style: &Style,
138 forced_scope: Option<Where>,
139) -> Result<Option<(Where, Vec<Answer>)>, String> {
140 println!("{BIN} setup — what `commit-msg` enforces, and how it decorates.");
141 println!("Nothing here disables a check; it changes what the check asks for.");
142 println!("Enter keeps the current value. `q` quits without writing anything.");
143
144 let scope = match forced_scope {
145 Some(s) => s,
146 None => match ask_scope(input)? {
147 Some(s) => s,
148 None => return Ok(None),
149 },
150 };
151
152 let mut answers = Vec::new();
153 match ask_gitmoji(input, style.gitmoji)? {
154 Some(a) => answers.push(a),
155 None => return Ok(None),
156 }
157 for (key, label, why, current, default) in [
158 (
159 KEY_SUBJECT_MAX,
160 "Maximum length of the whole subject line",
161 "72 is git's own convention, and what `git log --oneline` fits",
162 style.subject_max,
163 commit_style::DEFAULT_SUBJECT_MAX,
164 ),
165 (
166 KEY_DESCRIPTION_MAX,
167 "Maximum length of the description, after the `type: `",
168 "50 is the strict end of the convention; 68 still fits a 72-column \
169 subject with a short type and no scope",
170 style.description_max,
171 commit_style::DEFAULT_DESCRIPTION_MAX,
172 ),
173 (
174 KEY_BODY_WRAP,
175 "Hard-wrap the body at how many columns",
176 "0 leaves the body exactly as written — what keeps a pasted stack \
177 trace or a fenced code block intact",
178 style.body_wrap,
179 commit_style::DEFAULT_BODY_WRAP,
180 ),
181 ] {
182 match ask_number(input, key, label, why, current, default)? {
183 Some(a) => answers.push(a),
184 None => return Ok(None),
185 }
186 }
187
188 Ok(Some((scope, answers)))
189}
190
191fn quit() -> Result<(), String> {
192 println!("\nnothing written.");
193 Ok(())
194}
195
196fn apply(answers: &[Answer], scope: Where, dry_run: bool) -> Result<(), String> {
198 let changed: Vec<&Answer> = answers.iter().filter(|a| a.changed).collect();
199 println!();
200 if changed.is_empty() {
201 println!("nothing to change — every setting is already what you chose.");
202 } else {
203 println!(
204 "{} ({}):",
205 if dry_run { "would write" } else { "wrote" },
206 scope.word()
207 );
208 for a in &changed {
209 match &a.value {
210 Some(v) => println!(" git config {} {} {v}", scope.flag(), a.key),
211 None => println!(" git config {} --unset {}", scope.flag(), a.key),
215 }
216 }
217 if !dry_run {
218 for a in &changed {
219 let ok = match &a.value {
220 Some(v) => git::succeeds(&["config", scope.flag(), a.key, v]),
221 None => {
222 git::succeeds(&["config", scope.flag(), "--unset", a.key])
224 || matches!(
225 git::output(&["config", scope.flag(), "--get", a.key]),
226 Some(o) if o.code == 1
227 )
228 }
229 };
230 if !ok {
231 return Err(format!("{BIN} setup: could not write {}", a.key));
232 }
233 }
234 }
235 }
236
237 let unchanged: Vec<&Answer> = answers.iter().filter(|a| !a.changed).collect();
238 if !unchanged.is_empty() {
239 println!("\nunchanged:");
240 for a in unchanged {
241 println!(" {}", a.key);
242 }
243 }
244
245 println!("\nTwo more, per repository rather than per person:");
246 println!(" git config amont.fix true # let a check fix what it finds");
247 println!(" git config amont.testPushedTree true # test what you push, not your tree");
248 println!("\nRead it all back with: {BIN} list");
249 Ok(())
250}
251
252fn offer_the_commands(style: &Style, scope: Where) -> Result<(), String> {
259 eprintln!("{BIN} setup: not a terminal — nothing to ask. The keys, with their current values:");
260 println!(
261 "git config {} {KEY_GITMOJI} {}",
262 scope.flag(),
263 style.gitmoji.as_str()
264 );
265 println!(
266 "git config {} {KEY_SUBJECT_MAX} {}",
267 scope.flag(),
268 style.subject_max
269 );
270 println!(
271 "git config {} {KEY_DESCRIPTION_MAX} {}",
272 scope.flag(),
273 style.description_max
274 );
275 println!(
276 "git config {} {KEY_BODY_WRAP} {}",
277 scope.flag(),
278 style.body_wrap
279 );
280 Ok(())
281}
282
283fn prompt(input: &mut impl BufRead, question: &str, why: &str, current: &str) -> Option<String> {
285 println!("\n{question}");
286 if !why.is_empty() {
287 println!(" {why}");
288 }
289 print!(" [{}] > ", highlight(current));
290 let _ = std::io::stdout().flush();
291 let mut line = String::new();
292 if input.read_line(&mut line).ok()? == 0 {
293 return None; }
295 let answer = line.trim().to_string();
296 if answer.eq_ignore_ascii_case("q") {
297 return None;
298 }
299 Some(answer)
300}
301
302fn ask_scope(input: &mut impl BufRead) -> Result<Option<Where>, String> {
303 loop {
304 let Some(answer) = prompt(
305 input,
306 "Where should these settings go?",
307 "global is usually right — how you write commit messages is the same \
308 statement in every repository you have",
309 "global",
310 ) else {
311 return Ok(None);
312 };
313 match answer.as_str() {
314 "" | "global" => return Ok(Some(Where::Global)),
315 "local" => {
316 if git::stdout(&["rev-parse", "--show-toplevel"]).is_none() {
317 println!(" not inside a git repository — `local` has nowhere to go.");
318 continue;
319 }
320 return Ok(Some(Where::Local));
321 }
322 other => println!(" {other:?} is neither `global` nor `local`."),
323 }
324 }
325}
326
327fn ask_gitmoji(input: &mut impl BufRead, current: Gitmoji) -> Result<Option<Answer>, String> {
328 println!("\nWhere should the type's gitmoji go?");
329 for g in Gitmoji::ALL {
330 println!(" {:<9} {:<22} {}", g.as_str(), g.example(), g.explain());
331 }
332 loop {
333 print!(" [{}] > ", highlight(current.as_str()));
334 let _ = std::io::stdout().flush();
335 let mut line = String::new();
336 if input.read_line(&mut line).map_err(|e| e.to_string())? == 0 {
337 return Ok(None);
338 }
339 let answer = line.trim();
340 if answer.eq_ignore_ascii_case("q") {
341 return Ok(None);
342 }
343 let chosen = if answer.is_empty() {
344 current
345 } else {
346 match Gitmoji::parse(&answer.to_ascii_lowercase()) {
347 Some(g) => g,
348 None => {
349 println!(" {answer:?} is not one of the four above.");
350 continue;
351 }
352 }
353 };
354 return Ok(Some(answer_for(
355 KEY_GITMOJI,
356 chosen.as_str().to_string(),
357 commit_style::DEFAULT_GITMOJI.as_str().to_string(),
358 current.as_str().to_string(),
359 )));
360 }
361}
362
363fn ask_number(
364 input: &mut impl BufRead,
365 key: &'static str,
366 label: &str,
367 why: &str,
368 current: usize,
369 default: usize,
370) -> Result<Option<Answer>, String> {
371 loop {
372 let Some(answer) = prompt(input, label, why, ¤t.to_string()) else {
373 return Ok(None);
374 };
375 let chosen = if answer.is_empty() {
376 current
377 } else {
378 match answer.parse::<usize>() {
379 Ok(n) => n,
380 Err(_) => {
381 println!(" {answer:?} is not a number.");
382 continue;
383 }
384 }
385 };
386 return Ok(Some(answer_for(
387 key,
388 chosen.to_string(),
389 default.to_string(),
390 current.to_string(),
391 )));
392 }
393}
394
395fn answer_for(key: &'static str, chosen: String, default: String, current: String) -> Answer {
401 let changed = chosen != current;
402 Answer {
403 key,
404 value: if chosen == default {
405 None
406 } else {
407 Some(chosen)
408 },
409 changed,
410 }
411}
412
413#[cfg(test)]
414mod tests {
415 use super::*;
416
417 #[test]
420 fn choosing_the_default_unsets_the_key() {
421 let a = answer_for(KEY_SUBJECT_MAX, "72".into(), "72".into(), "100".into());
422 assert!(a.value.is_none(), "should unset");
423 assert!(a.changed);
424
425 let b = answer_for(KEY_SUBJECT_MAX, "100".into(), "72".into(), "72".into());
426 assert_eq!(b.value.as_deref(), Some("100"));
427 assert!(b.changed);
428 }
429
430 #[test]
433 fn keeping_the_current_value_changes_nothing() {
434 let a = answer_for(KEY_SUBJECT_MAX, "100".into(), "72".into(), "100".into());
435 assert!(!a.changed);
436 }
437
438 #[test]
439 fn the_two_scopes_spell_themselves_for_git() {
440 assert_eq!(Where::Local.flag(), "--local");
441 assert_eq!(Where::Global.flag(), "--global");
442 }
443
444 #[test]
447 fn q_and_eof_both_mean_quit() {
448 let mut q = std::io::Cursor::new(b"q\n".to_vec());
449 assert!(prompt(&mut q, "x", "", "d").is_none());
450 let mut eof = std::io::Cursor::new(Vec::new());
451 assert!(prompt(&mut eof, "x", "", "d").is_none());
452 let mut enter = std::io::Cursor::new(b"\n".to_vec());
453 assert_eq!(prompt(&mut enter, "x", "", "d").as_deref(), Some(""));
454 }
455
456 fn answers(input: &str, style: &Style) -> Option<(Where, Vec<Answer>)> {
457 let mut cursor = std::io::Cursor::new(input.as_bytes().to_vec());
458 ask_all(&mut cursor, style, None).expect("the flow does not fail")
459 }
460
461 fn value(list: &[Answer], key: &str) -> Option<String> {
462 list.iter()
463 .find(|a| a.key == key)
464 .and_then(|a| a.value.clone())
465 }
466
467 #[test]
469 fn every_answer_reaches_its_key() {
470 let (scope, list) = answers("global\nsuffix\n100\n68\n0\n", &Style::default()).unwrap();
471 assert_eq!(scope, Where::Global);
472 assert_eq!(value(&list, KEY_GITMOJI).as_deref(), Some("suffix"));
473 assert_eq!(value(&list, KEY_SUBJECT_MAX).as_deref(), Some("100"));
474 assert_eq!(value(&list, KEY_DESCRIPTION_MAX).as_deref(), Some("68"));
475 assert_eq!(value(&list, KEY_BODY_WRAP).as_deref(), Some("0"));
476 }
477
478 #[test]
483 fn accepting_every_default_changes_nothing() {
484 let (_, list) = answers("\n\n\n\n\n", &Style::default()).unwrap();
485 assert!(
486 list.iter().all(|a| !a.changed),
487 "something was marked changed: {:?}",
488 list.iter().map(|a| a.key).collect::<Vec<_>>()
489 );
490 }
491
492 #[test]
495 fn the_offered_default_is_what_is_in_effect() {
496 let configured = Style {
497 gitmoji: Gitmoji::Prefix,
498 subject_max: 100,
499 ..Style::default()
500 };
501 let (_, list) = answers("\n\n\n\n\n", &configured).unwrap();
502 assert!(list.iter().all(|a| !a.changed));
503 assert_eq!(value(&list, KEY_GITMOJI).as_deref(), Some("prefix"));
505 assert_eq!(value(&list, KEY_SUBJECT_MAX).as_deref(), Some("100"));
506 }
507
508 #[test]
511 fn returning_to_the_default_unsets_rather_than_pins() {
512 let configured = Style {
513 subject_max: 100,
514 ..Style::default()
515 };
516 let (_, list) = answers("\nnone\n72\n\n\n", &configured).unwrap();
517 let subject = list
518 .iter()
519 .find(|a| a.key == KEY_SUBJECT_MAX)
520 .expect("asked");
521 assert!(subject.changed);
522 assert!(subject.value.is_none(), "should unset, not write 72");
523 }
524
525 #[test]
527 fn an_unusable_answer_is_asked_again() {
528 let (_, list) = answers(
529 "sideways\nglobal\nnope\nsuffix\nlots\n80\n\n\n",
530 &Style::default(),
531 )
532 .unwrap();
533 assert_eq!(value(&list, KEY_GITMOJI).as_deref(), Some("suffix"));
534 assert_eq!(value(&list, KEY_SUBJECT_MAX).as_deref(), Some("80"));
535 }
536
537 #[test]
539 fn quitting_midway_discards_the_answers_already_given() {
540 assert!(answers("global\nsuffix\nq\n", &Style::default()).is_none());
541 assert!(answers("global\nsuffix\n", &Style::default()).is_none());
543 }
544}