Debian Codegraph @

src/de.rs

raw
1 // SPDX-License-Identifier: Apache-2.0 OR MIT
2
3 //! Cargo configuration that environment variables, config overrides, and
4 //! target-specific configurations have not been resolved.
5
6 #[path = "gen/de.rs"]
7 mod generated;
8
9 use alloc::{
10 borrow::{Cow, ToOwned as _},
11 collections::BTreeMap,
12 format,
13 string::String,
14 vec,
15 vec::Vec,
16 };
17 use core::{fmt, iter, slice, str::FromStr};
18 use std::{
19 ffi::OsStr,
20 fs,
21 path::{Path, PathBuf},
22 };
23
24 use serde::{
25 de::{self, Deserialize, Deserializer},
26 ser::{Serialize, Serializer},
27 };
28 use serde_derive::{Deserialize, Serialize};
29
30 pub use crate::value::{Definition, Value};
31 use crate::{
32 easy,
33 error::{Context as _, Error, Result},
34 merge::Merge,
35 resolve::{ResolveContext, TargetTripleRef},
36 value::SetPath,
37 walk,
38 };
39
40 /// Cargo configuration that environment variables, config overrides, and
41 /// target-specific configurations have not been resolved.
42 #[derive(Debug, Clone, Default, Serialize, Deserialize)]
43 #[serde(rename_all = "kebab-case")]
44 #[non_exhaustive]
45 pub struct Config {
46 // TODO: paths
47 /// The `[alias]` table.
48 ///
49 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#alias)
50 #[serde(default)]
51 #[serde(skip_serializing_if = "BTreeMap::is_empty")]
52 pub alias: BTreeMap<String, StringList>,
53 /// The `[build]` table.
54 ///
55 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#build)
56 #[serde(default)]
57 #[serde(skip_serializing_if = "BuildConfig::is_none")]
58 pub build: BuildConfig,
59 /// The `[credential-alias]` table.
60 ///
61 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#credential-alias)
62 #[serde(default)]
63 #[serde(skip_serializing_if = "BTreeMap::is_empty")]
64 pub credential_alias: BTreeMap<String, PathAndArgs>,
65 /// The `[doc]` table.
66 ///
67 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#doc)
68 #[serde(default)]
69 #[serde(skip_serializing_if = "DocConfig::is_none")]
70 pub doc: DocConfig,
71 /// The `[env]` table.
72 ///
73 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#env)
74 #[serde(default)]
75 #[serde(skip_serializing_if = "BTreeMap::is_empty")]
76 pub env: BTreeMap<String, EnvConfigValue>,
77 /// The `[future-incompat-report]` table.
78 ///
79 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#future-incompat-report)
80 #[serde(default)]
81 #[serde(skip_serializing_if = "FutureIncompatReportConfig::is_none")]
82 pub future_incompat_report: FutureIncompatReportConfig,
83 /// The `[cargo-new]` table.
84 ///
85 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#cargo-new)
86 #[serde(default)]
87 #[serde(skip_serializing_if = "CargoNewConfig::is_none")]
88 pub cargo_new: CargoNewConfig,
89 /// The `[http]` table.
90 ///
91 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#http)
92 #[serde(default)]
93 #[serde(skip_serializing_if = "HttpConfig::is_none")]
94 pub http: HttpConfig,
95 // TODO: install
96 /// The `[net]` table.
97 ///
98 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#net)
99 #[serde(default)]
100 #[serde(skip_serializing_if = "NetConfig::is_none")]
101 pub net: NetConfig,
102 // TODO: patch
103 // TODO: profile
104 /// The `[registries]` table.
105 ///
106 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#registries)
107 #[serde(default)]
108 #[serde(skip_serializing_if = "BTreeMap::is_empty")]
109 pub registries: BTreeMap<String, RegistriesConfigValue>,
110 /// The `[registry]` table.
111 ///
112 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#registry)
113 #[serde(default)]
114 #[serde(skip_serializing_if = "RegistryConfig::is_none")]
115 pub registry: RegistryConfig,
116 /// The `[source]` table.
117 ///
118 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#source)
119 #[serde(default)]
120 #[serde(skip_serializing_if = "BTreeMap::is_empty")]
121 pub source: BTreeMap<String, SourceConfigValue>,
122 /// The `[target]` table.
123 ///
124 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#target)
125 #[serde(default)]
126 #[serde(skip_serializing_if = "BTreeMap::is_empty")]
127 pub target: BTreeMap<String, TargetConfig>,
128 /// The `[term]` table.
129 ///
130 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#term)
131 #[serde(default)]
132 #[serde(skip_serializing_if = "TermConfig::is_none")]
133 pub term: TermConfig,
134 }
135
136 impl Config {
137 /// Reads config files hierarchically from the current directory and merges them.
138 pub fn load() -> Result<Self> {
139 Self::load_with_cwd(std::env::current_dir().context("failed to get current directory")?)
140 }
141
142 /// Reads config files hierarchically from the given directory and merges them.
143 pub fn load_with_cwd<P: AsRef<Path>>(cwd: P) -> Result<Self> {
144 let cwd = cwd.as_ref();
145 Self::_load_with_options(cwd, walk::cargo_home_with_cwd(cwd).as_deref())
146 }
147
148 /// Reads config files hierarchically from the given directory and merges them.
149 pub fn load_with_options<P: AsRef<Path>, Q: Into<Option<PathBuf>>>(
150 cwd: P,
151 cargo_home: Q,
152 ) -> Result<Self> {
153 Self::_load_with_options(cwd.as_ref(), cargo_home.into().as_deref())
154 }
155 pub(crate) fn _load_with_options(
156 current_dir: &Path,
157 cargo_home: Option<&Path>,
158 ) -> Result<Config> {
159 let mut base = None;
160 for path in crate::walk::WalkInner::with_cargo_home(current_dir, cargo_home) {
161 let config = Self::_load_file(&path)?;
162 match &mut base {
163 None => base = Some((path, config)),
164 Some((base_path, base)) => base.merge(config, false).with_context(|| {
165 format!(
166 "failed to merge config from `{}` into `{}`",
167 path.display(),
168 base_path.display()
169 )
170 })?,
171 }
172 }
173 Ok(base.map(|(_, c)| c).unwrap_or_default())
174 }
175
176 /// Reads cargo config file at the given path.
177 ///
178 /// **Note:** Note: This just reads a file at the given path and does not
179 /// respect the hierarchical structure of the cargo config.
180 pub fn load_file<P: AsRef<Path>>(path: P) -> Result<Self> {
181 Self::_load_file(path.as_ref())
182 }
183 fn _load_file(path: &Path) -> Result<Self> {
184 let buf = fs::read_to_string(path)
185 .with_context(|| format!("failed to read `{}`", path.display()))?;
186 let mut config: Config = toml::de::from_str(&buf).with_context(|| {
187 format!("failed to parse `{}` as cargo configuration", path.display())
188 })?;
189 config.set_path(path);
190 Ok(config)
191 }
192
193 /// Merges the given config into this config.
194 ///
195 /// If `force` is `false`, this matches the way cargo [merges configs in the
196 /// parent directories](https://doc.rust-lang.org/nightly/cargo/reference/config.html#hierarchical-structure).
197 ///
198 /// If `force` is `true`, this matches the way cargo's `--config` CLI option
199 /// overrides config.
200 pub(crate) fn merge(&mut self, low: Self, force: bool) -> Result<()> {
201 crate::merge::Merge::merge(self, low, force)
202 }
203
204 pub(crate) fn set_path(&mut self, path: &Path) {
205 crate::value::SetPath::set_path(self, path);
206 }
207
208 #[allow(clippy::ref_option)]
209 pub(crate) fn resolve_target(
210 cx: &ResolveContext,
211 target_configs: &BTreeMap<String, TargetConfig>,
212 override_target_rustflags: bool,
213 build_rustflags: &Option<Flags>,
214 override_target_rustdocflags: bool,
215 build_rustdocflags: &Option<Flags>,
216 target_triple: &TargetTripleRef<'_>,
217 build_config: &easy::BuildConfig,
218 ) -> Result<Option<TargetConfig>> {
219 let target = target_triple.triple();
220 if target.starts_with("cfg(") {
221 bail!("'{target}' is not valid target triple");
222 }
223 let mut target_config = None;
224
225 if let Some(config) = target_configs.get(target) {
226 target_config = Some(TargetConfig {
227 linker: config.linker.clone(),
228 runner: config.runner.clone(),
229 rustflags: config.rustflags.clone(),
230 rustdocflags: config.rustdocflags.clone(),
231 rest: BTreeMap::new(), // skip cloning rest
232 });
233 } else if let Some((before, rest)) = target.split_once('.') {
234 if let Some(config) = target_configs.get(before) {
235 let mut rest_target_configs = &config.rest;
236 let mut rest_target = rest;
237 loop {
238 if let Some(config) = rest_target_configs.get(rest_target) {
239 if let TargetConfigRestValue::Config(config) = config {
240 target_config = Some(TargetConfig {
241 linker: config.linker.clone(),
242 runner: config.runner.clone(),
243 rustflags: config.rustflags.clone(),
244 rustdocflags: config.rustdocflags.clone(),
245 rest: BTreeMap::new(), // skip cloning rest
246 });
247 }
248 break;
249 }
250 if let Some((before, rest)) = rest_target.split_once('.') {
251 if let Some(TargetConfigRestValue::Config(config)) =
252 rest_target_configs.get(before)
253 {
254 rest_target_configs = &config.rest;
255 rest_target = rest;
256 continue;
257 }
258 }
259 break;
260 }
261 }
262 }
263
264 let target_u_upper = target_u_upper(target);
265 let mut target_linker = target_config.as_mut().and_then(|c| c.linker.take());
266 let mut target_runner = target_config.as_mut().and_then(|c| c.runner.take());
267 let mut target_rustflags: Option<Flags> =
268 target_config.as_mut().and_then(|c| c.rustflags.take());
269 let mut target_rustdocflags: Option<Flags> =
270 target_config.as_mut().and_then(|c| c.rustdocflags.take());
271 if let Some(linker) = cx.env_dyn(&format!("CARGO_TARGET_{target_u_upper}_LINKER"))? {
272 target_linker = Some(linker);
273 }
274 if let Some(runner) = cx.env_dyn(&format!("CARGO_TARGET_{target_u_upper}_RUNNER"))? {
275 target_runner = Some(
276 PathAndArgs::from_string(&runner.val, runner.definition.as_ref())
277 .context("invalid length 0, expected at least one element")?,
278 );
279 }
280 if let Some(rustflags) = cx.env_dyn(&format!("CARGO_TARGET_{target_u_upper}_RUSTFLAGS"))? {
281 let mut rustflags =
282 Flags::from_space_separated(&rustflags.val, rustflags.definition.as_ref());
283 match &mut target_rustflags {
284 Some(target_rustflags) => {
285 target_rustflags.flags.append(&mut rustflags.flags);
286 }
287 target_rustflags @ None => *target_rustflags = Some(rustflags),
288 }
289 }
290 if let Some(rustdocflags) =
291 cx.env_dyn(&format!("CARGO_TARGET_{target_u_upper}_RUSTDOCFLAGS"))?
292 {
293 let mut rustdocflags =
294 Flags::from_space_separated(&rustdocflags.val, rustdocflags.definition.as_ref());
295 match &mut target_rustdocflags {
296 Some(target_rustdocflags) => {
297 target_rustdocflags.flags.append(&mut rustdocflags.flags);
298 }
299 target_rustdocflags @ None => *target_rustdocflags = Some(rustdocflags),
300 }
301 }
302 for (k, v) in target_configs {
303 if !k.starts_with("cfg(") {
304 continue;
305 }
306 if cx.eval_cfg(k, target_triple, build_config)? {
307 // https://github.com/rust-lang/cargo/pull/12535
308 if target_linker.is_none() {
309 if let Some(linker) = v.linker.as_ref() {
310 target_linker = Some(linker.clone());
311 }
312 }
313 // Priorities (as of 1.68.0-nightly (2022-12-23)):
314 // 1. CARGO_TARGET_<triple>_RUNNER
315 // 2. target.<triple>.runner
316 // 3. target.<cfg>.runner
317 if target_runner.is_none() {
318 if let Some(runner) = v.runner.as_ref() {
319 target_runner = Some(runner.clone());
320 }
321 }
322 // Applied order (as of 1.68.0-nightly (2022-12-23)):
323 // 1. target.<triple>.rustflags
324 // 2. CARGO_TARGET_<triple>_RUSTFLAGS
325 // 3. target.<cfg>.rustflags
326 if let Some(rustflags) = v.rustflags.as_ref() {
327 match &mut target_rustflags {
328 Some(target_rustflags) => {
329 target_rustflags.flags.extend_from_slice(&rustflags.flags);
330 }
331 target_rustflags @ None => *target_rustflags = Some(rustflags.clone()),
332 }
333 }
334 // Applied order (as of 1.97.1):
335 // 1. target.<triple>.rustdocflags
336 // 2. CARGO_TARGET_<triple>_RUSTDOCFLAGS
337 // 3. target.<cfg>.rustdocflags
338 if let Some(rustdocflags) = v.rustdocflags.as_ref() {
339 match &mut target_rustdocflags {
340 Some(target_rustdocflags) => {
341 target_rustdocflags.flags.extend_from_slice(&rustdocflags.flags);
342 }
343 target_rustdocflags @ None => {
344 *target_rustdocflags = Some(rustdocflags.clone());
345 }
346 }
347 }
348 }
349 }
350
351 // Empty target flags do not override build flags, per cargo's behavior as of Rust 1.97.1.
352 target_rustflags = target_rustflags.filter(|rustflags| !rustflags.flags.is_empty());
353 target_rustdocflags =
354 target_rustdocflags.filter(|rustdocflags| !rustdocflags.flags.is_empty());
355
356 if let Some(linker) = target_linker {
357 target_config.get_or_insert_with(TargetConfig::default).linker = Some(linker);
358 }
359 if let Some(runner) = target_runner {
360 target_config.get_or_insert_with(TargetConfig::default).runner = Some(runner);
361 }
362 if override_target_rustflags {
363 target_config
364 .get_or_insert_with(TargetConfig::default)
365 .rustflags
366 .clone_from(build_rustflags);
367 } else if let Some(rustflags) = target_rustflags {
368 target_config.get_or_insert_with(TargetConfig::default).rustflags = Some(rustflags);
369 } else {
370 target_config
371 .get_or_insert_with(TargetConfig::default)
372 .rustflags
373 .clone_from(build_rustflags);
374 }
375 if override_target_rustdocflags {
376 target_config
377 .get_or_insert_with(TargetConfig::default)
378 .rustdocflags
379 .clone_from(build_rustdocflags);
380 } else if let Some(rustdocflags) = target_rustdocflags {
381 target_config.get_or_insert_with(TargetConfig::default).rustdocflags =
382 Some(rustdocflags);
383 } else {
384 target_config
385 .get_or_insert_with(TargetConfig::default)
386 .rustdocflags
387 .clone_from(build_rustdocflags);
388 }
389 Ok(target_config)
390 }
391 }
392
393 /// The `[build]` table.
394 ///
395 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#build)
396 #[derive(Debug, Clone, Default, Serialize, Deserialize)]
397 #[serde(rename_all = "kebab-case")]
398 #[non_exhaustive]
399 pub struct BuildConfig {
400 /// Sets the maximum number of compiler processes to run in parallel.
401 /// If negative, it sets the maximum number of compiler processes to the
402 /// number of logical CPUs plus provided value. Should not be 0.
403 ///
404 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#buildjobs)
405 #[serde(skip_serializing_if = "Option::is_none")]
406 pub jobs: Option<Value<i32>>,
407 /// Sets the executable to use for `rustc`.
408 ///
409 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#buildrustc)
410 #[serde(skip_serializing_if = "Option::is_none")]
411 pub rustc: Option<Value<String>>,
412 /// Sets a wrapper to execute instead of `rustc`.
413 ///
414 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#buildrustc-wrapper)
415 #[serde(skip_serializing_if = "Option::is_none")]
416 pub rustc_wrapper: Option<Value<String>>,
417 /// Sets a wrapper to execute instead of `rustc`, for workspace members only.
418 ///
419 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#buildrustc-workspace-wrapper)
420 #[serde(skip_serializing_if = "Option::is_none")]
421 pub rustc_workspace_wrapper: Option<Value<String>>,
422 /// Sets the executable to use for `rustdoc`.
423 ///
424 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#buildrustdoc)
425 #[serde(skip_serializing_if = "Option::is_none")]
426 pub rustdoc: Option<Value<String>>,
427 /// The default target platform triples to compile to.
428 ///
429 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#buildtarget)
430 #[serde(skip_serializing_if = "Option::is_none")]
431 pub target: Option<StringOrArray>,
432 /// The path to where all compiler output is placed. The default if not
433 /// specified is a directory named target located at the root of the workspace.
434 ///
435 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#buildtarget)
436 #[serde(skip_serializing_if = "Option::is_none")]
437 pub target_dir: Option<Value<String>>,
438 /// The path to where all compiler intermediate artifacts are placed. The default if not
439 /// specified is the value of build.target-dir
440 ///
441 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#build-dir)
442 #[serde(skip_serializing_if = "Option::is_none")]
443 pub build_dir: Option<Value<String>>,
444 /// Extra command-line flags to pass to rustc. The value may be an array
445 /// of strings or a space-separated string.
446 ///
447 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#buildrustflags)
448 #[serde(skip_serializing_if = "Option::is_none")]
449 pub rustflags: Option<Flags>,
450 /// Extra command-line flags to pass to `rustdoc`. The value may be an array
451 /// of strings or a space-separated string.
452 ///
453 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#buildrustdocflags)
454 #[serde(skip_serializing_if = "Option::is_none")]
455 pub rustdocflags: Option<Flags>,
456 /// Whether or not to perform incremental compilation.
457 ///
458 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#buildincremental)
459 #[serde(skip_serializing_if = "Option::is_none")]
460 pub incremental: Option<Value<bool>>,
461 /// Strips the given path prefix from dep info file paths.
462 ///
463 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#builddep-info-basedir)
464 #[serde(skip_serializing_if = "Option::is_none")]
465 pub dep_info_basedir: Option<Value<String>>,
466
467 // Resolve contexts. Completely ignored in serialization and deserialization.
468 #[serde(skip)]
469 pub(crate) override_target_rustflags: bool,
470 #[serde(skip)]
471 pub(crate) override_target_rustdocflags: bool,
472 }
473
474 // https://github.com/rust-lang/cargo/blob/0.80.0/src/cargo/util/context/target.rs
475 /// A `[target.<triple>]` or `[target.<cfg>]` table.
476 ///
477 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#target)
478 #[derive(Debug, Clone, Default, Serialize, Deserialize)]
479 #[serde(rename_all = "kebab-case")]
480 #[non_exhaustive]
481 pub struct TargetConfig {
482 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#targettriplelinker)
483 #[serde(skip_serializing_if = "Option::is_none")]
484 pub linker: Option<Value<String>>,
485 /// [reference (`target.<triple>.runner`)](https://doc.rust-lang.org/nightly/cargo/reference/config.html#targettriplerunner)
486 ///
487 /// [reference (`target.<cfg>.runner`)](https://doc.rust-lang.org/nightly/cargo/reference/config.html#targetcfgrunner)
488 #[serde(skip_serializing_if = "Option::is_none")]
489 pub runner: Option<PathAndArgs>,
490 /// [reference (`target.<triple>.rustflags`)](https://doc.rust-lang.org/nightly/cargo/reference/config.html#targettriplerustflags)
491 ///
492 /// [reference (`target.<cfg>.rustflags`)](https://doc.rust-lang.org/nightly/cargo/reference/config.html#targetcfgrustflags)
493 #[serde(skip_serializing_if = "Option::is_none")]
494 pub rustflags: Option<Flags>,
495 /// [reference (`target.<triple>.rustdocflags`)](https://doc.rust-lang.org/nightly/cargo/reference/config.html#targettriplerustdocflags)
496 ///
497 /// [reference (`target.<cfg>.rustdocflags`)](https://doc.rust-lang.org/nightly/cargo/reference/config.html#targetcfgrustdocflags)
498 #[serde(skip_serializing_if = "Option::is_none")]
499 pub rustdocflags: Option<Flags>,
500 // TODO: links: https://doc.rust-lang.org/nightly/cargo/reference/config.html#targettriplelinks
501 #[serde(flatten)]
502 pub(crate) rest: BTreeMap<String, TargetConfigRestValue>,
503 }
504
505 #[derive(Debug, Clone, Serialize, Deserialize)]
506 #[serde(untagged)]
507 pub(crate) enum TargetConfigRestValue {
508 Config(TargetConfig),
509 Other(toml::Value),
510 }
511
512 impl Merge for TargetConfigRestValue {
513 fn merge(&mut self, low: Self, force: bool) -> Result<()> {
514 match (self, low) {
515 (Self::Config(this), Self::Config(low)) => this.merge(low, force),
516 (this @ Self::Other(_), low @ Self::Config(_)) => {
517 *this = low;
518 Ok(())
519 }
520 (_, Self::Other(_)) => Ok(()),
521 }
522 }
523 }
524 impl SetPath for TargetConfigRestValue {
525 fn set_path(&mut self, path: &Path) {
526 match self {
527 Self::Config(v) => {
528 v.set_path(path);
529 }
530 Self::Other(_) => {}
531 }
532 }
533 }
534
535 /// The `[doc]` table.
536 ///
537 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#doc)
538 #[derive(Debug, Clone, Default, Serialize, Deserialize)]
539 #[serde(rename_all = "kebab-case")]
540 #[non_exhaustive]
541 pub struct DocConfig {
542 /// This option sets the browser to be used by `cargo doc`, overriding the
543 /// `BROWSER` environment variable when opening documentation with the `--open` option.
544 ///
545 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#docbrowser)
546 #[serde(skip_serializing_if = "Option::is_none")]
547 pub browser: Option<PathAndArgs>,
548 }
549
550 // TODO: hide internal repr, change to struct
551 /// A value of the `[env]` table.
552 ///
553 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#env)
554 #[derive(Debug, Clone, Serialize, Deserialize)]
555 #[serde(untagged)]
556 #[non_exhaustive]
557 pub enum EnvConfigValue {
558 Value(Value<String>),
559 Table {
560 value: Value<String>,
561 #[serde(skip_serializing_if = "Option::is_none")]
562 force: Option<Value<bool>>,
563 #[serde(skip_serializing_if = "Option::is_none")]
564 relative: Option<Value<bool>>,
565 },
566 }
567
568 impl EnvConfigValue {
569 pub(crate) const fn kind(&self) -> &'static str {
570 match self {
571 Self::Value(..) => "string",
572 Self::Table { .. } => "table",
573 }
574 }
575
576 pub(crate) fn resolve(&self, current_dir: &Path) -> Cow<'_, OsStr> {
577 match self {
578 Self::Value(v) => OsStr::new(&v.val).into(),
579 Self::Table { value, relative, .. } => {
580 if relative.as_ref().is_some_and(|v| v.val) {
581 if let Some(def) = &value.definition {
582 return def.root(current_dir).join(&value.val).into_os_string().into();
583 }
584 }
585 OsStr::new(&value.val).into()
586 }
587 }
588 }
589 }
590
591 /// The `[future-incompat-report]` table.
592 ///
593 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#future-incompat-report)
594 #[derive(Debug, Clone, Default, Serialize, Deserialize)]
595 #[serde(rename_all = "kebab-case")]
596 #[non_exhaustive]
597 pub struct FutureIncompatReportConfig {
598 /// Controls how often we display a notification to the terminal when a future incompat report is available.
599 ///
600 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#future-incompat-reportfrequency)
601 #[serde(skip_serializing_if = "Option::is_none")]
602 pub frequency: Option<Value<Frequency>>,
603 }
604
605 /// The `[cargo-new]` table.
606 ///
607 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#cargo-new)
608 #[derive(Debug, Clone, Default, Serialize, Deserialize)]
609 #[serde(rename_all = "kebab-case")]
610 #[non_exhaustive]
611 pub struct CargoNewConfig {
612 /// Specifies the source control system to use for initializing a new repository.
613 /// Valid values are git, hg (for Mercurial), pijul, fossil or none to disable this behavior.
614 /// Defaults to git, or none if already inside a VCS repository. Can be overridden with the --vcs CLI option.
615 #[serde(skip_serializing_if = "Option::is_none")]
616 pub vcs: Option<Value<VersionControlSoftware>>,
617 }
618
619 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
620 #[serde(rename_all = "kebab-case")]
621 #[non_exhaustive]
622 pub enum VersionControlSoftware {
623 /// Git
624 Git,
625 /// Mercurial
626 #[serde(rename = "hg")]
627 Mercurial,
628 /// Pijul
629 Pijul,
630 /// Fossil
631 Fossil,
632 /// No VCS
633 None,
634 }
635
636 impl VersionControlSoftware {
637 pub const fn as_str(self) -> &'static str {
638 match self {
639 VersionControlSoftware::Git => "git",
640 VersionControlSoftware::Mercurial => "hg",
641 VersionControlSoftware::Pijul => "pijul",
642 VersionControlSoftware::Fossil => "fossil",
643 VersionControlSoftware::None => "none",
644 }
645 }
646 }
647
648 impl FromStr for VersionControlSoftware {
649 type Err = Error;
650
651 fn from_str(vcs: &str) -> Result<Self, Self::Err> {
652 match vcs {
653 "git" => Ok(Self::Git),
654 "hg" => Ok(Self::Mercurial),
655 "pijul" => Ok(Self::Pijul),
656 "fossil" => Ok(Self::Fossil),
657 "none" => Ok(Self::None),
658 other => bail!("must be git, hg, pijul, fossil, none, but found `{other}`"),
659 }
660 }
661 }
662
663 /// The `[http]` table.
664 ///
665 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#http)
666 #[derive(Debug, Clone, Default, Serialize, Deserialize)]
667 #[serde(rename_all = "kebab-case")]
668 #[non_exhaustive]
669 pub struct HttpConfig {
670 /// If true, enables debugging of HTTP requests.
671 /// The debug information can be seen by setting the `CARGO_LOG=network=debug` environment variable
672 /// (or use `network=trace` for even more information).
673 ///
674 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#httpdebug)
675 #[serde(skip_serializing_if = "Option::is_none")]
676 pub debug: Option<Value<bool>>,
677 /// Sets an HTTP and HTTPS proxy to use. The format is in libcurl format as in `[protocol://]host[:port]`.
678 /// If not set, Cargo will also check the http.proxy setting in your global git configuration.
679 /// If none of those are set, the HTTPS_PROXY or https_proxy environment variables set the proxy for HTTPS requests,
680 /// and http_proxy sets it for HTTP requests.
681 ///
682 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#httpproxy)
683 #[serde(skip_serializing_if = "Option::is_none")]
684 pub proxy: Option<Value<String>>,
685 /// Sets the timeout for each HTTP request, in seconds.
686 ///
687 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#httptimeout)
688 #[serde(skip_serializing_if = "Option::is_none")]
689 pub timeout: Option<Value<u32>>,
690 /// Path to a Certificate Authority (CA) bundle file, used to verify TLS certificates.
691 /// If not specified, Cargo attempts to use the system certificates.
692 ///
693 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#httpcainfo)
694 #[serde(skip_serializing_if = "Option::is_none")]
695 pub cainfo: Option<Value<String>>,
696 /// This determines whether or not TLS certificate revocation checks should be performed.
697 /// This only works on Windows.
698 ///
699 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#httpcheck-revoke)
700 #[serde(skip_serializing_if = "Option::is_none")]
701 pub check_revoke: Option<Value<bool>>,
702 // TODO: handle ssl-version
703 /// This setting controls timeout behavior for slow connections.
704 /// If the average transfer speed in bytes per second is below the given value
705 /// for `http.timeout` seconds (default 30 seconds), then the connection is considered too slow and Cargo will abort and retry.
706 ///
707 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#httplow-speed-limit)
708 #[serde(skip_serializing_if = "Option::is_none")]
709 pub low_speed_limit: Option<Value<u32>>,
710 /// When true, Cargo will attempt to use the HTTP2 protocol with multiplexing.
711 /// This allows multiple requests to use the same connection, usually improving performance when fetching multiple files.
712 /// If false, Cargo will use HTTP 1.1 without pipelining.
713 ///
714 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#httpmultiplexing)
715 #[serde(skip_serializing_if = "Option::is_none")]
716 pub multiplexing: Option<Value<bool>>,
717 /// Specifies a custom user-agent header to use.
718 /// The default if not specified is a string that includes Cargo's version.
719 ///
720 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#httpuser-agent)
721 #[serde(skip_serializing_if = "Option::is_none")]
722 pub user_agent: Option<Value<String>>,
723 }
724
725 /// The `[net]` table.
726 ///
727 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#net)
728 #[derive(Debug, Clone, Default, Serialize, Deserialize)]
729 #[serde(rename_all = "kebab-case")]
730 #[non_exhaustive]
731 pub struct NetConfig {
732 /// Number of times to retry possibly spurious network errors.
733 ///
734 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#netretry)
735 #[serde(skip_serializing_if = "Option::is_none")]
736 pub retry: Option<Value<u32>>,
737 /// If this is `true`, then Cargo will use the `git` executable to fetch
738 /// registry indexes and git dependencies. If `false`, then it uses a
739 /// built-in `git` library.
740 ///
741 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#netgit-fetch-with-cli)
742 #[serde(skip_serializing_if = "Option::is_none")]
743 pub git_fetch_with_cli: Option<Value<bool>>,
744 /// If this is `true`, then Cargo will avoid accessing the network, and
745 /// attempt to proceed with locally cached data. If `false`, Cargo will
746 /// access the network as needed, and generate an error if it encounters a
747 /// network error.
748 ///
749 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#netoffline)
750 #[serde(skip_serializing_if = "Option::is_none")]
751 pub offline: Option<Value<bool>>,
752 }
753
754 /// A value of the `[registries]` table.
755 ///
756 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#registries)
757 #[derive(Clone, Default, Serialize, Deserialize)]
758 #[serde(rename_all = "kebab-case")]
759 #[non_exhaustive]
760 pub struct RegistriesConfigValue {
761 /// Specifies the URL of the git index for the registry.
762 ///
763 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#registriesnameindex)
764 #[serde(skip_serializing_if = "Option::is_none")]
765 pub index: Option<Value<String>>,
766 /// Specifies the authentication token for the given registry.
767 ///
768 /// Note: This library does not read any values in the
769 /// [credentials](https://doc.rust-lang.org/nightly/cargo/reference/config.html#credentials)
770 /// file.
771 ///
772 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#registriesnametoken)
773 #[serde(skip_serializing_if = "Option::is_none")]
774 pub token: Option<Value<String>>,
775 /// Specifies the credential provider for the given registry.
776 ///
777 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#registriesnamecredential-provider)
778 #[serde(skip_serializing_if = "Option::is_none")]
779 pub credential_provider: Option<CredentialProvider>,
780 /// Specifies the protocol used to access crates.io.
781 /// Not allowed for any registries besides crates.io.
782 ///
783 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#registriescrates-ioprotocol)
784 #[serde(skip_serializing_if = "Option::is_none")]
785 pub protocol: Option<Value<RegistriesProtocol>>,
786 }
787
788 impl fmt::Debug for RegistriesConfigValue {
789 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
790 let Self { index, credential_provider, token, protocol } = self;
791 let redacted_token = token
792 .as_ref()
793 .map(|token| Value { val: "[REDACTED]", definition: token.definition.clone() });
794 f.debug_struct("RegistriesConfigValue")
795 .field("index", &index)
796 .field("token", &redacted_token)
797 .field("credential_provider", credential_provider)
798 .field("protocol", &protocol)
799 .finish()
800 }
801 }
802
803 /// Specifies the protocol used to access crates.io.
804 ///
805 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#registriescrates-ioprotocol)
806 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
807 #[serde(rename_all = "kebab-case")]
808 #[non_exhaustive]
809 pub enum RegistriesProtocol {
810 /// Causes Cargo to clone the entire index of all packages ever published to
811 /// [crates.io](https://crates.io/) from <https://github.com/rust-lang/crates.io-index/>.
812 Git,
813 /// A newer protocol which uses HTTPS to download only what is necessary from
814 /// <https://index.crates.io/>.
815 Sparse,
816 }
817
818 impl FromStr for RegistriesProtocol {
819 type Err = Error;
820
821 fn from_str(protocol: &str) -> Result<Self, Self::Err> {
822 match protocol {
823 "git" => Ok(Self::Git),
824 "sparse" => Ok(Self::Sparse),
825 other => bail!("must be git or sparse, but found `{other}`"),
826 }
827 }
828 }
829
830 /// The `[registry]` table.
831 ///
832 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#registry)
833 #[derive(Clone, Default, Serialize, Deserialize)]
834 #[serde(rename_all = "kebab-case")]
835 #[non_exhaustive]
836 pub struct RegistryConfig {
837 /// The name of the registry (from the
838 /// [`registries` table](https://doc.rust-lang.org/nightly/cargo/reference/config.html#registries))
839 /// to use by default for registry commands like
840 /// [`cargo publish`](https://doc.rust-lang.org/nightly/cargo/commands/cargo-publish.html).
841 ///
842 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#registrydefault)
843 #[serde(skip_serializing_if = "Option::is_none")]
844 pub default: Option<Value<String>>,
845 /// Specifies the credential provider for crates.io. If not set, the providers in
846 /// [`registry.global-credential-providers`]((https://doc.rust-lang.org/nightly/cargo/reference/config.html#registryglobal-credential-providers))
847 /// will be used.
848 ///
849 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#registrycredential-provider)
850 #[serde(skip_serializing_if = "Option::is_none")]
851 pub credential_provider: Option<CredentialProvider>,
852 /// Specifies the authentication token for [crates.io](https://crates.io/).
853 ///
854 /// Note: This library does not read any values in the
855 /// [credentials](https://doc.rust-lang.org/nightly/cargo/reference/config.html#credentials)
856 /// file.
857 ///
858 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#registrytoken)
859 #[serde(skip_serializing_if = "Option::is_none")]
860 pub token: Option<Value<String>>,
861 /// Specifies the list of global credential providers.
862 /// If credential provider is not set for a specific registry using
863 /// [`registries.<name>.credential-provider`](https://doc.rust-lang.org/nightly/cargo/reference/config.html#registriesnamecredential-provider),
864 /// Cargo will use the credential providers in this list.
865 /// Providers toward the end of the list have precedence.
866 ///
867 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#registryglobal-credential-providers)
868 #[serde(default)]
869 #[serde(skip_serializing_if = "GlobalCredentialProviders::is_none")]
870 pub global_credential_providers: GlobalCredentialProviders,
871 }
872
873 impl fmt::Debug for RegistryConfig {
874 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
875 let Self { default, credential_provider, token, global_credential_providers } = self;
876 let redacted_token = token
877 .as_ref()
878 .map(|token| Value { val: "[REDACTED]", definition: token.definition.clone() });
879 f.debug_struct("RegistryConfig")
880 .field("default", &default)
881 .field("credential_provider", credential_provider)
882 .field("token", &redacted_token)
883 .field("global_credential_providers", global_credential_providers)
884 .finish()
885 }
886 }
887
888 /// A value of the `[source]` table.
889 ///
890 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#source)
891 #[derive(Clone, Default, Debug, Serialize, Deserialize)]
892 #[serde(rename_all = "kebab-case")]
893 #[non_exhaustive]
894 pub struct SourceConfigValue {
895 /// If set, replace this source with the given named source or named registry.
896 ///
897 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#sourcenamereplace-with)
898 #[serde(skip_serializing_if = "Option::is_none")]
899 pub replace_with: Option<Value<String>>,
900 /// Sets the path to a directory to use as a directory source.
901 ///
902 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#sourcenamedirectory)
903 #[serde(skip_serializing_if = "Option::is_none")]
904 pub directory: Option<Value<String>>,
905 /// Sets the URL to use for a registry source.
906 ///
907 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#sourcenameregistry)
908 #[serde(skip_serializing_if = "Option::is_none")]
909 pub registry: Option<Value<String>>,
910 /// Sets the path to a directory to use as a local registry source.
911 ///
912 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#sourcenamelocal-registry)
913 #[serde(skip_serializing_if = "Option::is_none")]
914 pub local_registry: Option<Value<String>>,
915 /// Sets the URL to use for a git source.
916 ///
917 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#sourcenamegit)
918 #[serde(skip_serializing_if = "Option::is_none")]
919 pub git: Option<Value<String>>,
920 /// Sets the branch name to use for a git repository.
921 /// If none of branch, tag, or rev is set, defaults to the master branch.
922 ///
923 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#sourcenamebranch)
924 #[serde(skip_serializing_if = "Option::is_none")]
925 pub branch: Option<Value<String>>,
926 /// Sets the tag name to use for a git repository.
927 /// If none of branch, tag, or rev is set, defaults to the master branch.
928 ///
929 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#sourcenametag)
930 #[serde(skip_serializing_if = "Option::is_none")]
931 pub tag: Option<Value<String>>,
932 /// Sets the revision to use for a git repository.
933 /// If none of branch, tag, or rev is set, defaults to the master branch.
934 ///
935 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#sourcenamerev)
936 #[serde(skip_serializing_if = "Option::is_none")]
937 pub rev: Option<Value<String>>,
938 }
939
940 /// Global credential providers.
941 ///
942 /// [Cargo Reference](https://doc.rust-lang.org/cargo/reference/config.html#registryglobal-credential-providers)
943 #[derive(Clone, Debug, Default)]
944 pub struct GlobalCredentialProviders(pub(crate) Vec<CredentialProvider>);
945
946 impl GlobalCredentialProviders {
947 pub(crate) fn is_none(&self) -> bool {
948 self.0.is_empty()
949 }
950 }
951
952 impl GlobalCredentialProviders {
953 pub(crate) fn from_list<T>(
954 list: impl IntoIterator<Item = T>,
955 definition: Option<&Definition>,
956 ) -> Result<Self, Error>
957 where
958 T: AsRef<str>,
959 {
960 Ok(Self(
961 list.into_iter()
962 .map(|v| CredentialProvider::from_string(v.as_ref(), definition))
963 .collect::<Result<_, _>>()?,
964 ))
965 }
966 }
967
968 impl AsRef<[CredentialProvider]> for GlobalCredentialProviders {
969 fn as_ref(&self) -> &[CredentialProvider] {
970 &self.0
971 }
972 }
973
974 impl Serialize for GlobalCredentialProviders {
975 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
976 where
977 S: Serializer,
978 {
979 self.0.serialize(serializer)
980 }
981 }
982
983 impl<'de> Deserialize<'de> for GlobalCredentialProviders {
984 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
985 where
986 D: Deserializer<'de>,
987 {
988 // TODO: use visitor?
989 Ok(Self(
990 <Vec<String>>::deserialize(deserializer)?
991 .iter()
992 .map(|s| CredentialProvider::from_string(s, None))
993 .collect::<Result<_, _>>()
994 .map_err(de::Error::custom)?,
995 ))
996 }
997 }
998
999 /// A registry's credential provider.
1000 ///
1001 /// [Cargo Reference](https://doc.rust-lang.org/cargo/reference/registry-authentication.html)
1002 #[derive(Clone, Debug)]
1003 pub struct CredentialProvider {
1004 pub kind: CredentialProviderKind,
1005 deserialized_repr: StringListDeserializedRepr,
1006 }
1007
1008 /// The kind of a registry's credential provider.
1009 #[derive(Clone, Debug)]
1010 #[non_exhaustive]
1011 pub enum CredentialProviderKind {
1012 /// Uses Cargo's credentials file to store tokens unencrypted in plain text.
1013 ///
1014 /// [Cargo Reference](https://doc.rust-lang.org/cargo/reference/registry-authentication.html#cargotoken)
1015 CargoToken,
1016 /// Uses the Windows Credential Manager to store tokens.
1017 ///
1018 /// [Cargo Reference](https://doc.rust-lang.org/cargo/reference/registry-authentication.html#cargowincred)
1019 CargoWincred,
1020 /// Uses the macOS Keychain to store tokens.
1021 ///
1022 /// [Cargo Reference](https://doc.rust-lang.org/cargo/reference/registry-authentication.html#cargomacos-keychain)
1023 CargoMacosKeychain,
1024 /// Uses libsecret to store tokens.
1025 ///
1026 /// [Cargo Reference](https://doc.rust-lang.org/cargo/reference/registry-authentication.html#cargolibsecret)
1027 CargoLibsecret,
1028 /// Launch a subprocess that returns a token on stdout. Newlines will be trimmed.
1029 ///
1030 /// [Cargo Reference](https://doc.rust-lang.org/cargo/reference/registry-authentication.html#cargotoken-from-stdout-command-args)
1031 CargoTokenFromStdout(PathAndArgs),
1032 /// For credential provider plugins that follow Cargo's credential provider protocol,
1033 /// the configuration value should be a string with the path to the executable (or the executable name if on the PATH).
1034 ///
1035 /// [Cargo Reference](https://doc.rust-lang.org/cargo/reference/registry-authentication.html#credential-plugins)
1036 Plugin(PathAndArgs),
1037 /// Maybe an alias, otherwise a plugin command.
1038 MaybeAlias(Value<String>),
1039 }
1040
1041 impl CredentialProvider {
1042 pub(crate) fn from_string(value: &str, definition: Option<&Definition>) -> Result<Self, Error> {
1043 Ok(Self {
1044 kind: CredentialProviderKind::from_list(
1045 split_space_separated(value)
1046 .map(|v| Value { val: v.to_owned(), definition: definition.cloned() }),
1047 StringListDeserializedRepr::String,
1048 )?,
1049 deserialized_repr: StringListDeserializedRepr::String,
1050 })
1051 }
1052
1053 pub(crate) fn from_array(list: Vec<Value<String>>) -> Result<Self, Error> {
1054 Ok(Self {
1055 kind: CredentialProviderKind::from_list(list, StringListDeserializedRepr::Array)?,
1056 deserialized_repr: StringListDeserializedRepr::Array,
1057 })
1058 }
1059 }
1060
1061 impl SetPath for CredentialProviderKind {
1062 fn set_path(&mut self, path: &Path) {
1063 match self {
1064 Self::CargoToken
1065 | Self::CargoWincred
1066 | Self::CargoMacosKeychain
1067 | Self::CargoLibsecret => {}
1068 Self::CargoTokenFromStdout(command) | Self::Plugin(command) => command.set_path(path),
1069 Self::MaybeAlias(s) => s.set_path(path),
1070 }
1071 }
1072 }
1073
1074 impl Serialize for CredentialProvider {
1075 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1076 where
1077 S: Serializer,
1078 {
1079 match self.deserialized_repr {
1080 StringListDeserializedRepr::String => {
1081 let mut s = String::new();
1082
1083 let command = match &self.kind {
1084 CredentialProviderKind::CargoToken => {
1085 return "cargo:token".serialize(serializer);
1086 }
1087 CredentialProviderKind::CargoWincred => {
1088 return "cargo:wincred".serialize(serializer);
1089 }
1090 CredentialProviderKind::CargoMacosKeychain => {
1091 return "cargo:macos-keychain".serialize(serializer);
1092 }
1093 CredentialProviderKind::CargoLibsecret => {
1094 return "cargo:libsecret".serialize(serializer);
1095 }
1096 CredentialProviderKind::CargoTokenFromStdout(command) => {
1097 s.push_str("cargo:token-from-stdout ");
1098
1099 command
1100 }
1101 CredentialProviderKind::Plugin(command) => command,
1102 CredentialProviderKind::MaybeAlias(value) => {
1103 return value.serialize(serializer);
1104 }
1105 };
1106
1107 command.serialize_to_string(&mut s);
1108
1109 s.serialize(serializer)
1110 }
1111 StringListDeserializedRepr::Array => {
1112 let mut array = vec![];
1113
1114 let command = match &self.kind {
1115 CredentialProviderKind::CargoToken => {
1116 return ["cargo:token"].serialize(serializer);
1117 }
1118 CredentialProviderKind::CargoWincred => {
1119 return ["cargo:wincred"].serialize(serializer);
1120 }
1121 CredentialProviderKind::CargoMacosKeychain => {
1122 return ["cargo:macos-keychain"].serialize(serializer);
1123 }
1124 CredentialProviderKind::CargoLibsecret => {
1125 return ["cargo:libsecret"].serialize(serializer);
1126 }
1127 CredentialProviderKind::CargoTokenFromStdout(command) => {
1128 array.push("cargo:token-from-stdout");
1129
1130 command
1131 }
1132 CredentialProviderKind::Plugin(command) => command,
1133 CredentialProviderKind::MaybeAlias(value) => {
1134 return [value].serialize(serializer);
1135 }
1136 };
1137
1138 command.serialize_to_array(&mut array);
1139
1140 array.serialize(serializer)
1141 }
1142 }
1143 }
1144 }
1145
1146 impl<'de> Deserialize<'de> for CredentialProvider {
1147 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1148 where
1149 D: Deserializer<'de>,
1150 {
1151 // TODO: use visitor?
1152 match StringOrArray::deserialize(deserializer)? {
1153 StringOrArray::String(s) => Self::from_string(&s.val, s.definition.as_ref()),
1154 StringOrArray::Array(v) => Self::from_array(v),
1155 }
1156 .map_err(de::Error::custom)
1157 }
1158 }
1159
1160 impl CredentialProviderKind {
1161 fn from_list<T>(list: T, deserialized_repr: StringListDeserializedRepr) -> Result<Self, Error>
1162 where
1163 T: IntoIterator<Item = Value<String>>,
1164 {
1165 let mut iter = list.into_iter().peekable();
1166 let first = iter
1167 .next()
1168 .ok_or_else(|| format_err!("invalid length 0, expected at least one element"))?;
1169
1170 let empty_args = |kind: Self, mut iter: iter::Peekable<T::IntoIter>| {
1171 if iter.next().is_some() {
1172 bail!(
1173 "args should be empty for credential provider of kind {:?}",
1174 kind.builtin_kind().unwrap(),
1175 );
1176 }
1177
1178 Ok(kind)
1179 };
1180
1181 match &*first.val {
1182 "cargo:token" => empty_args(Self::CargoToken, iter),
1183 "cargo:wincred" => empty_args(Self::CargoWincred, iter),
1184 "cargo:macos-keychain" => empty_args(Self::CargoMacosKeychain, iter),
1185 "cargo:libsecret" => empty_args(Self::CargoLibsecret, iter),
1186 "cargo:token-from-stdout" => {
1187 let command = PathAndArgs::from_list(
1188 iter,
1189 deserialized_repr,
1190 ).ok_or_else(|| format_err!(r#"invalid length 1, expected at least two elements for registry of kind "cargo:token-from-stdout""#))?;
1191
1192 Ok(Self::CargoTokenFromStdout(command))
1193 }
1194 _ if iter.peek().is_none() => Ok(Self::MaybeAlias(first)),
1195 _ => Ok(Self::Plugin(
1196 PathAndArgs::from_list(iter::once(first).chain(iter), deserialized_repr).unwrap(),
1197 )),
1198 }
1199 }
1200
1201 fn builtin_kind(&self) -> Option<&'static str> {
1202 Some(match self {
1203 Self::CargoToken => "cargo:token",
1204 Self::CargoWincred => "cargo:wincred",
1205 Self::CargoMacosKeychain => "cargo:macos-keychain",
1206 Self::CargoLibsecret => "cargo:libsecret",
1207 Self::CargoTokenFromStdout(_) => "cargo:token-from-stdout",
1208 Self::Plugin(_) | Self::MaybeAlias(_) => return None,
1209 })
1210 }
1211 }
1212
1213 /// The `[term]` table.
1214 ///
1215 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#term)
1216 #[derive(Debug, Clone, Default, Serialize, Deserialize)]
1217 #[serde(rename_all = "kebab-case")]
1218 #[non_exhaustive]
1219 pub struct TermConfig {
1220 /// Controls whether or not log messages are displayed by Cargo.
1221 ///
1222 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#termquiet)
1223 #[serde(skip_serializing_if = "Option::is_none")]
1224 pub quiet: Option<Value<bool>>,
1225 /// Controls whether or not extra detailed messages are displayed by Cargo.
1226 ///
1227 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#termverbose)
1228 #[serde(skip_serializing_if = "Option::is_none")]
1229 pub verbose: Option<Value<bool>>,
1230 /// Controls whether or not colored output is used in the terminal.
1231 ///
1232 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#termcolor)
1233 #[serde(skip_serializing_if = "Option::is_none")]
1234 pub color: Option<Value<Color>>,
1235 #[serde(default)]
1236 #[serde(skip_serializing_if = "TermProgress::is_none")]
1237 pub progress: TermProgress,
1238 }
1239
1240 #[derive(Debug, Clone, Default, Serialize, Deserialize)]
1241 #[serde(rename_all = "kebab-case")]
1242 #[non_exhaustive]
1243 pub struct TermProgress {
1244 /// Controls whether or not progress bar is shown in the terminal.
1245 ///
1246 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#termprogresswhen)
1247 #[serde(skip_serializing_if = "Option::is_none")]
1248 pub when: Option<Value<When>>,
1249 /// Sets the width for progress bar.
1250 ///
1251 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#termprogresswidth)
1252 #[serde(skip_serializing_if = "Option::is_none")]
1253 pub width: Option<Value<u32>>,
1254 }
1255
1256 #[allow(clippy::exhaustive_enums)]
1257 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1258 #[serde(rename_all = "kebab-case")]
1259 pub enum Color {
1260 /// (default) Automatically detect if color support is available on the terminal.
1261 #[default]
1262 Auto,
1263 /// Always display colors.
1264 Always,
1265 /// Never display colors.
1266 Never,
1267 }
1268
1269 impl Color {
1270 pub const fn as_str(self) -> &'static str {
1271 match self {
1272 Self::Auto => "auto",
1273 Self::Always => "always",
1274 Self::Never => "never",
1275 }
1276 }
1277 }
1278
1279 impl FromStr for Color {
1280 type Err = Error;
1281
1282 fn from_str(color: &str) -> Result<Self, Self::Err> {
1283 match color {
1284 "auto" => Ok(Self::Auto),
1285 "always" => Ok(Self::Always),
1286 "never" => Ok(Self::Never),
1287 other => bail!("must be auto, always, or never, but found `{other}`"),
1288 }
1289 }
1290 }
1291
1292 #[allow(clippy::exhaustive_enums)]
1293 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1294 #[serde(rename_all = "kebab-case")]
1295 pub enum When {
1296 /// (default) Intelligently guess whether to show progress bar.
1297 #[default]
1298 Auto,
1299 /// Always show progress bar.
1300 Always,
1301 /// Never show progress bar.
1302 Never,
1303 }
1304
1305 impl When {
1306 pub const fn as_str(self) -> &'static str {
1307 match self {
1308 Self::Auto => "auto",
1309 Self::Always => "always",
1310 Self::Never => "never",
1311 }
1312 }
1313 }
1314
1315 impl FromStr for When {
1316 type Err = Error;
1317
1318 fn from_str(color: &str) -> Result<Self, Self::Err> {
1319 match color {
1320 "auto" => Ok(Self::Auto),
1321 "always" => Ok(Self::Always),
1322 "never" => Ok(Self::Never),
1323 other => bail!("must be auto, always, or never, but found `{other}`"),
1324 }
1325 }
1326 }
1327
1328 #[allow(clippy::exhaustive_enums)]
1329 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1330 #[serde(rename_all = "kebab-case")]
1331 pub enum Frequency {
1332 /// (default) Always display a notification when a command (e.g. `cargo build`)
1333 /// produces a future incompat report.
1334 #[default]
1335 Always,
1336 /// Never display a notification.
1337 Never,
1338 }
1339
1340 impl Frequency {
1341 pub const fn as_str(self) -> &'static str {
1342 match self {
1343 Self::Always => "always",
1344 Self::Never => "never",
1345 }
1346 }
1347 }
1348
1349 impl FromStr for Frequency {
1350 type Err = Error;
1351
1352 fn from_str(color: &str) -> Result<Self, Self::Err> {
1353 match color {
1354 "always" => Ok(Self::Always),
1355 "never" => Ok(Self::Never),
1356 other => bail!("must be always or never, but found `{other}`"),
1357 }
1358 }
1359 }
1360
1361 /// A representation of rustflags and rustdocflags.
1362 #[derive(Debug, Clone, Serialize)]
1363 #[serde(transparent)]
1364 pub struct Flags {
1365 pub flags: Vec<Value<String>>,
1366 // for merge
1367 #[serde(skip)]
1368 pub(crate) deserialized_repr: StringListDeserializedRepr,
1369 }
1370
1371 impl Flags {
1372 /// Creates a rustflags from a string separated with ASCII unit separator ('\x1f').
1373 ///
1374 /// This is a valid format for the following environment variables:
1375 ///
1376 /// - `CARGO_ENCODED_RUSTFLAGS` (Cargo 1.55+)
1377 /// - `CARGO_ENCODED_RUSTDOCFLAGS` (Cargo 1.55+)
1378 ///
1379 /// See also `encode`.
1380 pub(crate) fn from_encoded(s: &Value<String>) -> Self {
1381 Self {
1382 flags: split_encoded(&s.val)
1383 .map(|v| Value { val: v.to_owned(), definition: s.definition.clone() })
1384 .collect(),
1385 // Encoded rustflags cannot be serialized as a string because they may contain spaces.
1386 deserialized_repr: StringListDeserializedRepr::Array,
1387 }
1388 }
1389
1390 /// Creates a rustflags from a string separated with space (' ').
1391 ///
1392 /// This is a valid format for the following environment variables:
1393 ///
1394 /// - `RUSTFLAGS`
1395 /// - `CARGO_TARGET_<triple>_RUSTFLAGS`
1396 /// - `CARGO_BUILD_RUSTFLAGS`
1397 /// - `RUSTDOCFLAGS`
1398 /// - `CARGO_TARGET_<triple>_RUSTDOCFLAGS`
1399 /// - `CARGO_BUILD_RUSTDOCFLAGS`
1400 ///
1401 /// And the following configs:
1402 ///
1403 /// - `target.<triple>.rustflags`
1404 /// - `target.<cfg>.rustflags`
1405 /// - `build.rustflags`
1406 /// - `target.<triple>.rustdocflags` (Cargo 1.78+)
1407 /// - `target.<cfg>.rustdocflags` (Cargo 1.96+)
1408 /// - `build.rustdocflags`
1409 ///
1410 /// See also `encode_space_separated`.
1411 pub(crate) fn from_space_separated(s: &str, def: Option<&Definition>) -> Self {
1412 Self {
1413 flags: split_space_separated(s)
1414 .map(|v| Value { val: v.to_owned(), definition: def.cloned() })
1415 .collect(),
1416 deserialized_repr: StringListDeserializedRepr::String,
1417 }
1418 }
1419
1420 pub(crate) fn from_array(flags: Vec<Value<String>>) -> Self {
1421 Self { flags, deserialized_repr: StringListDeserializedRepr::Array }
1422 }
1423 }
1424
1425 impl<'de> Deserialize<'de> for Flags {
1426 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1427 where
1428 D: Deserializer<'de>,
1429 {
1430 // TODO: use visitor?
1431 let v: StringOrArray = Deserialize::deserialize(deserializer)?;
1432 match v {
1433 StringOrArray::String(s) => {
1434 Ok(Self::from_space_separated(&s.val, s.definition.as_ref()))
1435 }
1436 StringOrArray::Array(v) => Ok(Self::from_array(v)),
1437 }
1438 }
1439 }
1440
1441 // https://github.com/rust-lang/cargo/blob/0.80.0/src/cargo/util/context/path.rs
1442 #[derive(Debug, Deserialize, PartialEq, Clone)]
1443 #[serde(transparent)]
1444 pub struct ConfigRelativePath(pub(crate) Value<String>);
1445
1446 impl ConfigRelativePath {
1447 /// Returns the underlying value.
1448 pub fn value(&self) -> &Value<String> {
1449 &self.0
1450 }
1451
1452 /// Returns the raw underlying configuration value for this key.
1453 pub fn raw_value(&self) -> &str {
1454 &self.0.val
1455 }
1456
1457 // /// Resolves this configuration-relative path to an absolute path.
1458 // ///
1459 // /// This will always return an absolute path where it's relative to the
1460 // /// location for configuration for this value.
1461 // pub(crate) fn resolve_path(&self, current_dir: &Path) -> Cow<'_, Path> {
1462 // self.0.resolve_as_path(current_dir)
1463 // }
1464
1465 /// Resolves this configuration-relative path to either an absolute path or
1466 /// something appropriate to execute from `PATH`.
1467 ///
1468 /// Values which don't look like a filesystem path (don't contain `/` or
1469 /// `\`) will be returned as-is, and everything else will fall through to an
1470 /// absolute path.
1471 pub(crate) fn resolve_program(&self, current_dir: &Path) -> Cow<'_, Path> {
1472 self.0.resolve_as_program_path(current_dir)
1473 }
1474 }
1475
1476 /// An executable path with arguments.
1477 ///
1478 /// [Cargo Reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#executable-paths-with-arguments)
1479 #[derive(Debug, Clone)]
1480 #[non_exhaustive]
1481 pub struct PathAndArgs {
1482 pub path: ConfigRelativePath,
1483 pub args: Vec<Value<String>>,
1484
1485 // for merge
1486 pub(crate) deserialized_repr: StringListDeserializedRepr,
1487 }
1488
1489 impl PathAndArgs {
1490 pub(crate) fn from_string(value: &str, definition: Option<&Definition>) -> Option<Self> {
1491 Self::from_list(
1492 split_space_separated(value)
1493 .map(|v| Value { val: v.to_owned(), definition: definition.cloned() }),
1494 StringListDeserializedRepr::String,
1495 )
1496 }
1497
1498 pub(crate) fn from_array(list: Vec<Value<String>>) -> Option<Self> {
1499 Self::from_list(list, StringListDeserializedRepr::Array)
1500 }
1501
1502 fn from_list(
1503 list: impl IntoIterator<Item = Value<String>>,
1504 deserialized_repr: StringListDeserializedRepr,
1505 ) -> Option<Self> {
1506 let mut iter = list.into_iter();
1507
1508 Some(Self {
1509 path: ConfigRelativePath(iter.next()?),
1510 args: iter.collect(),
1511 deserialized_repr,
1512 })
1513 }
1514
1515 fn serialize_to_string(&self, s: &mut String) {
1516 s.push_str(self.path.raw_value());
1517
1518 for arg in &self.args {
1519 s.push(' ');
1520 s.push_str(&arg.val);
1521 }
1522 }
1523
1524 fn array_len(&self) -> usize {
1525 1 + self.args.len()
1526 }
1527
1528 fn serialize_to_array<'a>(&'a self, v: &mut Vec<&'a str>) {
1529 v.push(self.path.raw_value());
1530
1531 for arg in &self.args {
1532 v.push(&arg.val);
1533 }
1534 }
1535 }
1536
1537 impl Serialize for PathAndArgs {
1538 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1539 where
1540 S: Serializer,
1541 {
1542 match self.deserialized_repr {
1543 StringListDeserializedRepr::String => {
1544 let mut s = String::new();
1545
1546 self.serialize_to_string(&mut s);
1547 s.serialize(serializer)
1548 }
1549 StringListDeserializedRepr::Array => {
1550 let mut v = Vec::with_capacity(self.array_len());
1551
1552 self.serialize_to_array(&mut v);
1553 v.serialize(serializer)
1554 }
1555 }
1556 }
1557 }
1558 impl<'de> Deserialize<'de> for PathAndArgs {
1559 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1560 where
1561 D: Deserializer<'de>,
1562 {
1563 // TODO: use visitor?
1564 match StringOrArray::deserialize(deserializer)? {
1565 StringOrArray::String(s) => Self::from_string(&s.val, s.definition.as_ref()),
1566 StringOrArray::Array(v) => Self::from_array(v),
1567 }
1568 .ok_or_else(|| de::Error::invalid_length(0, &"at least one element"))
1569 }
1570 }
1571
1572 #[derive(Debug, Clone)]
1573 #[non_exhaustive]
1574 pub struct StringList {
1575 pub list: Vec<Value<String>>,
1576
1577 // for merge
1578 pub(crate) deserialized_repr: StringListDeserializedRepr,
1579 }
1580
1581 impl Default for StringList {
1582 fn default() -> Self {
1583 Self { list: vec![], deserialized_repr: StringListDeserializedRepr::Array }
1584 }
1585 }
1586
1587 #[derive(Debug, Clone, Copy, PartialEq)]
1588 pub(crate) enum StringListDeserializedRepr {
1589 String,
1590 Array,
1591 }
1592 impl StringListDeserializedRepr {
1593 pub(crate) const fn as_str(self) -> &'static str {
1594 match self {
1595 Self::String => "string",
1596 Self::Array => "array",
1597 }
1598 }
1599 }
1600
1601 impl StringList {
1602 pub(crate) fn from_string(value: &str, definition: Option<&Definition>) -> Self {
1603 Self {
1604 list: split_space_separated(value)
1605 .map(|v| Value { val: v.to_owned(), definition: definition.cloned() })
1606 .collect(),
1607 deserialized_repr: StringListDeserializedRepr::String,
1608 }
1609 }
1610 pub(crate) fn from_array(list: Vec<Value<String>>) -> Self {
1611 Self { list, deserialized_repr: StringListDeserializedRepr::Array }
1612 }
1613 }
1614
1615 impl Serialize for StringList {
1616 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1617 where
1618 S: Serializer,
1619 {
1620 match self.deserialized_repr {
1621 StringListDeserializedRepr::String => {
1622 let mut s = String::with_capacity(
1623 self.list.len().saturating_sub(1)
1624 + self.list.iter().map(|v| v.val.len()).sum::<usize>(),
1625 );
1626 for arg in &self.list {
1627 if !s.is_empty() {
1628 s.push(' ');
1629 }
1630 s.push_str(&arg.val);
1631 }
1632 s.serialize(serializer)
1633 }
1634 StringListDeserializedRepr::Array => self.list.serialize(serializer),
1635 }
1636 }
1637 }
1638 impl<'de> Deserialize<'de> for StringList {
1639 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1640 where
1641 D: Deserializer<'de>,
1642 {
1643 // TODO: use visitor?
1644 let v: StringOrArray = Deserialize::deserialize(deserializer)?;
1645 match v {
1646 StringOrArray::String(s) => Ok(Self::from_string(&s.val, s.definition.as_ref())),
1647 StringOrArray::Array(v) => Ok(Self::from_array(v)),
1648 }
1649 }
1650 }
1651
1652 /// A string or array of strings.
1653 #[allow(clippy::exhaustive_enums)]
1654 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1655 #[serde(untagged)]
1656 pub enum StringOrArray {
1657 String(Value<String>),
1658 Array(Vec<Value<String>>),
1659 }
1660
1661 impl StringOrArray {
1662 pub(crate) const fn kind(&self) -> &'static str {
1663 match self {
1664 Self::String(..) => "string",
1665 Self::Array(..) => "array",
1666 }
1667 }
1668
1669 // pub(crate) fn string(&self) -> Option<&Value<String>> {
1670 // match self {
1671 // Self::String(s) => Some(s),
1672 // Self::Array(_) => None,
1673 // }
1674 // }
1675 // pub(crate) fn array(&self) -> Option<&[Value<String>]> {
1676 // match self {
1677 // Self::String(_) => None,
1678 // Self::Array(v) => Some(v),
1679 // }
1680 // }
1681 pub(crate) fn as_array_no_split(&self) -> &[Value<String>] {
1682 match self {
1683 Self::String(s) => slice::from_ref(s),
1684 Self::Array(v) => v,
1685 }
1686 }
1687 }
1688
1689 fn target_u_lower(target: &str) -> String {
1690 target.replace(['-', '.'], "_")
1691 }
1692 pub(crate) fn target_u_upper(target: &str) -> String {
1693 let mut target = target_u_lower(target);
1694 target.make_ascii_uppercase();
1695 target
1696 }
1697
1698 pub(crate) fn split_encoded(s: &str) -> impl Iterator<Item = &str> {
1699 // Cargo treats an entirely empty value as no flags,
1700 // but preserves empty components in a non-empty value:
1701 // https://github.com/rust-lang/cargo/blob/c980f4866141969fab6254a680546a277789d6f0/src/cargo/core/compiler/build_context/target_info.rs#L825-L833
1702 (!s.is_empty()).then(|| s.split('\x1f')).into_iter().flatten()
1703 }
1704 pub(crate) fn split_space_separated(s: &str) -> impl Iterator<Item = &str> {
1705 // TODO: tab/line?
1706 // https://github.com/rust-lang/cargo/blob/0.80.0/src/cargo/util/context/path.rs#L89
1707 s.split(' ').map(str::trim).filter(|s| !s.is_empty())
1708 }