1use 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#[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#[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 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#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
154#[derive(Deserialize, Serialize)]
155pub struct DetailedIncludeConfig {
156 pub path: ConfigParentRelativePath,
157 #[serde(default)]
159 pub optional: bool,
160}
161
162impl DetailedIncludeConfig {
163 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 pub auto_clean_frequency: Option<String>,
201 pub global_clean: Option<GlobalCleanConfig>,
203}
204
205#[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 pub max_src_age: Option<String>,
217 pub max_crate_age: Option<String>,
219 pub max_index_age: Option<String>,
221 pub max_git_co_age: Option<String>,
223 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#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
294#[derive(Debug, Deserialize, Serialize)]
295#[serde(rename_all = "kebab-case")]
296pub struct SourceConfigDef {
297 pub replace_with: OptValue<String>,
299 pub directory: Option<ConfigRootRelativePath>,
301 pub registry: OptValue<String>,
303 pub local_registry: Option<ConfigRootRelativePath>,
305 pub git: OptValue<String>,
307 pub branch: OptValue<String>,
309 pub tag: OptValue<String>,
311 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#[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 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#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
373#[derive(Debug, Hash, Serialize)]
374#[serde(rename_all = "lowercase")]
375pub enum RustdocExternMode {
376 Local,
378 Remote,
380 #[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#[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#[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#[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#[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#[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#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
613#[derive(Debug, Deserialize, Serialize)]
614#[serde(rename_all = "kebab-case")]
615pub struct CargoBuildConfig {
616 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 pub sbom: Option<bool>,
635 pub analysis: Option<CargoBuildAnalysis>,
637 pub fingerprint: Option<FingerprintMethod>,
639 pub build_std: Option<BuildStdConfig>,
640}
641
642#[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#[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 Warn,
658 Allow,
660 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#[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#[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#[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 #[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#[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 pub fn values(&self, current_dir: &Path) -> Result<Vec<String>> {
779 let map = |s: &String| {
780 if s.ends_with(".json") {
781 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 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#[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#[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#[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 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
907impl<'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#[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 pub fn is_force(&self) -> bool {
1025 match self.inner {
1026 EnvConfigValueInner::Simple(_) => false,
1027 EnvConfigValueInner::WithOptions { force, .. } => force,
1028 }
1029 }
1030
1031 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#[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#[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 pub min_publish_age: Option<String>,
1079 #[serde(rename = "protocol")]
1080 _protocol: Option<String>,
1081}
1082
1083#[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 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: None,
1113 _protocol: None,
1114 }
1115 }
1116}
1117
1118macro_rules! rel_path {
1119 ($name:ident) => {
1120 #[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 pub fn is_empty(&self) -> bool {
1133 self.as_str().is_empty()
1134 }
1135
1136 pub fn as_value(&self) -> &Value<String> {
1138 &self.0
1139 }
1140
1141 pub fn as_str(&self) -> &str {
1143 &self.0.val
1144 }
1145
1146 fn as_path(&self) -> &Path {
1148 Path::new(self.as_str())
1149 }
1150
1151 pub fn extension(&self) -> Option<&OsStr> {
1153 self.as_path().extension()
1155 }
1156
1157 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 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 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 PathBuf::from(value)
1201 }
1202 }
1203}
1204
1205rel_path!(ConfigRootRelativePathTemplate);
1206
1207impl ConfigRootRelativePathTemplate {
1208 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 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 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#[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 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#[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}