Debian Codegraph @

src/cli/config.rs

raw
1 //! Command-line parser for `sq config`.
2
3 use std::{
4 collections::BTreeMap,
5 ffi::OsStr,
6 path::PathBuf,
7 sync::OnceLock,
8 };
9
10 use clap::{
11 Parser,
12 Subcommand,
13 };
14 use clap_lex::OsStrExt;
15
16 use sequoia_directories::Home;
17
18 pub mod get;
19 pub mod inspect;
20 pub mod set;
21 pub mod template;
22
23 /// Computes the path to the config file even if argument parsing
24 /// failed.
25 ///
26 /// This happens notably if `--help` is given.
27 pub fn find_home() -> Option<Home> {
28 let args = std::env::args_os().collect::<Vec<_>>();
29
30 for (i, arg) in args.iter().enumerate() {
31 if arg == "--" {
32 break;
33 }
34
35 if arg.starts_with("--home=") {
36 return handle(arg.strip_prefix("--home="));
37 }
38
39 if arg == "--home" {
40 if let Some(home) = args.get(i + 1) {
41 return handle(Some(home.as_os_str()));
42 }
43 }
44 }
45
46 /// Handle the argument to `--home`.
47 fn handle(arg: Option<&OsStr>) -> Option<Home> {
48 if let Some(arg) = arg {
49 match arg.to_str() {
50 Some("default") => Home::default().cloned(),
51 Some("none") => None,
52 _ => Home::new(Some(PathBuf::from(arg))).ok(),
53 }
54 } else {
55 // No argument to `--home` is a syntax error.
56 None
57 }
58 }
59
60 // No `--home` argument, select the default, possibly overridden
61 // by SEQUOIA_HOME.
62 Home::new(None).ok()
63 }
64
65 /// Values read from the config file to be included in help messages.
66 pub type Augmentations = BTreeMap<&'static str, String>;
67
68 /// Includes values from the config file in help messages.
69 pub fn augment_help(key: &'static str, text: &str) -> String {
70 if let Some(a) = get_augmentation(key) {
71 format!("{}\n\
72 \n\
73 The default can be changed in the configuration \
74 file using the setting `{}`.
75 \n\
76 [config: {}] (overrides default)",
77 text.trim_end(), key, a)
78 } else {
79 format!("{}\n\
80 \n\
81 The default can be changed in the configuration \
82 file using the setting `{}`.",
83 text.trim_end(), key)
84 }
85 }
86
87 /// Returns the value of an augmentation, if any.
88 pub fn get_augmentation(key: &str) -> Option<&str> {
89 AUGMENTATIONS.get().and_then(|a| a.get(key).map(|v| v.as_str()))
90 }
91
92 /// Includes values from the config file in help messages.
93 pub fn set_augmentations(augmentations: Augmentations) {
94 AUGMENTATIONS.set(augmentations)
95 .expect("augmentations must only be set once");
96 }
97
98 /// Values read from the config file to be included in help messages.
99 static AUGMENTATIONS: OnceLock<Augmentations> = OnceLock::new();
100
101 #[derive(Debug, Parser)]
102 #[clap(
103 name = "config",
104 about = "Query, inspect, and create the configuration file",
105 long_about = format!("\
106 Query, inspect, and create the configuration file
107
108 This subcommand can be used to query and inspect the configuration \
109 file{}, and to create a template that can be edited to your liking.
110
111 Configuration file: {}
112 ",
113 sequoia_directories::Home::default()
114 .map(|home| {
115 let p = home.config_dir(sequoia_directories::Component::Sq);
116 let p = p.join("config.toml");
117 let p = p.display().to_string();
118 if let Some(home) = dirs::home_dir() {
119 let home = home.display().to_string();
120 if let Some(rest) = p.strip_prefix(&home) {
121 return format!(" (default location: $HOME{})",
122 rest);
123 }
124 }
125 format!(" (default location: {})", p)
126 })
127 .unwrap_or("".to_string()),
128 find_home()
129 .map(|home| {
130 let p = home.config_dir(sequoia_directories::Component::Sq);
131 let p = p.join("config.toml");
132 let p = p.display().to_string();
133 if let Some(home) = dirs::home_dir() {
134 let home = home.display().to_string();
135 if let Some(rest) = p.strip_prefix(&home) {
136 return format!("$HOME{}", rest);
137 }
138 }
139 p
140 })
141 .unwrap_or("".to_string())),
142 subcommand_required = true,
143 arg_required_else_help = true,
144 disable_help_subcommand = true,
145 )]
146 pub struct Command {
147 #[clap(subcommand)]
148 pub subcommand: Subcommands,
149 }
150
151 #[derive(Debug, Subcommand)]
152 #[non_exhaustive]
153 pub enum Subcommands {
154 Get(get::Command),
155 Inspect(inspect::Command),
156 Template(template::Command),
157 }