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));
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 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
131fn 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
198fn 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 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 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 println!("\nTwo more, per repository rather than per person:");
248 println!(" git config amont.fix true # let a check fix what it finds");
249 println!(" git config amont.testPushedTree true # test what you push, not your tree");
250 println!("\nRead it all back with: {BIN} list");
251 Ok(())
252}
253
254fn offer_the_commands(style: &Style, scope: Where) -> Result<(), String> {
261 eprintln!("{BIN} setup: not a terminal — nothing to ask. The keys, with their current values:");
262 println!(
263 "git config {} {KEY_GITMOJI} {}",
264 scope.flag(),
265 style.gitmoji.as_str()
266 );
267 println!(
268 "git config {} {KEY_SUBJECT_MAX} {}",
269 scope.flag(),
270 style.subject_max
271 );
272 println!(
273 "git config {} {KEY_DESCRIPTION_MAX} {}",
274 scope.flag(),
275 style.description_max
276 );
277 println!(
278 "git config {} {KEY_BODY_WRAP} {}",
279 scope.flag(),
280 style.body_wrap
281 );
282 Ok(())
283}
284
285fn prompt(input: &mut impl BufRead, question: &str, why: &str, current: &str) -> Option<String> {
287 println!("\n{question}");
288 if !why.is_empty() {
289 println!(" {why}");
290 }
291 print!(" [{}] > ", highlight(current));
292 let _ = std::io::stdout().flush();
293 let mut line = String::new();
294 if input.read_line(&mut line).ok()? == 0 {
295 return None; }
297 let answer = line.trim().to_string();
298 if answer.eq_ignore_ascii_case("q") {
299 return None;
300 }
301 Some(answer)
302}
303
304fn ask_scope(input: &mut impl BufRead) -> Result<Option<Where>, String> {
305 loop {
306 let Some(answer) = prompt(
307 input,
308 "Where should these settings go?",
309 "global is usually right — how you write commit messages is the same \
310 statement in every repository you have",
311 "global",
312 ) else {
313 return Ok(None);
314 };
315 match answer.as_str() {
316 "" | "global" => return Ok(Some(Where::Global)),
317 "local" => {
318 if git::stdout(&["rev-parse", "--show-toplevel"]).is_none() {
319 println!(" not inside a git repository — `local` has nowhere to go.");
320 continue;
321 }
322 return Ok(Some(Where::Local));
323 }
324 other => println!(" {other:?} is neither `global` nor `local`."),
325 }
326 }
327}
328
329fn ask_gitmoji(input: &mut impl BufRead, current: Gitmoji) -> Result<Option<Answer>, String> {
330 println!("\nWhere should the type's gitmoji go?");
331 for g in Gitmoji::ALL {
332 println!(" {:<9} {:<22} {}", g.as_str(), g.example(), g.explain());
333 }
334 loop {
335 print!(" [{}] > ", highlight(current.as_str()));
336 let _ = std::io::stdout().flush();
337 let mut line = String::new();
338 if input.read_line(&mut line).map_err(|e| e.to_string())? == 0 {
339 return Ok(None);
340 }
341 let answer = line.trim();
342 if answer.eq_ignore_ascii_case("q") {
343 return Ok(None);
344 }
345 let chosen = if answer.is_empty() {
346 current
347 } else {
348 match Gitmoji::parse(&answer.to_ascii_lowercase()) {
349 Some(g) => g,
350 None => {
351 println!(" {answer:?} is not one of the four above.");
352 continue;
353 }
354 }
355 };
356 return Ok(Some(answer_for(
357 KEY_GITMOJI,
358 chosen.as_str().to_string(),
359 commit_style::DEFAULT_GITMOJI.as_str().to_string(),
360 current.as_str().to_string(),
361 )));
362 }
363}
364
365fn ask_number(
366 input: &mut impl BufRead,
367 key: &'static str,
368 label: &str,
369 why: &str,
370 current: usize,
371 default: usize,
372) -> Result<Option<Answer>, String> {
373 loop {
374 let Some(answer) = prompt(input, label, why, ¤t.to_string()) else {
375 return Ok(None);
376 };
377 let chosen = if answer.is_empty() {
378 current
379 } else {
380 match answer.parse::<usize>() {
381 Ok(n) => n,
382 Err(_) => {
383 println!(" {answer:?} is not a number.");
384 continue;
385 }
386 }
387 };
388 return Ok(Some(answer_for(
389 key,
390 chosen.to_string(),
391 default.to_string(),
392 current.to_string(),
393 )));
394 }
395}
396
397fn answer_for(key: &'static str, chosen: String, default: String, current: String) -> Answer {
403 let changed = chosen != current;
404 Answer {
405 key,
406 value: if chosen == default {
407 None
408 } else {
409 Some(chosen)
410 },
411 changed,
412 }
413}
414
415#[cfg(test)]
416mod tests {
417 use super::*;
418
419 #[test]
422 fn choosing_the_default_unsets_the_key() {
423 let a = answer_for(KEY_SUBJECT_MAX, "72".into(), "72".into(), "100".into());
424 assert!(a.value.is_none(), "should unset");
425 assert!(a.changed);
426
427 let b = answer_for(KEY_SUBJECT_MAX, "100".into(), "72".into(), "72".into());
428 assert_eq!(b.value.as_deref(), Some("100"));
429 assert!(b.changed);
430 }
431
432 #[test]
435 fn keeping_the_current_value_changes_nothing() {
436 let a = answer_for(KEY_SUBJECT_MAX, "100".into(), "72".into(), "100".into());
437 assert!(!a.changed);
438 }
439
440 #[test]
441 fn the_two_scopes_spell_themselves_for_git() {
442 assert_eq!(Where::Local.flag(), "--local");
443 assert_eq!(Where::Global.flag(), "--global");
444 }
445
446 #[test]
449 fn q_and_eof_both_mean_quit() {
450 let mut q = std::io::Cursor::new(b"q\n".to_vec());
451 assert!(prompt(&mut q, "x", "", "d").is_none());
452 let mut eof = std::io::Cursor::new(Vec::new());
453 assert!(prompt(&mut eof, "x", "", "d").is_none());
454 let mut enter = std::io::Cursor::new(b"\n".to_vec());
455 assert_eq!(prompt(&mut enter, "x", "", "d").as_deref(), Some(""));
456 }
457
458 fn answers(input: &str, style: &Style) -> Option<(Where, Vec<Answer>)> {
459 let mut cursor = std::io::Cursor::new(input.as_bytes().to_vec());
460 ask_all(&mut cursor, style, None).expect("the flow does not fail")
461 }
462
463 fn value(list: &[Answer], key: &str) -> Option<String> {
464 list.iter()
465 .find(|a| a.key == key)
466 .and_then(|a| a.value.clone())
467 }
468
469 #[test]
471 fn every_answer_reaches_its_key() {
472 let (scope, list) = answers("global\nsuffix\n100\n68\n0\n", &Style::default()).unwrap();
473 assert_eq!(scope, Where::Global);
474 assert_eq!(value(&list, KEY_GITMOJI).as_deref(), Some("suffix"));
475 assert_eq!(value(&list, KEY_SUBJECT_MAX).as_deref(), Some("100"));
476 assert_eq!(value(&list, KEY_DESCRIPTION_MAX).as_deref(), Some("68"));
477 assert_eq!(value(&list, KEY_BODY_WRAP).as_deref(), Some("0"));
478 }
479
480 #[test]
485 fn accepting_every_default_changes_nothing() {
486 let (_, list) = answers("\n\n\n\n\n", &Style::default()).unwrap();
487 assert!(
488 list.iter().all(|a| !a.changed),
489 "something was marked changed: {:?}",
490 list.iter().map(|a| a.key).collect::<Vec<_>>()
491 );
492 }
493
494 #[test]
497 fn the_offered_default_is_what_is_in_effect() {
498 let configured = Style {
499 gitmoji: Gitmoji::Prefix,
500 subject_max: 100,
501 ..Style::default()
502 };
503 let (_, list) = answers("\n\n\n\n\n", &configured).unwrap();
504 assert!(list.iter().all(|a| !a.changed));
505 assert_eq!(value(&list, KEY_GITMOJI).as_deref(), Some("prefix"));
507 assert_eq!(value(&list, KEY_SUBJECT_MAX).as_deref(), Some("100"));
508 }
509
510 #[test]
513 fn returning_to_the_default_unsets_rather_than_pins() {
514 let configured = Style {
515 subject_max: 100,
516 ..Style::default()
517 };
518 let (_, list) = answers("\nnone\n72\n\n\n", &configured).unwrap();
519 let subject = list
520 .iter()
521 .find(|a| a.key == KEY_SUBJECT_MAX)
522 .expect("asked");
523 assert!(subject.changed);
524 assert!(subject.value.is_none(), "should unset, not write 72");
525 }
526
527 #[test]
529 fn an_unusable_answer_is_asked_again() {
530 let (_, list) = answers(
531 "sideways\nglobal\nnope\nsuffix\nlots\n80\n\n\n",
532 &Style::default(),
533 )
534 .unwrap();
535 assert_eq!(value(&list, KEY_GITMOJI).as_deref(), Some("suffix"));
536 assert_eq!(value(&list, KEY_SUBJECT_MAX).as_deref(), Some("80"));
537 }
538
539 #[test]
541 fn quitting_midway_discards_the_answers_already_given() {
542 assert!(answers("global\nsuffix\nq\n", &Style::default()).is_none());
543 assert!(answers("global\nsuffix\n", &Style::default()).is_none());
545 }
546}