Debian Codegraph @

examples/get.rs

raw
1 // SPDX-License-Identifier: Apache-2.0 OR MIT
2
3 // Partial re-implementation of `cargo config get` using cargo-config2.
4
5 use std::{
6 env,
7 io::{self, BufWriter, Write as _},
8 str::FromStr,
9 };
10
11 use anyhow::{Result, bail};
12 use cargo_config2::de::Config;
13 use lexopt::{
14 Arg::{Long, Short},
15 ValueExt as _,
16 };
17
18 // TODO: --show-origin and --config
19 static USAGE:&str = "cargo-config2-get
20 Usage: cargo run --example get -- [OPTIONS]
21
22 Options:
23 --format <format> Display format [default: toml] [possible values: toml, json]
24 --merged <merged> Whether or not to merge config values [default: yes] [possible values: yes, no]
25 -h, --help Print help information
26 ";
27
28 fn main() {
29 if let Err(e) = try_main() {
30 eprintln!("error: {e:#}");
31 std::process::exit(1)
32 }
33 }
34
35 fn try_main() -> Result<()> {
36 let Some(args) = Args::parse()? else { return Ok(()) };
37
38 let mut stdout = BufWriter::new(io::stdout().lock()); // Buffered because it is written with newline many times.
39 match args.merged {
40 Merged::Yes => {
41 let config = Config::load()?;
42 print_config(&mut stdout, args.format, &config)?;
43 }
44 Merged::No => {
45 if args.format == Format::Json {
46 bail!(
47 "the `json` format does not support --merged=no, try the `toml` format instead"
48 );
49 }
50 for path in cargo_config2::Walk::new(&env::current_dir()?) {
51 let config = Config::load_file(&path)?;
52 writeln!(stdout, "# {}", path.display())?;
53 print_config(&mut stdout, args.format, &config)?;
54 writeln!(stdout)?;
55 }
56 }
57 }
58 stdout.flush()?;
59
60 // In toml format, `cargo config get` outputs this in the form of a comment,
61 // but may output toml in an invalid format because it does not handle newlines properly.
62 let mut stderr = BufWriter::new(io::stderr().lock()); // Buffered because it is written with newline many times.
63 writeln!(stderr, "note: The following environment variables may affect the loaded values.")?;
64 for (k, v) in env::vars_os() {
65 if let (Ok(k), Ok(v)) = (k.into_string(), v.into_string()) {
66 if k.starts_with("CARGO_") {
67 writeln!(stderr, "{k}={}", shell_escape::escape(v.into()))?;
68 }
69 }
70 }
71 stderr.flush()?;
72
73 Ok(())
74 }
75
76 fn print_config(writer: &mut dyn io::Write, format: Format, config: &Config) -> Result<()> {
77 match format {
78 Format::Json => writeln!(writer, "{}", serde_json::to_string(&config)?)?,
79 Format::Toml => {
80 // `cargo config get` displays config with the following format:
81 //
82 // ```
83 // a.b.c = <value>
84 // a.b.d = <value>
85 // ```
86 //
87 // Neither toml nor toml_edit supports this output format, so format it manually.
88 fn print_value(
89 writer: &mut dyn io::Write,
90 path: &str,
91 value: &toml::Value,
92 ) -> Result<()> {
93 match value {
94 toml::Value::Table(table) => {
95 for (key, item) in table {
96 print_value(writer, &format!("{path}.{key}"), item)?;
97 }
98 }
99 _ => writeln!(writer, "{path} = {value}")?,
100 }
101 Ok(())
102 }
103 let doc = toml::from_str::<toml::Value>(&toml::to_string(&config)?)?;
104 if let Some(table) = doc.as_table() {
105 for (key, value) in table {
106 print_value(writer, key, value)?;
107 }
108 }
109 }
110 }
111 Ok(())
112 }
113
114 struct Args {
115 format: Format,
116 merged: Merged,
117 }
118
119 #[derive(Clone, Copy, Default, PartialEq, Eq)]
120 enum Format {
121 #[default]
122 Toml,
123 Json,
124 }
125
126 impl FromStr for Format {
127 type Err = anyhow::Error;
128 fn from_str(s: &str) -> Result<Self, Self::Err> {
129 match s {
130 "toml" => Ok(Self::Toml),
131 "json" => Ok(Self::Json),
132 other => bail!("must be toml or json, but found `{other}`"),
133 }
134 }
135 }
136
137 #[derive(Clone, Copy, Default)]
138 enum Merged {
139 #[default]
140 Yes,
141 No,
142 }
143
144 impl FromStr for Merged {
145 type Err = anyhow::Error;
146 fn from_str(s: &str) -> Result<Self, Self::Err> {
147 match s {
148 "yes" => Ok(Self::Yes),
149 "no" => Ok(Self::No),
150 other => bail!("must be yes or no, but found `{other}`"),
151 }
152 }
153 }
154
155 impl Args {
156 fn parse() -> Result<Option<Self>> {
157 let mut format: Option<Format> = None;
158 let mut merged: Option<Merged> = None;
159
160 let mut parser = lexopt::Parser::from_env();
161 while let Some(arg) = parser.next()? {
162 match arg {
163 Long("format") if format.is_none() => format = Some(parser.value()?.parse()?),
164 Long("merged") if merged.is_none() => merged = Some(parser.value()?.parse()?),
165 Short('h') | Long("help") => {
166 print!("{USAGE}");
167 return Ok(None);
168 }
169 Short('V') | Long("version") => {
170 println!("{} {}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"));
171 return Ok(None);
172 }
173 _ => return Err(arg.unexpected().into()),
174 }
175 }
176
177 Ok(Some(Self { format: format.unwrap_or_default(), merged: merged.unwrap_or_default() }))
178 }
179 }