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 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
255fn 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
286fn 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; }
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, ¤t.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
398fn 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 #[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 #[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 #[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 #[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 #[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 #[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 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 #[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 #[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 #[test]
542 fn quitting_midway_discards_the_answers_already_given() {
543 assert!(answers("global\nsuffix\nq\n", &Style::default()).is_none());
544 assert!(answers("global\nsuffix\n", &Style::default()).is_none());
546 }
547}