Skip to main content

cargo_util_config/
schema.rs

1//! Cargo configuration schemas.
2//!
3//! This module contains types that define the schema for various configuration
4//! sections found in Cargo configuration.
5//!
6//! These types are mostly used by [`ConfigReader::get`](super::ConfigReader::get)
7//! to deserialize configuration values from TOML files, environment variables,
8//! and CLI arguments.
9//!
10//! Schema types here should only contain data and simple accessor methods.
11//! Avoid depending on Cargo's `GlobalContext` directly.
12
13use cargo_util::collections::HashMap;
14use std::borrow::Cow;
15use std::ffi::OsStr;
16use std::str::FromStr;
17use std::{fmt, hash};
18
19use cargo_credential::Secret;
20use cargo_util::paths;
21use cargo_util_schemas::manifest::ProfileName;
22use serde::Deserialize;
23use serde::Serialize;
24use serde::de;
25use serde::de::Error;
26use serde_untagged::UntaggedEnumVisitor;
27
28use std::path::Path;
29use std::path::PathBuf;
30
31use anyhow::Result;
32
33use super::CRATES_IO_REGISTRY;
34use super::Definition;
35use super::OptValue;
36use super::Value;
37
38pub use cargo_util_schemas::manifest::TomlProfiles;
39
40/// Cargo's `.cargo/config.toml` file
41#[cfg(feature = "unstable-schema")]
42#[derive(Deserialize, Serialize, schemars::JsonSchema)]
43#[serde(rename_all = "kebab-case")]
44pub struct Config {
45    pub include: Option<Vec<IncludeConfig>>,
46
47    pub paths: Option<Vec<ConfigRootRelativePath>>,
48    pub target_applies_to_host: Option<bool>,
49
50    pub build: Option<CargoBuildConfig>,
51    pub cache: Option<CargoCacheConfig>,
52    pub cargo_new: Option<CargoNewConfig>,
53    pub credential_alias: Option<HashMap<String, PathAndArgs>>,
54    pub doc: Option<DocConfig>,
55    pub env: Option<EnvConfig>,
56    pub future_incompat_report: Option<CargoFutureIncompatConfig>,
57    pub http: Option<CargoHttpConfig>,
58    pub net: Option<CargoNetConfig>,
59    pub patch: Option<HashMap<String, HashMap<String, PatchDependency>>>,
60    pub path_bases: Option<HashMap<String, ConfigRootRelativePath>>,
61    pub profile: Option<TomlProfiles>,
62    pub registries: Option<HashMap<String, RegistryConfig>>,
63    pub registry: Option<GlobalRegistryConfig>,
64    pub resolver: Option<CargoResolverConfig>,
65    pub source: Option<HashMap<String, SourceConfigDef>>,
66    pub term: Option<TermConfig>,
67    #[schemars(with = "Option<cargo_util_schemas::schema::TomlValueWrapper>")]
68    pub unstable: Option<toml::Value>,
69}
70
71/// Cargo's `credentials.toml` file
72#[cfg(feature = "unstable-schema")]
73#[derive(Deserialize, Serialize, schemars::JsonSchema)]
74pub struct Credentials {
75    pub registry: Option<RegistryCredential>,
76    pub registries: Option<HashMap<String, RegistryCredential>>,
77}
78
79#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
80#[derive(Serialize)]
81#[serde(untagged)]
82pub enum IncludeConfig {
83    Simple(ConfigParentRelativePath),
84    Detailed(DetailedIncludeConfig),
85}
86
87impl<'de> Deserialize<'de> for IncludeConfig {
88    fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
89        // HACK: Workaround the serialization protocol for `ConfigParentRelativePath` / `Value` is
90        // a newtype, making it messier to use in `IncludeConfig::Simple`.
91        enum RawIncludeConfig {
92            Simple(String),
93            Detailed(DetailedIncludeConfig),
94        }
95
96        impl<'de> Deserialize<'de> for RawIncludeConfig {
97            fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
98                struct IncludeVisitor;
99
100                impl<'de> de::Visitor<'de> for IncludeVisitor {
101                    type Value = RawIncludeConfig;
102
103                    fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
104                        f.write_str("a config include path or table")
105                    }
106
107                    fn visit_str<E: de::Error>(self, path: &str) -> Result<Self::Value, E> {
108                        self.visit_string(path.to_owned())
109                    }
110
111                    fn visit_string<E: de::Error>(self, path: String) -> Result<Self::Value, E> {
112                        Ok(RawIncludeConfig::Simple(path))
113                    }
114
115                    fn visit_map<M: de::MapAccess<'de>>(
116                        self,
117                        map: M,
118                    ) -> Result<Self::Value, M::Error> {
119                        DetailedIncludeConfig::deserialize(de::value::MapAccessDeserializer::new(
120                            map,
121                        ))
122                        .map(RawIncludeConfig::Detailed)
123                    }
124                }
125
126                deserializer.deserialize_any(IncludeVisitor)
127            }
128        }
129
130        let Value { val, definition } = Value::<RawIncludeConfig>::deserialize(deserializer)?;
131        Ok(match val {
132            RawIncludeConfig::Simple(val) => {
133                Self::Simple(ConfigParentRelativePath::new(Value { val, definition }))
134            }
135            RawIncludeConfig::Detailed(include) => Self::Detailed(include),
136        })
137    }
138}
139
140impl IncludeConfig {
141    pub fn into_detailed(self) -> DetailedIncludeConfig {
142        match self {
143            Self::Simple(path) => DetailedIncludeConfig {
144                path,
145                optional: false,
146            },
147            Self::Detailed(include) => include,
148        }
149    }
150}
151
152/// Represents a config-include value in the configuration.
153#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
154#[derive(Deserialize, Serialize)]
155pub struct DetailedIncludeConfig {
156    pub path: ConfigParentRelativePath,
157    /// Whether this include is optional (missing files are silently ignored)
158    #[serde(default)]
159    pub optional: bool,
160}
161
162impl DetailedIncludeConfig {
163    /// Resolves the absolute path for this include.
164    ///
165    /// For file based include,
166    /// it is relative to parent directory of the config file includes it.
167    /// For example, if `.cargo/config.toml has a `include = "foo.toml"`,
168    /// Cargo will load `.cargo/foo.toml`.
169    ///
170    /// For CLI based include (e.g., `--config 'include = "foo.toml"'`),
171    /// it is relative to the current working directory.
172    ///
173    /// Returns `None` if this is an optional include and the file doesn't exist.
174    /// Otherwise returns `Some(PathBuf)` with the absolute path.
175    pub fn resolve_path(&self, current_dir: &Path) -> Option<PathBuf> {
176        let abs_path = self.path.resolve(current_dir);
177        let abs_path = paths::normalize_path(&abs_path);
178
179        if self.optional && !abs_path.exists() {
180            tracing::info!(
181                "skipping optional include `{}` in `{}`:  file not found at `{}`",
182                self.path,
183                self.path.definition(),
184                abs_path.display(),
185            );
186            None
187        } else {
188            Some(abs_path)
189        }
190    }
191}
192
193pub type PatchDependency = cargo_util_schemas::manifest::TomlDependency<ConfigRootRelativePath>;
194
195#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
196#[derive(Debug, Default, Deserialize, Serialize, PartialEq)]
197#[serde(rename_all = "kebab-case")]
198pub struct CargoCacheConfig {
199    /// How often to automatically clean unused cache data.
200    pub auto_clean_frequency: Option<String>,
201    /// Settings for cleaning the global cache.
202    pub global_clean: Option<GlobalCleanConfig>,
203}
204
205/// Cache cleaning settings from the `cache.global-clean` config table.
206///
207/// NOTE: Not all of these options may get stabilized. Some of them are very
208/// low-level details, and may not be something typical users need.
209///
210/// If any of these options are `None`, the built-in default is used.
211#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
212#[derive(Debug, Default, Deserialize, Serialize, PartialEq)]
213#[serde(rename_all = "kebab-case")]
214pub struct GlobalCleanConfig {
215    /// Anything older than this duration will be deleted in the source cache.
216    pub max_src_age: Option<String>,
217    /// Anything older than this duration will be deleted in the compressed crate cache.
218    pub max_crate_age: Option<String>,
219    /// Any index older than this duration will be deleted from the index cache.
220    pub max_index_age: Option<String>,
221    /// Any git checkout older than this duration will be deleted from the checkout cache.
222    pub max_git_co_age: Option<String>,
223    /// Any git clone older than this duration will be deleted from the git cache.
224    pub max_git_db_age: Option<String>,
225}
226
227#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
228#[derive(Deserialize, Serialize)]
229#[serde(rename_all = "kebab-case")]
230pub struct CargoNewConfig {
231    #[deprecated = "cargo-new no longer supports adding the authors field"]
232    name: Option<String>,
233
234    #[deprecated = "cargo-new no longer supports adding the authors field"]
235    email: Option<String>,
236
237    #[serde(rename = "vcs")]
238    pub version_control: Option<VersionControl>,
239}
240
241#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
242#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
243#[serde(rename_all = "lowercase")]
244pub enum VersionControl {
245    Git,
246    Hg,
247    Pijul,
248    Fossil,
249    #[serde(rename = "none")]
250    NoVcs,
251}
252
253impl VersionControl {
254    pub const VALUES: &[Self] = &[Self::Git, Self::Hg, Self::Pijul, Self::Fossil, Self::NoVcs];
255
256    pub fn as_str(&self) -> &'static str {
257        match self {
258            VersionControl::Git => "git",
259            VersionControl::Hg => "hg",
260            VersionControl::Pijul => "pijul",
261            VersionControl::Fossil => "fossil",
262            VersionControl::NoVcs => "none",
263        }
264    }
265}
266
267impl FromStr for VersionControl {
268    type Err = anyhow::Error;
269
270    fn from_str(s: &str) -> Result<Self, anyhow::Error> {
271        match s {
272            "git" => Ok(VersionControl::Git),
273            "hg" => Ok(VersionControl::Hg),
274            "pijul" => Ok(VersionControl::Pijul),
275            "fossil" => Ok(VersionControl::Fossil),
276            "none" => Ok(VersionControl::NoVcs),
277            other => anyhow::bail!("unknown vcs specification: `{}`", other),
278        }
279    }
280}
281
282impl<'de> de::Deserialize<'de> for VersionControl {
283    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
284    where
285        D: de::Deserializer<'de>,
286    {
287        let s = String::deserialize(deserializer)?;
288        FromStr::from_str(&s).map_err(de::Error::custom)
289    }
290}
291
292/// Definition of a source in a config file.
293#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
294#[derive(Debug, Deserialize, Serialize)]
295#[serde(rename_all = "kebab-case")]
296pub struct SourceConfigDef {
297    /// Indicates this source should be replaced with another of the given name.
298    pub replace_with: OptValue<String>,
299    /// A directory source.
300    pub directory: Option<ConfigRootRelativePath>,
301    /// A registry source. Value is a URL.
302    pub registry: OptValue<String>,
303    /// A local registry source.
304    pub local_registry: Option<ConfigRootRelativePath>,
305    /// A git source. Value is a URL.
306    pub git: OptValue<String>,
307    /// The git branch.
308    pub branch: OptValue<String>,
309    /// The git tag.
310    pub tag: OptValue<String>,
311    /// The git revision.
312    pub rev: OptValue<String>,
313}
314
315#[cfg(feature = "unstable-schema")]
316#[derive(Deserialize, Serialize, schemars::JsonSchema)]
317#[serde(rename_all = "kebab-case")]
318pub struct DocConfig {
319    pub browser: Option<PathAndArgs>,
320    pub extern_map: Option<RustdocExternMap>,
321}
322
323/// A map of registry names to URLs where documentations are hosted.
324/// This is for unstable feature [`-Zrustdoc-map`][1].
325///
326/// [1]: https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#rustdoc-map
327#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
328#[derive(Deserialize, Serialize, Debug)]
329#[serde(default)]
330pub struct RustdocExternMap {
331    #[serde(deserialize_with = "default_crates_io_to_docs_rs")]
332    /// * Key is the registry name in the configuration `[registries.<name>]`.
333    /// * Value is the URL where the documentation is hosted.
334    pub registries: HashMap<String, String>,
335    pub std: Option<RustdocExternMode>,
336}
337
338impl Default for RustdocExternMap {
339    fn default() -> Self {
340        Self {
341            registries: HashMap::from_iter([(CRATES_IO_REGISTRY.into(), DOCS_RS_URL.into())]),
342            std: None,
343        }
344    }
345}
346
347const DOCS_RS_URL: &'static str = "https://docs.rs/";
348
349fn default_crates_io_to_docs_rs<'de, D: serde::Deserializer<'de>>(
350    de: D,
351) -> Result<HashMap<String, String>, D::Error> {
352    let mut registries = HashMap::deserialize(de)?;
353    if !registries.contains_key(CRATES_IO_REGISTRY) {
354        registries.insert(CRATES_IO_REGISTRY.into(), DOCS_RS_URL.into());
355    }
356    Ok(registries)
357}
358
359impl hash::Hash for RustdocExternMap {
360    fn hash<H: hash::Hasher>(&self, into: &mut H) {
361        self.std.hash(into);
362        for (key, value) in &self.registries {
363            key.hash(into);
364            value.hash(into);
365        }
366    }
367}
368
369/// Mode used for `std`. This is for unstable feature [`-Zrustdoc-map`][1].
370///
371/// [1]: https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#rustdoc-map
372#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
373#[derive(Debug, Hash, Serialize)]
374#[serde(rename_all = "lowercase")]
375pub enum RustdocExternMode {
376    /// Use a local `file://` URL.
377    Local,
378    /// Use a remote URL to <https://doc.rust-lang.org/> (default).
379    Remote,
380    /// An arbitrary URL.
381    #[serde(untagged)]
382    Url(String),
383}
384
385impl From<String> for RustdocExternMode {
386    fn from(s: String) -> RustdocExternMode {
387        match s.as_ref() {
388            "local" => RustdocExternMode::Local,
389            "remote" => RustdocExternMode::Remote,
390            _ => RustdocExternMode::Url(s),
391        }
392    }
393}
394
395impl fmt::Display for RustdocExternMode {
396    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
397        match self {
398            RustdocExternMode::Local => "local".fmt(f),
399            RustdocExternMode::Remote => "remote".fmt(f),
400            RustdocExternMode::Url(s) => s.fmt(f),
401        }
402    }
403}
404
405impl<'de> serde::de::Deserialize<'de> for RustdocExternMode {
406    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
407    where
408        D: serde::de::Deserializer<'de>,
409    {
410        let s = String::deserialize(deserializer)?;
411        Ok(s.into())
412    }
413}
414
415/// The `[http]` table.
416///
417/// Example configuration:
418///
419/// ```toml
420/// [http]
421/// proxy = "host:port"
422/// timeout = 30
423/// cainfo = "/path/to/ca-bundle.crt"
424/// check-revoke = true
425/// multiplexing = true
426/// ssl-version = "tlsv1.3"
427/// ```
428#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
429#[derive(Debug, Default, Deserialize, Serialize, PartialEq)]
430#[serde(rename_all = "kebab-case")]
431pub struct CargoHttpConfig {
432    pub proxy: Option<String>,
433    pub low_speed_limit: Option<u32>,
434    pub timeout: Option<u64>,
435    pub cainfo: Option<ConfigRootRelativePath>,
436    pub proxy_cainfo: Option<ConfigRootRelativePath>,
437    pub check_revoke: Option<bool>,
438    pub user_agent: Option<String>,
439    pub debug: Option<bool>,
440    pub multiplexing: Option<bool>,
441    pub ssl_version: Option<SslVersionConfig>,
442}
443
444/// The `[future-incompat-report]` stable
445///
446/// Example configuration:
447///
448/// ```toml
449/// [future-incompat-report]
450/// frequency = "always"
451/// ```
452#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
453#[derive(Debug, Default, Deserialize, Serialize, PartialEq)]
454#[serde(rename_all = "kebab-case")]
455pub struct CargoFutureIncompatConfig {
456    frequency: Option<CargoFutureIncompatFrequencyConfig>,
457}
458
459#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
460#[derive(Debug, Default, Deserialize, Serialize, PartialEq)]
461#[serde(rename_all = "kebab-case")]
462pub enum CargoFutureIncompatFrequencyConfig {
463    #[default]
464    Always,
465    Never,
466}
467
468impl CargoFutureIncompatConfig {
469    pub fn should_display_message(&self) -> bool {
470        use CargoFutureIncompatFrequencyConfig::*;
471
472        let frequency = self.frequency.as_ref().unwrap_or(&Always);
473        match frequency {
474            Always => true,
475            Never => false,
476        }
477    }
478}
479
480/// Configuration for `ssl-version` in `http` section
481/// There are two ways to configure:
482///
483/// ```text
484/// [http]
485/// ssl-version = "tlsv1.3"
486/// ```
487///
488/// ```text
489/// [http]
490/// ssl-version.min = "tlsv1.2"
491/// ssl-version.max = "tlsv1.3"
492/// ```
493#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
494#[derive(Clone, Debug, PartialEq, Serialize)]
495#[serde(untagged)]
496pub enum SslVersionConfig {
497    Single(String),
498    Range(SslVersionConfigRange),
499}
500
501impl<'de> Deserialize<'de> for SslVersionConfig {
502    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
503    where
504        D: serde::Deserializer<'de>,
505    {
506        struct Visitor;
507
508        impl<'de> de::Visitor<'de> for Visitor {
509            type Value = SslVersionConfig;
510
511            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
512                f.write_str("a string or map")
513            }
514
515            fn visit_str<E: de::Error>(self, value: &str) -> Result<Self::Value, E> {
516                Ok(SslVersionConfig::Single(value.to_owned()))
517            }
518
519            fn visit_string<E: de::Error>(self, value: String) -> Result<Self::Value, E> {
520                Ok(SslVersionConfig::Single(value))
521            }
522
523            fn visit_map<M: de::MapAccess<'de>>(self, map: M) -> Result<Self::Value, M::Error> {
524                SslVersionConfigRange::deserialize(de::value::MapAccessDeserializer::new(map))
525                    .map(SslVersionConfig::Range)
526            }
527        }
528
529        deserializer.deserialize_any(Visitor)
530    }
531}
532
533#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
534#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
535#[serde(rename_all = "kebab-case")]
536pub struct SslVersionConfigRange {
537    pub min: Option<String>,
538    pub max: Option<String>,
539}
540
541/// The `[net]` table.
542///
543/// Example configuration:
544///
545/// ```toml
546/// [net]
547/// retry = 2
548/// offline = false
549/// git-fetch-with-cli = true
550/// ```
551#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
552#[derive(Debug, Deserialize, Serialize)]
553#[serde(rename_all = "kebab-case")]
554pub struct CargoNetConfig {
555    pub retry: Option<u32>,
556    pub offline: Option<bool>,
557    pub git_fetch_with_cli: Option<bool>,
558    pub ssh: Option<CargoSshConfig>,
559}
560
561#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
562#[derive(Debug, Deserialize, Serialize)]
563#[serde(rename_all = "kebab-case")]
564pub struct CargoSshConfig {
565    pub known_hosts: Option<Vec<Value<String>>>,
566}
567
568/// Configuration for `jobs` in `build` section. There are two
569/// ways to configure: An integer or a simple string expression.
570///
571/// ```toml
572/// [build]
573/// jobs = 1
574/// ```
575///
576/// ```toml
577/// [build]
578/// jobs = "default" # Currently only support "default".
579/// ```
580#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
581#[derive(Debug, Clone, Serialize)]
582#[serde(untagged)]
583pub enum JobsConfig {
584    Integer(i32),
585    String(String),
586}
587
588impl<'de> Deserialize<'de> for JobsConfig {
589    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
590    where
591        D: serde::Deserializer<'de>,
592    {
593        UntaggedEnumVisitor::new()
594            .i32(|int| Ok(JobsConfig::Integer(int)))
595            .string(|string| Ok(JobsConfig::String(string.to_owned())))
596            .deserialize(deserializer)
597    }
598}
599
600/// The `[build]` table.
601///
602/// Example configuration:
603///
604/// ```toml
605/// [build]
606/// jobs = 4
607/// target = "x86_64-unknown-linux-gnu"
608/// target-dir = "target"
609/// rustflags = ["-C", "link-arg=-fuse-ld=lld"]
610/// incremental = true
611/// ```
612#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
613#[derive(Debug, Deserialize, Serialize)]
614#[serde(rename_all = "kebab-case")]
615pub struct CargoBuildConfig {
616    // deprecated, but preserved for compatibility
617    pub pipelining: Option<bool>,
618    pub dep_info_basedir: Option<ConfigRootRelativePath>,
619    pub target_dir: Option<ConfigRootRelativePath>,
620    pub build_dir: Option<ConfigRootRelativePathTemplate>,
621    pub incremental: Option<bool>,
622    pub target: Option<BuildTargetConfig>,
623    pub profile: Option<ProfileName>,
624    pub jobs: Option<JobsConfig>,
625    pub rustflags: Option<StringList>,
626    pub rustdocflags: Option<StringList>,
627    pub rustc_wrapper: Option<ConfigRootRelativeProgramPath>,
628    pub rustc_workspace_wrapper: Option<ConfigRootRelativeProgramPath>,
629    pub rustc: Option<ConfigRootRelativeProgramPath>,
630    pub rustdoc: Option<ConfigRootRelativeProgramPath>,
631    pub artifact_dir: Option<ConfigRootRelativePath>,
632    pub warnings: Option<WarningHandling>,
633    /// Unstable feature `-Zsbom`.
634    pub sbom: Option<bool>,
635    /// Unstable feature `-Zbuild-analysis`.
636    pub analysis: Option<CargoBuildAnalysis>,
637    /// Unstable feature `-Zchecksum-freshness`.
638    pub fingerprint: Option<FingerprintMethod>,
639    pub build_std: Option<BuildStdConfig>,
640}
641
642/// Metrics collection for build analysis.
643#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
644#[derive(Debug, Deserialize, Serialize, Default)]
645#[serde(rename_all = "kebab-case")]
646pub struct CargoBuildAnalysis {
647    pub enabled: bool,
648}
649
650/// Whether warnings should warn, be allowed, or cause an error.
651#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
652#[derive(Debug, Copy, Clone, PartialEq, Eq, Deserialize, Serialize, Default)]
653#[serde(rename_all = "kebab-case")]
654pub enum WarningHandling {
655    #[default]
656    /// Output warnings.
657    Warn,
658    /// Allow warnings (do not output them).
659    Allow,
660    /// Error if  warnings are emitted.
661    Deny,
662}
663
664#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
665#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Deserialize, Serialize, Default)]
666#[serde(rename_all = "kebab-case")]
667pub enum FingerprintMethod {
668    #[default]
669    Mtime,
670    Content,
671}
672
673impl FingerprintMethod {
674    pub fn as_str(&self) -> &'static str {
675        match self {
676            Self::Mtime => "mtime",
677            Self::Content => "content",
678        }
679    }
680}
681
682impl std::fmt::Display for FingerprintMethod {
683    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
684        self.as_str().fmt(f)
685    }
686}
687
688/// Configuration for `build.build-std`.
689#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
690#[derive(Debug, Deserialize, Serialize)]
691#[serde(rename_all = "kebab-case")]
692pub struct BuildStdConfig {
693    pub when: Option<BuildStdWhen>,
694    pub crates: Option<BuildStdCrates>,
695}
696
697/// When to build the standard library.
698#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
699#[derive(Debug, Deserialize, Serialize, PartialEq, Eq)]
700#[serde(rename_all = "kebab-case")]
701pub enum BuildStdWhen {
702    Never,
703    Always,
704}
705
706/// Which standard library crates to build.
707/// Valid values are "core", "alloc", "std", or an array of crate names
708#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
709#[derive(Debug, PartialEq, Eq, Serialize)]
710#[serde(rename_all = "lowercase")]
711pub enum BuildStdCrates {
712    Core,
713    Alloc,
714    Std,
715    // Custom list of crates - permanently unstable
716    #[serde(untagged)]
717    List(Vec<String>),
718}
719
720impl<'de> Deserialize<'de> for BuildStdCrates {
721    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
722    where
723        D: de::Deserializer<'de>,
724    {
725        UntaggedEnumVisitor::new()
726            .string(|s| match s {
727                "core" => Ok(Self::Core),
728                "alloc" => Ok(Self::Alloc),
729                "std" => Ok(Self::Std),
730                _ => Err(serde::de::Error::unknown_variant(
731                    s,
732                    &["core", "alloc", "std"],
733                )),
734            })
735            .seq(|seq| seq.deserialize().map(Self::List))
736            .deserialize(deserializer)
737    }
738}
739
740/// Configuration for `build.target`.
741///
742/// Accepts in the following forms:
743///
744/// ```toml
745/// target = "a"
746/// target = ["a"]
747/// target = ["a", "b"]
748/// ```
749#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
750#[derive(Debug, Deserialize, Serialize)]
751#[serde(transparent)]
752pub struct BuildTargetConfig {
753    inner: Value<BuildTargetConfigInner>,
754}
755
756#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
757#[derive(Debug, Serialize)]
758#[serde(untagged)]
759enum BuildTargetConfigInner {
760    One(String),
761    Many(Vec<String>),
762}
763
764impl<'de> Deserialize<'de> for BuildTargetConfigInner {
765    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
766    where
767        D: serde::Deserializer<'de>,
768    {
769        UntaggedEnumVisitor::new()
770            .string(|one| Ok(BuildTargetConfigInner::One(one.to_owned())))
771            .seq(|many| many.deserialize().map(BuildTargetConfigInner::Many))
772            .deserialize(deserializer)
773    }
774}
775
776impl BuildTargetConfig {
777    /// Gets values of `build.target` as a list of strings.
778    pub fn values(&self, current_dir: &Path) -> Result<Vec<String>> {
779        let map = |s: &String| {
780            if s.ends_with(".json") {
781                // Path to a target specification file (in JSON).
782                // <https://doc.rust-lang.org/rustc/targets/custom.html>
783                self.inner
784                    .definition
785                    .root(current_dir)
786                    .join(s)
787                    .to_str()
788                    .expect("must be utf-8 in toml")
789                    .to_string()
790            } else {
791                // A string. Probably a target tuple.
792                s.to_string()
793            }
794        };
795        let values = match &self.inner.val {
796            BuildTargetConfigInner::One(s) => vec![map(s)],
797            BuildTargetConfigInner::Many(v) => v.iter().map(map).collect(),
798        };
799        Ok(values)
800    }
801}
802
803/// The `[resolver]` table.
804///
805/// Example configuration:
806///
807/// ```toml
808/// [resolver]
809/// incompatible-rust-versions = "fallback"
810/// incompatible-publish-age = "deny"
811/// feature-unification = "workspace"
812/// lockfile-path = "my/Cargo.lock"
813/// ```
814#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
815#[derive(Debug, Deserialize, Serialize)]
816#[serde(rename_all = "kebab-case")]
817pub struct CargoResolverConfig {
818    pub incompatible_rust_versions: Option<IncompatibleRustVersions>,
819    pub incompatible_publish_age: Option<IncompatiblePublishAge>,
820    pub feature_unification: Option<FeatureUnification>,
821    pub lockfile_path: Option<ConfigRootRelativePathTemplate>,
822}
823
824#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
825#[derive(Debug, Deserialize, Serialize, PartialEq, Eq)]
826#[serde(rename_all = "kebab-case")]
827pub enum IncompatibleRustVersions {
828    Allow,
829    Fallback,
830}
831
832#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
833#[derive(Debug, Deserialize, Serialize, PartialEq, Eq)]
834#[serde(rename_all = "kebab-case")]
835pub enum IncompatiblePublishAge {
836    Allow,
837    Deny,
838}
839
840#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
841#[derive(Copy, Clone, Debug, Deserialize, Serialize)]
842#[serde(rename_all = "kebab-case")]
843pub enum FeatureUnification {
844    Package,
845    Selected,
846    Workspace,
847}
848
849/// The `[term]` table.
850///
851/// Example configuration:
852///
853/// ```toml
854/// [term]
855/// verbose = false
856/// quiet = false
857/// color = "auto"
858/// progress.when = "auto"
859/// ```
860#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
861#[derive(Debug, Deserialize, Serialize, Default)]
862#[serde(rename_all = "kebab-case")]
863pub struct TermConfig {
864    pub verbose: Option<bool>,
865    pub quiet: Option<bool>,
866    pub color: Option<String>,
867    pub hyperlinks: Option<bool>,
868    pub unicode: Option<bool>,
869    pub graphics: Option<bool>,
870    pub progress: Option<ProgressConfig>,
871}
872
873/// The `term.progress` configuration.
874///
875/// Example configuration:
876///
877/// ```toml
878/// [term]
879/// progress.when = "never" # or "auto"
880/// ```
881///
882/// ```toml
883/// # `when = "always"` requires a `width` field
884/// [term]
885/// progress = { when = "always", width = 80 }
886/// ```
887#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
888#[derive(Debug, Default, Serialize)]
889#[serde(rename_all = "kebab-case")]
890pub struct ProgressConfig {
891    pub when: ProgressWhen,
892    pub width: Option<usize>,
893    /// Communicate progress status with a terminal
894    pub term_integration: Option<bool>,
895}
896
897#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
898#[derive(Debug, Default, Deserialize, Serialize)]
899#[serde(rename_all = "kebab-case")]
900pub enum ProgressWhen {
901    #[default]
902    Auto,
903    Never,
904    Always,
905}
906
907// We need this custom deserialization for validadting the rule of
908// `when = "always"` requiring a `width` field.
909impl<'de> Deserialize<'de> for ProgressConfig {
910    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
911    where
912        D: serde::Deserializer<'de>,
913    {
914        #[derive(Deserialize)]
915        #[serde(rename_all = "kebab-case")]
916        struct ProgressConfigInner {
917            #[serde(default)]
918            when: ProgressWhen,
919            width: Option<usize>,
920            term_integration: Option<bool>,
921        }
922
923        let pc = ProgressConfigInner::deserialize(deserializer)?;
924        if let ProgressConfigInner {
925            when: ProgressWhen::Always,
926            width: None,
927            ..
928        } = pc
929        {
930            return Err(serde::de::Error::custom(
931                "\"always\" progress requires a `width` key",
932            ));
933        }
934        Ok(ProgressConfig {
935            when: pc.when,
936            width: pc.width,
937            term_integration: pc.term_integration,
938        })
939    }
940}
941
942#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
943#[derive(Debug, Serialize)]
944#[serde(untagged)]
945enum EnvConfigValueInner {
946    Simple(String),
947    WithOptions {
948        value: ConfigRootRelativePath,
949        #[serde(default)]
950        force: bool,
951        #[serde(default)]
952        relative: bool,
953    },
954}
955
956impl<'de> Deserialize<'de> for EnvConfigValueInner {
957    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
958    where
959        D: serde::Deserializer<'de>,
960    {
961        #[derive(Deserialize)]
962        struct WithOptions {
963            value: ConfigRootRelativePath,
964            #[serde(default)]
965            force: bool,
966            #[serde(default)]
967            relative: bool,
968        }
969
970        struct Visitor;
971
972        impl<'de> de::Visitor<'de> for Visitor {
973            type Value = EnvConfigValueInner;
974
975            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
976                f.write_str("a string or map")
977            }
978
979            fn visit_str<E: de::Error>(self, value: &str) -> Result<Self::Value, E> {
980                Ok(EnvConfigValueInner::Simple(value.to_owned()))
981            }
982
983            fn visit_string<E: de::Error>(self, value: String) -> Result<Self::Value, E> {
984                Ok(EnvConfigValueInner::Simple(value))
985            }
986
987            fn visit_map<M: de::MapAccess<'de>>(self, map: M) -> Result<Self::Value, M::Error> {
988                let options = WithOptions::deserialize(de::value::MapAccessDeserializer::new(map))?;
989                Ok(EnvConfigValueInner::WithOptions {
990                    value: options.value,
991                    force: options.force,
992                    relative: options.relative,
993                })
994            }
995        }
996
997        deserializer.deserialize_any(Visitor)
998    }
999}
1000
1001/// Configuration value for environment variables in `[env]` section.
1002///
1003/// Supports two formats: simple string and with options.
1004///
1005/// ```toml
1006/// [env]
1007/// FOO = "value"
1008/// ```
1009///
1010/// ```toml
1011/// [env]
1012/// BAR = { value = "relative/path", relative = true }
1013/// BAZ = { value = "override", force = true }
1014/// ```
1015#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1016#[derive(Debug, Deserialize, Serialize)]
1017#[serde(transparent)]
1018pub struct EnvConfigValue {
1019    inner: EnvConfigValueInner,
1020}
1021
1022impl EnvConfigValue {
1023    /// Whether this value should override existing environment variables.
1024    pub fn is_force(&self) -> bool {
1025        match self.inner {
1026            EnvConfigValueInner::Simple(_) => false,
1027            EnvConfigValueInner::WithOptions { force, .. } => force,
1028        }
1029    }
1030
1031    /// Resolves the environment variable value.
1032    ///
1033    /// If `relative = true`,
1034    /// the value is interpreted as a [`ConfigRootRelativePath`]-like path.
1035    pub fn resolve<'a>(&'a self, current_dir: &Path) -> Cow<'a, OsStr> {
1036        match self.inner {
1037            EnvConfigValueInner::Simple(ref s) => Cow::Borrowed(OsStr::new(s.as_str())),
1038            EnvConfigValueInner::WithOptions {
1039                ref value,
1040                relative,
1041                ..
1042            } => {
1043                if relative {
1044                    let p = value.resolve(current_dir);
1045                    Cow::Owned(p.into_os_string())
1046                } else {
1047                    Cow::Borrowed(OsStr::new(value.as_str()))
1048                }
1049            }
1050        }
1051    }
1052}
1053
1054pub type EnvConfig = HashMap<String, EnvConfigValue>;
1055
1056/// Credentials for a registry.
1057#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1058#[derive(Clone, Debug, Default, Deserialize, Serialize)]
1059#[serde(rename_all = "kebab-case")]
1060pub struct RegistryCredential {
1061    #[cfg_attr(feature = "unstable-schema", schemars(with = "Option<String>"))]
1062    pub token: OptValue<Secret<String>>,
1063}
1064
1065/// `[registries.NAME]` tables.
1066///
1067/// The values here should be kept in sync with `GlobalRegistryConfig`
1068#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1069#[derive(Deserialize, Serialize, Clone, Debug)]
1070#[serde(rename_all = "kebab-case")]
1071pub struct RegistryConfig {
1072    pub index: Option<String>,
1073    #[deprecated = "see `RegistryCredential::token` instead"]
1074    #[cfg_attr(feature = "unstable-schema", schemars(with = "Option<String>"))]
1075    pub token: OptValue<Secret<String>>,
1076    pub credential_provider: Option<PathAndArgs>,
1077    /// Minimum publish age threshold for RFC 3923
1078    pub min_publish_age: Option<String>,
1079    #[serde(rename = "protocol")]
1080    _protocol: Option<String>,
1081}
1082
1083/// The `[registry]` table, which has more keys than the `[registries.NAME]` tables.
1084///
1085/// Note: nesting `RegistryConfig` inside this struct and using `serde(flatten)` *should* work
1086/// but fails with "invalid type: sequence, expected a value" when attempting to deserialize.
1087#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1088#[derive(Deserialize, Serialize)]
1089#[serde(rename_all = "kebab-case")]
1090pub struct GlobalRegistryConfig {
1091    pub index: Option<String>,
1092    #[deprecated = "see `RegistryCredential::token` instead"]
1093    #[cfg_attr(feature = "unstable-schema", schemars(with = "Option<String>"))]
1094    pub token: OptValue<Secret<String>>,
1095    pub credential_provider: Option<PathAndArgs>,
1096    /// Global default Minimum publish age threshold for RFC 3923
1097    pub global_min_publish_age: Option<String>,
1098    #[serde(rename = "default")]
1099    _default: Option<String>,
1100    #[serde(rename = "global-credential-providers")]
1101    _global_credential_providers: Option<Vec<String>>,
1102}
1103
1104impl GlobalRegistryConfig {
1105    pub fn to_registry_config(self) -> RegistryConfig {
1106        RegistryConfig {
1107            index: self.index,
1108            #[expect(deprecated)]
1109            token: self.token,
1110            credential_provider: self.credential_provider,
1111            // `min-publish-age` is per-registry config only.
1112            min_publish_age: None,
1113            _protocol: None,
1114        }
1115    }
1116}
1117
1118macro_rules! rel_path {
1119    ($name:ident) => {
1120        /// A path, potentially relative to the config, not current_dir
1121        #[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1122        #[derive(Debug, Deserialize, Serialize, PartialEq, Clone)]
1123        #[serde(transparent)]
1124        pub struct $name(Value<String>);
1125
1126        impl $name {
1127            pub fn new(path: Value<String>) -> Self {
1128                Self(path)
1129            }
1130
1131            /// Returns whether the configured path is an empty string.
1132            pub fn is_empty(&self) -> bool {
1133                self.as_str().is_empty()
1134            }
1135
1136            /// Returns the underlying value.
1137            pub fn as_value(&self) -> &Value<String> {
1138                &self.0
1139            }
1140
1141            /// Returns the raw underlying configuration value for this key.
1142            pub fn as_str(&self) -> &str {
1143                &self.0.val
1144            }
1145
1146            /// PRIVATE: Not to be made public to ensure people dependent on the base path have resolved first
1147            fn as_path(&self) -> &Path {
1148                Path::new(self.as_str())
1149            }
1150
1151            /// Returns the [extension](Path::extension) of the configured path as written.
1152            pub fn extension(&self) -> Option<&OsStr> {
1153                // `as_path` is allowed since this is base-agnostic
1154                self.as_path().extension()
1155            }
1156
1157            /// Returns where this path was defined.
1158            pub fn definition(&self) -> &Definition {
1159                &self.0.definition
1160            }
1161        }
1162
1163        impl fmt::Display for $name {
1164            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1165                fmt::Display::fmt(self.as_str(), f)
1166            }
1167        }
1168    };
1169}
1170
1171rel_path!(ConfigRootRelativePath);
1172
1173impl ConfigRootRelativePath {
1174    /// Resolves this configuration-root-relative path to an absolute path.
1175    ///
1176    /// This will always return an absolute path where it's relative to the
1177    /// location for configuration for this value.
1178    pub fn resolve(&self, current_dir: &Path) -> PathBuf {
1179        let value = self.as_value();
1180        value.definition.root(current_dir).join(&value.val)
1181    }
1182}
1183
1184rel_path!(ConfigRootRelativeProgramPath);
1185
1186impl ConfigRootRelativeProgramPath {
1187    /// Resolves this configuration-relative path to either an absolute path or
1188    /// something appropriate to execute from `PATH`.
1189    ///
1190    /// Values which don't look like a filesystem path (don't contain `/` or
1191    /// `\`) will be returned as-is, and everything else will fall through to an
1192    /// absolute path.
1193    pub fn resolve(&self, current_dir: &Path) -> PathBuf {
1194        let value = self.as_str();
1195        let is_path = value.contains('/') || (cfg!(windows) && value.contains('\\'));
1196        if is_path {
1197            self.definition().root(current_dir).join(value)
1198        } else {
1199            // A pathless name.
1200            PathBuf::from(value)
1201        }
1202    }
1203}
1204
1205rel_path!(ConfigRootRelativePathTemplate);
1206
1207impl ConfigRootRelativePathTemplate {
1208    /// Applies string replacements before resolving the path.
1209    ///
1210    /// `replacements` should be an [`IntoIterator`] of tuples with the "from" and "to" for the
1211    /// string replacement.
1212    pub fn resolve(
1213        &self,
1214        current_dir: &Path,
1215        replacements: impl IntoIterator<Item = (impl AsRef<str>, impl AsRef<str>)>,
1216    ) -> Result<PathBuf, ResolveTemplateError> {
1217        let path = self.as_value();
1218        let mut value = path.val.clone();
1219
1220        for (from, to) in replacements {
1221            value = value.replace(from.as_ref(), to.as_ref());
1222        }
1223
1224        // Check for expected variables
1225        let re = regex::Regex::new(r"\{(.*)\}").unwrap();
1226        if let Some(caps) = re.captures(&value) {
1227            return Err(ResolveTemplateError::UnexpectedVariable {
1228                variable: caps[1].to_string(),
1229                raw_template: path.val.clone(),
1230            });
1231        };
1232
1233        if value.contains("{") {
1234            return Err(ResolveTemplateError::UnexpectedBracket {
1235                bracket_type: BracketType::Opening,
1236                raw_template: path.val.clone(),
1237            });
1238        }
1239
1240        if value.contains("}") {
1241            return Err(ResolveTemplateError::UnexpectedBracket {
1242                bracket_type: BracketType::Closing,
1243                raw_template: path.val.clone(),
1244            });
1245        }
1246
1247        Ok(path.definition.root(current_dir).join(&value))
1248    }
1249}
1250
1251#[derive(Debug)]
1252pub enum ResolveTemplateError {
1253    UnexpectedVariable {
1254        variable: String,
1255        raw_template: String,
1256    },
1257    UnexpectedBracket {
1258        bracket_type: BracketType,
1259        raw_template: String,
1260    },
1261}
1262
1263#[derive(Debug)]
1264pub enum BracketType {
1265    Opening,
1266    Closing,
1267}
1268
1269rel_path!(ConfigParentRelativePath);
1270
1271impl ConfigParentRelativePath {
1272    /// Resolves this configuration-parent-relative path to an absolute path.
1273    ///
1274    /// This will always return an absolute path where it's relative to the
1275    /// location for configuration for this value.
1276    pub fn resolve(&self, current_dir: &Path) -> PathBuf {
1277        let value = self.as_value();
1278        value.definition.parent(current_dir).join(&value.val)
1279    }
1280}
1281
1282/// A config type that is a program to run.
1283///
1284/// This supports a list of strings like `['/path/to/program', 'somearg']`
1285/// or a space separated string like `'/path/to/program somearg'`.
1286///
1287/// This expects the first value to be the path to the program to run.
1288/// Subsequent values are strings of arguments to pass to the program.
1289///
1290/// Typically you should use [`ConfigRootRelativeProgramPath::resolve`] on the path
1291/// to get the actual program.
1292///
1293/// **Note**: Any usage of this type in config needs to be listed in
1294/// the `NON_MERGEABLE_LISTS` check to prevent list merging
1295/// from multiple config files.
1296#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1297#[cfg_attr(feature = "unstable-schema", schemars(with = "StringList"))]
1298#[derive(Debug, Clone, PartialEq)]
1299pub struct PathAndArgs {
1300    pub path: ConfigRootRelativeProgramPath,
1301    pub args: Vec<String>,
1302}
1303
1304impl<'de> serde::Deserialize<'de> for PathAndArgs {
1305    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1306    where
1307        D: serde::Deserializer<'de>,
1308    {
1309        let vsl = Value::<StringList>::deserialize(deserializer)?;
1310        let mut strings = vsl.val.0;
1311        if strings.is_empty() {
1312            return Err(D::Error::invalid_length(0, &"at least one element"));
1313        }
1314        let first = strings.remove(0);
1315        let crp = Value {
1316            val: first,
1317            definition: vsl.definition,
1318        };
1319        Ok(PathAndArgs {
1320            path: ConfigRootRelativeProgramPath(crp),
1321            args: strings,
1322        })
1323    }
1324}
1325
1326impl Serialize for PathAndArgs {
1327    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1328        serializer.collect_seq(
1329            std::iter::once(self.path.as_str()).chain(self.args.iter().map(String::as_str)),
1330        )
1331    }
1332}
1333
1334impl PathAndArgs {
1335    /// Construct a `PathAndArgs` from a string. The string will be split on ascii whitespace,
1336    /// with the first item being treated as a `ConfigRootRelativeProgramPath` to the executable, and subsequent
1337    /// items as arguments.
1338    pub fn from_whitespace_separated_string(p: &Value<String>) -> PathAndArgs {
1339        let mut iter = p.val.split_ascii_whitespace().map(str::to_string);
1340        let val = iter.next().unwrap_or_default();
1341        let args = iter.collect();
1342        let crp = Value {
1343            val,
1344            definition: p.definition.clone(),
1345        };
1346        PathAndArgs {
1347            path: ConfigRootRelativeProgramPath(crp),
1348            args,
1349        }
1350    }
1351}
1352
1353/// A type to deserialize a list of strings from a toml file.
1354///
1355/// Supports deserializing either a whitespace-separated list of arguments in a
1356/// single string or a string list itself. For example these deserialize to
1357/// equivalent values:
1358///
1359/// ```toml
1360/// a = 'a b c'
1361/// b = ['a', 'b', 'c']
1362/// ```
1363#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1364#[cfg_attr(feature = "unstable-schema", schemars(extend("type" = ["array", "string"])))]
1365#[derive(Debug, Deserialize, Serialize, Clone)]
1366pub struct StringList(Vec<String>);
1367
1368impl StringList {
1369    pub fn as_slice(&self) -> &[String] {
1370        &self.0
1371    }
1372}
1373
1374#[cfg(feature = "unstable-schema")]
1375#[test]
1376fn dump_config_schema() {
1377    let schema = schemars::schema_for!(Config);
1378    let dump = serde_json::to_string_pretty(&schema).unwrap();
1379    snapbox::assert_data_eq!(dump, snapbox::file!("../config.schema.json").raw());
1380}
1381
1382#[cfg(feature = "unstable-schema")]
1383#[test]
1384fn dump_credentials_schema() {
1385    let schema = schemars::schema_for!(Credentials);
1386    let dump = serde_json::to_string_pretty(&schema).unwrap();
1387    snapbox::assert_data_eq!(dump, snapbox::file!("../credentials.schema.json").raw());
1388}