1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
use std::{
borrow::Cow,
cell::RefCell,
collections::BTreeMap,
ffi::{OsStr, OsString},
fmt::{self, Formatter},
ops,
path::{Path, PathBuf},
process::Command,
};
use serde::Serialize;
use crate::{
de::{self, split_encoded, split_space_separated, Color, Frequency, RegistriesProtocol, When},
error::{Context as _, Result},
process::ProcessBuilder,
resolve::{ResolveContext, ResolveOptions, TargetTriple, TargetTripleBorrow, TargetTripleRef},
value::Value,
};
/// Cargo configuration.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub struct Config {
// TODO: paths
/// The `[alias]` table.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#alias)
#[serde(default)]
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
pub alias: BTreeMap<String, StringList>,
/// The `[build]` table.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#build)
#[serde(default)]
#[serde(skip_serializing_if = "BuildConfig::is_none")]
pub build: BuildConfig,
/// The `[doc]` table.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#doc)
#[serde(default)]
#[serde(skip_serializing_if = "DocConfig::is_none")]
pub doc: DocConfig,
/// The `[env]` table.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#env)
#[serde(default)]
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
pub env: BTreeMap<String, EnvConfigValue>,
/// The `[future-incompat-report]` table.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#future-incompat-report)
#[serde(default)]
#[serde(skip_serializing_if = "FutureIncompatReportConfig::is_none")]
pub future_incompat_report: FutureIncompatReportConfig,
// TODO: cargo-new
// TODO: http
// TODO: install
/// The `[net]` table.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#net)
#[serde(default)]
#[serde(skip_serializing_if = "NetConfig::is_none")]
pub net: NetConfig,
// TODO: patch
// TODO: profile
/// The `[registries]` table.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#registries)
#[serde(default)]
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
pub registries: BTreeMap<String, RegistriesConfigValue>,
/// The `[registry]` table.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#registry)
#[serde(default)]
#[serde(skip_serializing_if = "RegistryConfig::is_none")]
pub registry: RegistryConfig,
// TODO: source
/// The resolved `[target]` table.
#[serde(skip_deserializing)]
#[serde(skip_serializing_if = "ref_cell_bree_map_is_empty")]
target: RefCell<BTreeMap<TargetTripleBorrow<'static>, TargetConfig>>,
/// The unresolved `[target]` table.
#[serde(default)]
#[serde(skip_serializing)]
#[serde(rename = "target")]
de_target: BTreeMap<String, de::TargetConfig>,
/// The `[term]` table.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#term)
#[serde(default)]
#[serde(skip_serializing_if = "TermConfig::is_none")]
pub term: TermConfig,
// Resolve contexts. Completely ignored in serialization and deserialization.
#[serde(skip)]
cx: ResolveContext,
#[serde(skip)]
current_dir: PathBuf,
}
fn ref_cell_bree_map_is_empty<K, V>(map: &RefCell<BTreeMap<K, V>>) -> bool {
map.borrow().is_empty()
}
impl Config {
/// Read config files hierarchically from the current directory and merges them.
pub fn load() -> Result<Self> {
Self::load_with_cwd(std::env::current_dir().context("failed to get current directory")?)
}
/// Read config files hierarchically from the given directory and merges them.
pub fn load_with_cwd(cwd: impl AsRef<Path>) -> Result<Self> {
let cwd = cwd.as_ref();
Self::load_with_options(cwd, ResolveOptions::default())
}
/// Read config files hierarchically from the given directory and merges them.
pub fn load_with_options(cwd: impl AsRef<Path>, options: ResolveOptions) -> Result<Self> {
let cwd = cwd.as_ref();
let cx = options.into_context();
let de = de::Config::_load_with_options(cwd, cx.cargo_home(cwd).clone())?;
Self::from_unresolved(de, cx, cwd.to_owned())
}
pub(crate) fn from_unresolved(
mut de: de::Config,
cx: ResolveContext,
current_dir: PathBuf,
) -> Result<Self> {
de.apply_env(&cx)?;
let mut alias = BTreeMap::new();
for (k, v) in de.alias {
alias.insert(k, StringList::from_unresolved(v));
}
let build = BuildConfig::from_unresolved(de.build, ¤t_dir);
let doc = DocConfig::from_unresolved(de.doc, ¤t_dir);
let mut env = BTreeMap::new();
for (k, v) in de.env {
env.insert(k, EnvConfigValue::from_unresolved(v, ¤t_dir));
}
let future_incompat_report =
FutureIncompatReportConfig::from_unresolved(de.future_incompat_report);
let net = NetConfig::from_unresolved(de.net);
let mut registries = BTreeMap::new();
for (k, v) in de.registries {
registries.insert(k, RegistriesConfigValue::from_unresolved(v));
}
let registry = RegistryConfig::from_unresolved(de.registry);
let term = TermConfig::from_unresolved(de.term);
Ok(Self {
alias,
build,
doc,
env,
future_incompat_report,
net,
registries,
registry,
target: RefCell::new(BTreeMap::new()),
de_target: de.target,
term,
cx,
current_dir,
})
}
/// Selects target triples to build.
///
/// The targets returned are based on the order of priority in which cargo
/// selects the target to be used for the build.
///
/// 1. `--target` option (`targets`)
/// 2. `CARGO_BUILD_TARGET` environment variable
/// 3. `build.target` config
/// 4. host triple (`host`)
///
/// **Note:** The result of this function is intended to handle target-specific
/// configurations and is not always appropriate to propagate directly to Cargo.
/// See [`build_target_for_cli`](Self::build_target_for_cli) for more.
///
/// ## Multi-target support
///
/// [Cargo 1.64+ supports multi-target builds](https://blog.rust-lang.org/2022/09/22/Rust-1.64.0.html#cargo-improvements-workspace-inheritance-and-multi-target-builds).
///
/// Therefore, this function may return multiple targets if multiple targets
/// are specified in `targets` or `build.target` config.
///
/// ## Custom target support
///
/// rustc allows you to build a custom target by specifying a target-spec file.
/// If a target-spec file is specified as the target, rustc considers the
/// [file stem](Path::file_stem) of that file to be the target triple name.
///
/// Since target-specific configs are referred by target triple name, this
/// function also converts the target specified in the path to a target triple name.
///
/// ## Examples
///
/// With single-target:
///
/// ```no_run
/// # fn main() -> anyhow::Result<()> {
/// use anyhow::bail;
/// use clap::Parser;
///
/// #[derive(Parser)]
/// struct Args {
/// #[clap(long)]
/// target: Option<String>,
/// }
///
/// let args = Args::parse();
/// let config = cargo_config2::Config::load()?;
///
/// let mut targets = config.build_target_for_config(args.target.as_ref())?;
/// if targets.len() != 1 {
/// bail!("multi-target build is not supported: {targets:?}");
/// }
/// let target = targets.pop().unwrap();
///
/// println!("{:?}", config.rustflags(target));
/// # Ok(()) }
/// ```
///
/// With multi-target:
///
/// ```no_run
/// # fn main() -> anyhow::Result<()> {
/// use clap::Parser;
///
/// #[derive(Parser)]
/// struct Args {
/// #[clap(long)]
/// target: Vec<String>,
/// }
///
/// let args = Args::parse();
/// let config = cargo_config2::Config::load()?;
///
/// let targets = config.build_target_for_config(&args.target)?;
///
/// for target in targets {
/// println!("{:?}", config.rustflags(target)?);
/// }
/// # Ok(()) }
/// ```
#[allow(single_use_lifetimes)]
pub fn build_target_for_config<'a>(
&self,
targets: impl IntoIterator<Item = impl Into<TargetTripleRef<'a>>>,
) -> Result<Vec<TargetTriple>> {
let targets: Vec<_> = targets.into_iter().map(|v| v.into().into_owned()).collect();
if !targets.is_empty() {
return Ok(targets);
}
let config_targets = self.build.target.clone().unwrap_or_default();
if !config_targets.is_empty() {
return Ok(config_targets);
}
Ok(vec![TargetTripleRef::from(self.cx.host_triple()?).into_owned()])
}
/// Selects target triples to pass to CLI.
///
/// The targets returned are based on the order of priority in which cargo
/// selects the target to be used for the build.
///
/// 1. `--target` option (`targets`)
/// 2. `CARGO_BUILD_TARGET` environment variable
/// 3. `build.target` config
///
/// Unlike [`build_target_for_config`](Self::build_target_for_config),
/// host triple is not referenced. This is because the behavior of Cargo
/// changes depending on whether or not `--target` option (or one of the
/// above) is set.
/// Also, Unlike [`build_target_for_config`](Self::build_target_for_config)
/// the target name specified in path is preserved.
#[allow(clippy::unnecessary_wraps)]
pub fn build_target_for_cli(
&self,
targets: impl IntoIterator<Item = impl AsRef<str>>,
) -> Result<Vec<String>> {
let targets: Vec<_> = targets.into_iter().map(|t| t.as_ref().to_owned()).collect();
if !targets.is_empty() {
return Ok(targets);
}
let config_targets = self.build.target.as_deref().unwrap_or_default();
if !config_targets.is_empty() {
return Ok(config_targets.iter().map(|t| t.cli_target_string().into_owned()).collect());
}
Ok(vec![])
}
fn init_target_config(&self, target: &TargetTripleRef<'_>) -> Result<()> {
let mut target_configs = self.target.borrow_mut();
if !target_configs.contains_key(target.cli_target()) {
let target_config = TargetConfig::from_unresolved(
de::Config::resolve_target(
&self.cx,
&self.de_target,
self.build.override_target_rustflags,
&self.build.de_rustflags,
target,
&self.build,
)?
.unwrap_or_default(),
&self.current_dir,
);
target_configs.insert(TargetTripleBorrow(target.clone().into_owned()), target_config);
}
Ok(())
}
/// Returns the resolved `[target]` table for the given target.
#[allow(single_use_lifetimes)]
pub fn target<'a>(&self, target: impl Into<TargetTripleRef<'a>>) -> Result<TargetConfig> {
let target = target.into();
self.init_target_config(&target)?;
Ok(self.target.borrow()[target.cli_target()].clone())
}
/// Returns the resolved linker path for the given target.
#[allow(single_use_lifetimes)]
pub fn linker<'a>(&self, target: impl Into<TargetTripleRef<'a>>) -> Result<Option<PathBuf>> {
let target = target.into();
self.init_target_config(&target)?;
Ok(self.target.borrow()[target.cli_target()].linker.clone())
}
/// Returns the resolved runner path and args for the given target.
#[allow(single_use_lifetimes)]
pub fn runner<'a>(
&self,
target: impl Into<TargetTripleRef<'a>>,
) -> Result<Option<PathAndArgs>> {
let target = target.into();
self.init_target_config(&target)?;
Ok(self.target.borrow()[target.cli_target()].runner.clone())
}
/// Returns the resolved rustflags for the given target.
#[allow(single_use_lifetimes)]
pub fn rustflags<'a>(&self, target: impl Into<TargetTripleRef<'a>>) -> Result<Option<Flags>> {
let target = target.into();
self.init_target_config(&target)?;
Ok(self.target.borrow()[target.cli_target()].rustflags.clone())
}
/// Returns the path and args that calls `rustc`.
///
/// If [`RUSTC_WRAPPER`](BuildConfig::rustc_wrapper) or
/// [`RUSTC_WORKSPACE_WRAPPER`](BuildConfig::rustc_workspace_wrapper) is set,
/// the path is the wrapper path and the argument is the rustc path.
/// Otherwise, the path is the rustc path.
///
/// If you set `rustc` path by [`ResolveOptions::rustc`], this returns the path set by that method.
pub fn rustc(&self) -> &PathAndArgs {
self.cx.rustc(&self.build)
}
/// Returns the path to `cargo`.
///
/// The returned path is the value of the `CARGO` environment variable if it is set. Otherwise, "cargo".
///
/// If you set `cargo` path by [`ResolveOptions::cargo`], this returns the path set by that method.
pub fn cargo(&self) -> &OsStr {
&self.cx.cargo
}
/// Returns the host triple.
pub fn host_triple(&self) -> Result<&str> {
self.cx.host_triple()
}
// TODO: add override instead?
// /// Merges the given config into this config.
// ///
// /// If `force` is `false`, this matches the way cargo [merges configs in the
// /// parent directories](https://doc.rust-lang.org/nightly/cargo/reference/config.html#hierarchical-structure).
// ///
// /// If `force` is `true`, this matches the way cargo's `--config` CLI option
// /// overrides config.
// pub fn merge(&mut self, from: Self, force: bool) -> Result<()> {
// merge::Merge::merge(self, from, force)
// }
}
/// The `[build]` table.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#build)
#[derive(Debug, Clone, Default, Serialize)]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub struct BuildConfig {
/// Sets the maximum number of compiler processes to run in parallel.
/// If negative, it sets the maximum number of compiler processes to the
/// number of logical CPUs plus provided value. Should not be 0.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#buildjobs)
#[serde(skip_serializing_if = "Option::is_none")]
pub jobs: Option<i32>,
/// Sets the executable to use for `rustc`.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#buildrustc)
///
/// **Note:** If a wrapper is set, cargo's actual rustc call goes through
/// the wrapper, so you may want to use [`Config::rustc`], which respects
/// that behavior instead of referencing this value directly.
#[serde(skip_serializing_if = "Option::is_none")]
pub rustc: Option<PathBuf>,
/// Sets a wrapper to execute instead of `rustc`.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#buildrustc-wrapper)
///
/// **Note:** If a wrapper is set, cargo's actual rustc call goes through
/// the wrapper, so you may want to use [`Config::rustc`], which respects
/// that behavior instead of referencing this value directly.
#[serde(skip_serializing_if = "Option::is_none")]
pub rustc_wrapper: Option<PathBuf>,
/// Sets a wrapper to execute instead of `rustc`, for workspace members only.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#buildrustc-workspace-wrapper)
///
/// **Note:** If a wrapper is set, cargo's actual rustc call goes through
/// the wrapper, so you may want to use [`Config::rustc`], which respects
/// that behavior instead of referencing this value directly.
#[serde(skip_serializing_if = "Option::is_none")]
pub rustc_workspace_wrapper: Option<PathBuf>,
/// Sets the executable to use for `rustdoc`.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#buildrustdoc)
#[serde(skip_serializing_if = "Option::is_none")]
pub rustdoc: Option<PathBuf>,
/// The default target platform triples to compile to.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#buildtarget)
#[serde(skip_serializing_if = "Option::is_none")]
pub target: Option<Vec<TargetTriple>>,
/// The path to where all compiler output is placed. The default if not
/// specified is a directory named target located at the root of the workspace.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#buildtarget)
#[serde(skip_serializing_if = "Option::is_none")]
pub target_dir: Option<PathBuf>,
/// Extra command-line flags to pass to rustc. The value may be an array
/// of strings or a space-separated string.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#buildrustflags)
///
/// **Note:** This field does not reflect the target-specific rustflags
/// configuration, so you may want to use [`Config::rustflags`] which respects
/// the target-specific rustflags configuration.
#[serde(skip_serializing_if = "Option::is_none")]
pub rustflags: Option<Flags>,
/// Extra command-line flags to pass to `rustdoc`. The value may be an array
/// of strings or a space-separated string.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#buildrustdocflags)
#[serde(skip_serializing_if = "Option::is_none")]
pub rustdocflags: Option<Flags>,
/// Whether or not to perform incremental compilation.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#buildincremental)
#[serde(skip_serializing_if = "Option::is_none")]
pub incremental: Option<bool>,
/// Strips the given path prefix from dep info file paths.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#builddep-info-basedir)
#[serde(skip_serializing_if = "Option::is_none")]
pub dep_info_basedir: Option<PathBuf>,
// Resolve contexts. Completely ignored in serialization and deserialization.
#[serde(skip)]
override_target_rustflags: bool,
#[serde(skip)]
pub(crate) de_rustflags: Option<de::Flags>,
}
impl BuildConfig {
pub(crate) fn from_unresolved(de: de::BuildConfig, current_dir: &Path) -> Self {
let jobs = de.jobs.map(|v| v.val);
let rustc = de.rustc.map(|v| v.resolve_as_program_path(current_dir).into_owned());
let rustc_wrapper =
de.rustc_wrapper.map(|v| v.resolve_as_program_path(current_dir).into_owned());
let rustc_workspace_wrapper =
de.rustc_workspace_wrapper.map(|v| v.resolve_as_program_path(current_dir).into_owned());
let rustdoc = de.rustdoc.map(|v| v.resolve_as_program_path(current_dir).into_owned());
let target = de.target.map(|t| {
t.as_array_no_split()
.iter()
.map(|v| {
TargetTriple::new(
v.val.clone().into(),
v.definition.as_ref(),
Some(current_dir),
)
})
.collect()
});
let target_dir = de.target_dir.map(|v| v.resolve_as_path(current_dir).into_owned());
let de_rustflags = de.rustflags.clone();
let rustflags =
de.rustflags.map(|v| Flags { flags: v.flags.into_iter().map(|v| v.val).collect() });
let rustdocflags =
de.rustdocflags.map(|v| Flags { flags: v.flags.into_iter().map(|v| v.val).collect() });
let incremental = de.incremental.map(|v| v.val);
let dep_info_basedir =
de.dep_info_basedir.map(|v| v.resolve_as_path(current_dir).into_owned());
let override_target_rustflags = de.override_target_rustflags;
Self {
jobs,
rustc,
rustc_wrapper,
rustc_workspace_wrapper,
rustdoc,
target,
target_dir,
rustflags,
rustdocflags,
incremental,
dep_info_basedir,
override_target_rustflags,
de_rustflags,
}
}
}
// https://github.com/rust-lang/cargo/blob/0.67.0/src/cargo/util/config/target.rs
/// A `[target.<triple>]` or `[target.<cfg>]` table.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#target)
#[derive(Debug, Clone, Default, Serialize)]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub struct TargetConfig {
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#targettriplelinker)
#[serde(skip_serializing_if = "Option::is_none")]
pub linker: Option<PathBuf>,
/// [reference (`target.<triple>.runner`)](https://doc.rust-lang.org/nightly/cargo/reference/config.html#targettriplerunner)
///
/// [reference (`target.<cfg>.runner`)](https://doc.rust-lang.org/nightly/cargo/reference/config.html#targetcfgrunner)
#[serde(skip_serializing_if = "Option::is_none")]
pub runner: Option<PathAndArgs>,
/// [reference (`target.<triple>.rustflags`)](https://doc.rust-lang.org/nightly/cargo/reference/config.html#targettriplerustflags)
///
/// [reference (`target.<cfg>.rustflags`)](https://doc.rust-lang.org/nightly/cargo/reference/config.html#targetcfgrustflags)
#[serde(skip_serializing_if = "Option::is_none")]
pub rustflags: Option<Flags>,
// TODO: links: https://doc.rust-lang.org/nightly/cargo/reference/config.html#targettriplelinks
}
impl TargetConfig {
pub(crate) fn from_unresolved(de: de::TargetConfig, current_dir: &Path) -> Self {
let linker = de.linker.map(|v| v.resolve_as_program_path(current_dir).into_owned());
let runner = match de.runner {
Some(v) => Some(PathAndArgs {
path: v.path.resolve_program(current_dir).into_owned(),
args: v.args.into_iter().map(|v| v.val.into()).collect(),
}),
None => None,
};
let rustflags =
de.rustflags.map(|v| Flags { flags: v.flags.into_iter().map(|v| v.val).collect() });
Self { linker, runner, rustflags }
}
}
/// The `[doc]` table.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#doc)
#[derive(Debug, Clone, Default, Serialize)]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub struct DocConfig {
/// This option sets the browser to be used by `cargo doc`, overriding the
/// `BROWSER` environment variable when opening documentation with the `--open` option.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#docbrowser)
#[serde(skip_serializing_if = "Option::is_none")]
pub browser: Option<PathAndArgs>,
}
impl DocConfig {
pub(crate) fn from_unresolved(de: de::DocConfig, current_dir: &Path) -> Self {
let browser = de.browser.map(|v| PathAndArgs {
path: v.path.resolve_program(current_dir).into_owned(),
args: v.args.into_iter().map(|v| v.val.into()).collect(),
});
Self { browser }
}
}
/// A value of the `[env]` table.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#env)
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct EnvConfigValue {
pub value: OsString,
pub force: bool,
pub relative: bool,
}
impl EnvConfigValue {
pub(crate) fn from_unresolved(de: de::EnvConfigValue, current_dir: &Path) -> Self {
if let de::EnvConfigValue::Table {
force, relative: Some(Value { val: true, .. }), ..
} = &de
{
return Self {
value: de.resolve(current_dir).into_owned(),
force: force.as_ref().map_or(false, |v| v.val),
// Since we resolved the value, it is no longer relative.
relative: false,
};
}
match de {
de::EnvConfigValue::Value(value) => {
Self { value: value.val.into(), force: false, relative: false }
}
de::EnvConfigValue::Table { value, force, .. } => Self {
value: value.val.into(),
force: force.map_or(false, |v| v.val),
relative: false,
},
}
}
}
impl Serialize for EnvConfigValue {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
#[derive(Serialize)]
#[serde(untagged)]
enum EnvRepr<'a> {
Value(Cow<'a, str>),
Table {
value: Cow<'a, str>,
#[serde(skip_serializing_if = "ops::Not::not")]
force: bool,
#[serde(skip_serializing_if = "ops::Not::not")]
relative: bool,
},
}
match self {
Self { value, force: false, relative: false } => {
EnvRepr::Value(value.to_string_lossy()).serialize(serializer)
}
Self { value, force, relative, .. } => EnvRepr::Table {
value: value.to_string_lossy(),
force: *force,
relative: *relative,
}
.serialize(serializer),
}
}
}
/// The `[future-incompat-report]` table.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#future-incompat-report)
#[derive(Debug, Clone, Default, Serialize)]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub struct FutureIncompatReportConfig {
/// Controls how often we display a notification to the terminal when a future incompat report is available.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#future-incompat-reportfrequency)
#[serde(skip_serializing_if = "Option::is_none")]
pub frequency: Option<Frequency>,
}
impl FutureIncompatReportConfig {
pub(crate) fn from_unresolved(de: de::FutureIncompatReportConfig) -> Self {
let frequency = de.frequency.map(|v| v.val);
Self { frequency }
}
}
/// The `[net]` table.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#net)
#[derive(Debug, Clone, Default, Serialize)]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub struct NetConfig {
/// Number of times to retry possibly spurious network errors.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#netretry)
#[serde(skip_serializing_if = "Option::is_none")]
pub retry: Option<u32>,
/// If this is `true`, then Cargo will use the `git` executable to fetch
/// registry indexes and git dependencies. If `false`, then it uses a
/// built-in `git` library.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#netgit-fetch-with-cli)
#[serde(skip_serializing_if = "Option::is_none")]
pub git_fetch_with_cli: Option<bool>,
/// If this is `true`, then Cargo will avoid accessing the network, and
/// attempt to proceed with locally cached data. If `false`, Cargo will
/// access the network as needed, and generate an error if it encounters a
/// network error.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#netoffline)
#[serde(skip_serializing_if = "Option::is_none")]
pub offline: Option<bool>,
}
impl NetConfig {
pub(crate) fn from_unresolved(de: de::NetConfig) -> Self {
let retry = de.retry.map(|v| v.val);
let git_fetch_with_cli = de.git_fetch_with_cli.map(|v| v.val);
let offline = de.offline.map(|v| v.val);
Self { retry, git_fetch_with_cli, offline }
}
}
/// A value of the `[registries]` table.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#registries)
#[derive(Clone, Default, Serialize)]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub struct RegistriesConfigValue {
/// Specifies the URL of the git index for the registry.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#registriesnameindex)
#[serde(skip_serializing_if = "Option::is_none")]
pub index: Option<String>,
/// Specifies the authentication token for the given registry.
///
/// Note: This library does not read any values in the
/// [credentials](https://doc.rust-lang.org/nightly/cargo/reference/config.html#credentials)
/// file.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#registriesnametoken)
#[serde(skip_serializing_if = "Option::is_none")]
pub token: Option<String>,
/// Specifies the protocol used to access crates.io.
/// Not allowed for any registries besides crates.io.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#registriescrates-ioprotocol)
#[serde(skip_serializing_if = "Option::is_none")]
pub protocol: Option<RegistriesProtocol>,
}
impl RegistriesConfigValue {
pub(crate) fn from_unresolved(de: de::RegistriesConfigValue) -> Self {
let index = de.index.map(|v| v.val);
let token = de.token.map(|v| v.val);
let protocol = de.protocol.map(|v| match v.val {
de::RegistriesProtocol::Git => RegistriesProtocol::Git,
de::RegistriesProtocol::Sparse => RegistriesProtocol::Sparse,
});
Self { index, token, protocol }
}
}
impl fmt::Debug for RegistriesConfigValue {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let Self { index, token, protocol } = self;
let redacted_token = token.as_ref().map(|_| "[REDACTED]");
f.debug_struct("RegistriesConfigValue")
.field("index", &index)
.field("token", &redacted_token)
.field("protocol", &protocol)
.finish_non_exhaustive()
}
}
/// The `[registry]` table.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#registry)
#[derive(Clone, Default, Serialize)]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub struct RegistryConfig {
/// The name of the registry (from the
/// [`registries` table](https://doc.rust-lang.org/nightly/cargo/reference/config.html#registries))
/// to use by default for registry commands like
/// [`cargo publish`](https://doc.rust-lang.org/nightly/cargo/commands/cargo-publish.html).
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#registrydefault)
#[serde(skip_serializing_if = "Option::is_none")]
pub default: Option<String>,
/// Specifies the authentication token for [crates.io](https://crates.io/).
///
/// Note: This library does not read any values in the
/// [credentials](https://doc.rust-lang.org/nightly/cargo/reference/config.html#credentials)
/// file.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#registrytoken)
#[serde(skip_serializing_if = "Option::is_none")]
pub token: Option<String>,
}
impl RegistryConfig {
pub(crate) fn from_unresolved(de: de::RegistryConfig) -> Self {
let default = de.default.map(|v| v.val);
let token = de.token.map(|v| v.val);
Self { default, token }
}
}
impl fmt::Debug for RegistryConfig {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let Self { default, token } = self;
let redacted_token = token.as_ref().map(|_| "[REDACTED]");
f.debug_struct("RegistryConfig")
.field("default", &default)
.field("token", &redacted_token)
.finish()
}
}
/// The `[term]` table.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#term)
#[derive(Debug, Clone, Default, Serialize)]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub struct TermConfig {
/// Controls whether or not log messages are displayed by Cargo.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#termquiet)
#[serde(skip_serializing_if = "Option::is_none")]
pub quiet: Option<bool>,
/// Controls whether or not extra detailed messages are displayed by Cargo.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#termverbose)
#[serde(skip_serializing_if = "Option::is_none")]
pub verbose: Option<bool>,
/// Controls whether or not colored output is used in the terminal.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#termcolor)
#[serde(skip_serializing_if = "Option::is_none")]
pub color: Option<Color>,
#[serde(default)]
#[serde(skip_serializing_if = "TermProgressConfig::is_none")]
pub progress: TermProgressConfig,
}
impl TermConfig {
pub(crate) fn from_unresolved(de: de::TermConfig) -> Self {
let quiet = de.quiet.map(|v| v.val);
let verbose = de.verbose.map(|v| v.val);
let color = de.color.map(|v| v.val);
let progress = TermProgressConfig::from_unresolved(de.progress);
Self { quiet, verbose, color, progress }
}
}
#[derive(Debug, Clone, Default, Serialize)]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub struct TermProgressConfig {
/// Controls whether or not progress bar is shown in the terminal.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#termprogresswhen)
#[serde(skip_serializing_if = "Option::is_none")]
pub when: Option<When>,
/// Sets the width for progress bar.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#termprogresswidth)
#[serde(skip_serializing_if = "Option::is_none")]
pub width: Option<u32>,
}
impl TermProgressConfig {
pub(crate) fn from_unresolved(de: de::TermProgress) -> Self {
let when = de.when.map(|v| v.val);
let width = de.width.map(|v| v.val);
Self { when, width }
}
}
/// A representation of rustflags and rustdocflags.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
#[serde(transparent)]
#[non_exhaustive]
pub struct Flags {
pub flags: Vec<String>,
}
impl Flags {
/// Creates a rustflags from a string separated with ASCII unit separator ('\x1f').
///
/// This is a valid format for the following environment variables:
///
/// - `CARGO_ENCODED_RUSTFLAGS` (Cargo 1.55+)
/// - `CARGO_ENCODED_RUSTDOCFLAGS` (Cargo 1.55+)
///
/// See also [`encode`](Self::encode).
pub fn from_encoded(s: &str) -> Self {
Self { flags: split_encoded(s).map(str::to_owned).collect() }
}
/// Creates a rustflags from a string separated with space (' ').
///
/// This is a valid format for the following environment variables:
///
/// - `RUSTFLAGS`
/// - `CARGO_TARGET_<triple>_RUSTFLAGS`
/// - `CARGO_BUILD_RUSTFLAGS`
/// - `RUSTDOCFLAGS`
/// - `CARGO_BUILD_RUSTDOCFLAGS`
///
/// And the following configs:
///
/// - `target.<triple>.rustflags`
/// - `target.<cfg>.rustflags`
/// - `build.rustflags`
/// - `build.rustdocflags`
///
/// See also [`encode_space_separated`](Self::encode_space_separated).
pub fn from_space_separated(s: &str) -> Self {
Self { flags: split_space_separated(s).map(str::to_owned).collect() }
}
/// Concatenates this rustflags with ASCII unit separator ('\x1f').
///
/// This is a valid format for the following environment variables:
///
/// - `CARGO_ENCODED_RUSTFLAGS` (Cargo 1.55+)
/// - `CARGO_ENCODED_RUSTDOCFLAGS` (Cargo 1.55+)
///
/// # Errors
///
/// This returns an error if any of flag contains ASCII unit separator ('\x1f').
///
/// This is because even if you do not intend it to be interpreted as a
/// separator, Cargo will interpret it as a separator.
///
/// Since it is not easy to insert an ASCII unit separator in a toml file or
/// Shell environment variable, this usually occurs when this rustflags is
/// created in the wrong way ([`from_encoded`](Self::from_encoded) vs
/// [`from_space_separated`](Self::from_space_separated)) or when a flag
/// containing a separator is written in the rust code ([`push`](Self::push),
/// `into`, `from`, etc.).
pub fn encode(&self) -> Result<String> {
self.encode_internal('\x1f')
}
/// Concatenates this rustflags with space (' ').
///
/// This is a valid format for the following environment variables:
///
/// - `RUSTFLAGS`
/// - `CARGO_TARGET_<triple>_RUSTFLAGS`
/// - `CARGO_BUILD_RUSTFLAGS`
/// - `RUSTDOCFLAGS`
/// - `CARGO_BUILD_RUSTDOCFLAGS`
///
/// And the following configs:
///
/// - `target.<triple>.rustflags`
/// - `target.<cfg>.rustflags`
/// - `build.rustflags`
/// - `build.rustdocflags`
///
/// # Errors
///
/// This returns an error if any of flag contains space (' ').
///
/// This is because even if you do not intend it to be interpreted as a
/// separator, Cargo will interpret it as a separator.
///
/// If you run into this error, consider using a more robust
/// [`CARGO_ENCODED_*` flags](Self::encode).
pub fn encode_space_separated(&self) -> Result<String> {
self.encode_internal(' ')
}
fn encode_internal(&self, sep: char) -> Result<String> {
let mut buf = String::with_capacity(
self.flags.len().saturating_sub(1) + self.flags.iter().map(String::len).sum::<usize>(),
);
for flag in &self.flags {
if flag.contains(sep) {
bail!("flag in rustflags must not contain its separator ({sep:?})");
}
if !buf.is_empty() {
buf.push(sep);
}
buf.push_str(flag);
}
Ok(buf)
}
/// Appends a flag to the back of this rustflags.
pub fn push(&mut self, flag: impl Into<String>) {
self.flags.push(flag.into());
}
}
impl From<Vec<String>> for Flags {
fn from(value: Vec<String>) -> Self {
Self { flags: value }
}
}
impl From<&[String]> for Flags {
fn from(value: &[String]) -> Self {
Self { flags: value.to_owned() }
}
}
impl From<&[&str]> for Flags {
fn from(value: &[&str]) -> Self {
Self { flags: value.iter().map(|&v| v.to_owned()).collect() }
}
}
impl<const N: usize> From<[String; N]> for Flags {
fn from(value: [String; N]) -> Self {
Self { flags: value[..].to_owned() }
}
}
impl<const N: usize> From<[&str; N]> for Flags {
fn from(value: [&str; N]) -> Self {
Self { flags: value[..].iter().map(|&v| v.to_owned()).collect() }
}
}
/// An executable path with arguments.
///
/// [reference](https://doc.rust-lang.org/nightly/cargo/reference/config.html#executable-paths-with-arguments)
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct PathAndArgs {
pub path: PathBuf,
pub args: Vec<OsString>,
}
impl PathAndArgs {
/// Creates a new program.
pub fn new(path: impl Into<PathBuf>) -> Self {
Self { path: path.into(), args: vec![] }
}
/// Adds an argument to pass to the program.
pub fn arg(&mut self, arg: impl Into<OsString>) -> &mut Self {
self.args.push(arg.into());
self
}
/// Adds multiple arguments to pass to the program.
pub fn args(&mut self, args: impl IntoIterator<Item = impl Into<OsString>>) -> &mut Self {
self.args.extend(args.into_iter().map(Into::into));
self
}
}
impl Serialize for PathAndArgs {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut v = Vec::with_capacity(1 + self.args.len());
v.push(self.path.to_string_lossy().into_owned());
for arg in &self.args {
v.push(arg.to_string_lossy().into_owned());
}
v.serialize(serializer)
}
}
impl From<PathAndArgs> for Command {
fn from(value: PathAndArgs) -> Self {
let mut cmd = Command::new(value.path);
cmd.args(value.args);
cmd
}
}
impl From<PathAndArgs> for ProcessBuilder {
fn from(value: PathAndArgs) -> Self {
let mut cmd = ProcessBuilder::new(value.path);
cmd.args(value.args);
cmd
}
}
/// A list of string.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
#[serde(transparent)]
#[non_exhaustive]
pub struct StringList {
pub list: Vec<String>,
}
impl StringList {
pub(crate) fn from_string(value: &str) -> Self {
Self { list: split_space_separated(value).map(str::to_owned).collect() }
}
pub(crate) fn from_array(list: Vec<String>) -> Self {
Self { list }
}
pub(crate) fn from_unresolved(value: de::StringList) -> Self {
Self { list: value.list.into_iter().map(|v| v.val).collect() }
}
}
impl From<String> for StringList {
fn from(value: String) -> Self {
Self::from_string(&value)
}
}
impl From<&String> for StringList {
fn from(value: &String) -> Self {
Self::from_string(value)
}
}
impl From<&str> for StringList {
fn from(value: &str) -> Self {
Self::from_string(value)
}
}
impl From<Vec<String>> for StringList {
fn from(value: Vec<String>) -> Self {
Self::from_array(value)
}
}
impl From<&[String]> for StringList {
fn from(value: &[String]) -> Self {
Self::from_array(value.to_owned())
}
}
impl From<&[&str]> for StringList {
fn from(value: &[&str]) -> Self {
Self::from_array(value.iter().map(|&v| v.to_owned()).collect())
}
}
impl<const N: usize> From<[String; N]> for StringList {
fn from(value: [String; N]) -> Self {
Self::from_array(value[..].to_owned())
}
}
impl<const N: usize> From<[&str; N]> for StringList {
fn from(value: [&str; N]) -> Self {
Self::from_array(value[..].iter().map(|&v| v.to_owned()).collect())
}
}