-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
mod.rs
2224 lines (2087 loc) · 77 KB
/
mod.rs
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
use annotate_snippets::{Annotation, AnnotationType, Renderer, Slice, Snippet, SourceAnnotation};
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::str::{self, FromStr};
use crate::AlreadyPrintedError;
use anyhow::{anyhow, bail, Context as _};
use cargo_platform::Platform;
use cargo_util::paths;
use cargo_util_schemas::manifest::{self, InheritableDependency};
use cargo_util_schemas::manifest::{RustVersion, TomlDependency};
use itertools::Itertools;
use lazycell::LazyCell;
use pathdiff::diff_paths;
use tracing::{debug, trace};
use url::Url;
use crate::core::compiler::{CompileKind, CompileTarget};
use crate::core::dependency::{Artifact, ArtifactTarget, DepKind};
use crate::core::manifest::{ManifestMetadata, TargetSourcePath, Warnings};
use crate::core::resolver::ResolveBehavior;
use crate::core::{find_workspace_root, resolve_relative_path, CliUnstable};
use crate::core::{Dependency, Manifest, PackageId, Summary, Target};
use crate::core::{Edition, EitherManifest, Feature, Features, VirtualManifest, Workspace};
use crate::core::{GitReference, PackageIdSpec, SourceId, WorkspaceConfig, WorkspaceRootConfig};
use crate::sources::{CRATES_IO_INDEX, CRATES_IO_REGISTRY};
use crate::util::errors::{CargoResult, ManifestError};
use crate::util::interning::InternedString;
use crate::util::{self, config::ConfigRelativePath, Config, IntoUrl, OptVersionReq};
mod embedded;
mod targets;
use self::targets::targets;
/// Loads a `Cargo.toml` from a file on disk.
///
/// This could result in a real or virtual manifest being returned.
///
/// A list of nested paths is also returned, one for each path dependency
/// within the manifest. For virtual manifests, these paths can only
/// come from patched or replaced dependencies. These paths are not
/// canonicalized.
pub fn read_manifest(
path: &Path,
source_id: SourceId,
config: &Config,
) -> CargoResult<(EitherManifest, Vec<PathBuf>)> {
trace!(
"read_manifest; path={}; source-id={}",
path.display(),
source_id
);
let mut contents = paths::read(path).map_err(|err| ManifestError::new(err, path.into()))?;
let embedded = is_embedded(path);
if embedded {
if !config.cli_unstable().script {
return Err(ManifestError::new(
anyhow::anyhow!("parsing `{}` requires `-Zscript`", path.display()),
path.into(),
))?;
}
contents = embedded::expand_manifest(&contents, path, config)
.map_err(|err| ManifestError::new(err, path.into()))?;
}
read_manifest_from_str(&contents, path, embedded, source_id, config).map_err(|err| {
if err.is::<AlreadyPrintedError>() {
err
} else {
ManifestError::new(
err.context(format!("failed to parse manifest at `{}`", path.display())),
path.into(),
)
.into()
}
})
}
/// See also `bin/cargo/commands/run.rs`s `is_manifest_command`
pub fn is_embedded(path: &Path) -> bool {
let ext = path.extension();
ext == Some(OsStr::new("rs")) ||
// Provide better errors by not considering directories to be embedded manifests
(ext.is_none() && path.is_file())
}
/// Parse an already-loaded `Cargo.toml` as a Cargo manifest.
///
/// This could result in a real or virtual manifest being returned.
///
/// A list of nested paths is also returned, one for each path dependency
/// within the manifest. For virtual manifests, these paths can only
/// come from patched or replaced dependencies. These paths are not
/// canonicalized.
fn read_manifest_from_str(
contents: &str,
manifest_file: &Path,
embedded: bool,
source_id: SourceId,
config: &Config,
) -> CargoResult<(EitherManifest, Vec<PathBuf>)> {
let package_root = manifest_file.parent().unwrap();
let mut unused = BTreeSet::new();
let deserializer = toml::de::Deserializer::new(contents);
let mut manifest: manifest::TomlManifest =
match serde_ignored::deserialize(deserializer, |path| {
let mut key = String::new();
stringify(&mut key, &path);
unused.insert(key);
}) {
Ok(manifest) => manifest,
Err(e) => {
let Some(span) = e.span() else {
return Err(e.into());
};
let (line_num, column) = translate_position(&contents, span.start);
let source_start = contents[0..span.start]
.rfind('\n')
.map(|s| s + 1)
.unwrap_or(0);
let source_end = contents[span.end - 1..]
.find('\n')
.map(|s| s + span.end)
.unwrap_or(contents.len());
let source = &contents[source_start..source_end];
// Make sure we don't try to highlight past the end of the line,
// but also make sure we are highlighting at least one character
let highlight_end = (column + contents[span].chars().count())
.min(source.len())
.max(column + 1);
// Get the path to the manifest, relative to the cwd
let manifest_path = diff_paths(manifest_file, config.cwd())
.unwrap_or_else(|| manifest_file.to_path_buf())
.display()
.to_string();
let snippet = Snippet {
title: Some(Annotation {
id: None,
label: Some(e.message()),
annotation_type: AnnotationType::Error,
}),
footer: vec![],
slices: vec![Slice {
source: &source,
line_start: line_num + 1,
origin: Some(manifest_path.as_str()),
annotations: vec![SourceAnnotation {
range: (column, highlight_end),
label: "",
annotation_type: AnnotationType::Error,
}],
fold: false,
}],
};
let renderer = Renderer::styled();
writeln!(config.shell().err(), "{}", renderer.render(snippet))?;
return Err(AlreadyPrintedError::new(e.into()).into());
}
};
let add_unused = |warnings: &mut Warnings| {
for key in unused {
warnings.add_warning(format!("unused manifest key: {}", key));
if key == "profiles.debug" {
warnings.add_warning("use `[profile.dev]` to configure debug builds".to_string());
}
}
};
if let Some(deps) = manifest
.workspace
.as_ref()
.and_then(|ws| ws.dependencies.as_ref())
{
for (name, dep) in deps {
if dep.is_optional() {
bail!("{name} is optional, but workspace dependencies cannot be optional",);
}
if dep.is_public() {
bail!("{name} is public, but workspace dependencies cannot be public",);
}
}
}
let mut public_deps_without_z = BTreeSet::new();
if let Some(deps) = &mut manifest.dependencies {
for (name, dep) in deps {
if let InheritableDependency::Value(toml_dep) = dep {
if toml_dep.is_public() && !config.cli_unstable().public_dependency {
if let TomlDependency::Detailed(d) = toml_dep {
d.public = Some(false)
}
public_deps_without_z.insert(name.clone());
}
}
}
}
let public_warn = |warnings: &mut Warnings| {
for name in public_deps_without_z {
warnings.add_warning(format!(
"{name} is public, pass `-Zpublic-dependency` to enable support for it",
))
}
};
return if manifest.project.is_some() || manifest.package.is_some() {
let (mut manifest, paths) =
to_real_manifest(manifest, embedded, source_id, package_root, config)?;
add_unused(manifest.warnings_mut());
public_warn(manifest.warnings_mut());
if manifest.targets().iter().all(|t| t.is_custom_build()) {
bail!(
"no targets specified in the manifest\n\
either src/lib.rs, src/main.rs, a [lib] section, or \
[[bin]] section must be present"
)
}
Ok((EitherManifest::Real(manifest), paths))
} else {
let (mut m, paths) = to_virtual_manifest(manifest, source_id, package_root, config)?;
add_unused(m.warnings_mut());
public_warn(m.warnings_mut());
Ok((EitherManifest::Virtual(m), paths))
};
fn stringify(dst: &mut String, path: &serde_ignored::Path<'_>) {
use serde_ignored::Path;
match *path {
Path::Root => {}
Path::Seq { parent, index } => {
stringify(dst, parent);
if !dst.is_empty() {
dst.push('.');
}
dst.push_str(&index.to_string());
}
Path::Map { parent, ref key } => {
stringify(dst, parent);
if !dst.is_empty() {
dst.push('.');
}
dst.push_str(key);
}
Path::Some { parent }
| Path::NewtypeVariant { parent }
| Path::NewtypeStruct { parent } => stringify(dst, parent),
}
}
}
/// Warn about paths that have been deprecated and may conflict.
fn warn_on_deprecated(new_path: &str, name: &str, kind: &str, warnings: &mut Vec<String>) {
let old_path = new_path.replace("-", "_");
warnings.push(format!(
"conflicting between `{new_path}` and `{old_path}` in the `{name}` {kind}.\n
`{old_path}` is ignored and not recommended for use in the future"
))
}
/// Prepares the manifest for publishing.
// - Path and git components of dependency specifications are removed.
// - License path is updated to point within the package.
pub fn prepare_for_publish(
me: &manifest::TomlManifest,
ws: &Workspace<'_>,
package_root: &Path,
) -> CargoResult<manifest::TomlManifest> {
let config = ws.config();
let mut package = me.package().unwrap().clone();
package.workspace = None;
let current_resolver = package
.resolver
.as_ref()
.map(|r| ResolveBehavior::from_manifest(r))
.unwrap_or_else(|| {
package
.edition
.as_ref()
.and_then(|e| e.as_value())
.map(|e| Edition::from_str(e))
.unwrap_or(Ok(Edition::Edition2015))
.map(|e| e.default_resolve_behavior())
})?;
if ws.resolve_behavior() != current_resolver {
// This ensures the published crate if built as a root (e.g. `cargo install`) will
// use the same resolver behavior it was tested with in the workspace.
// To avoid forcing a higher MSRV we don't explicitly set this if it would implicitly
// result in the same thing.
package.resolver = Some(ws.resolve_behavior().to_manifest());
}
if let Some(license_file) = &package.license_file {
let license_file = license_file
.as_value()
.context("license file should have been resolved before `prepare_for_publish()`")?;
let license_path = Path::new(&license_file);
let abs_license_path = paths::normalize_path(&package_root.join(license_path));
if abs_license_path.strip_prefix(package_root).is_err() {
// This path points outside of the package root. `cargo package`
// will copy it into the root, so adjust the path to this location.
package.license_file = Some(manifest::InheritableField::Value(
license_path
.file_name()
.unwrap()
.to_str()
.unwrap()
.to_string(),
));
}
}
if let Some(readme) = &package.readme {
let readme = readme
.as_value()
.context("readme should have been resolved before `prepare_for_publish()`")?;
match readme {
manifest::StringOrBool::String(readme) => {
let readme_path = Path::new(&readme);
let abs_readme_path = paths::normalize_path(&package_root.join(readme_path));
if abs_readme_path.strip_prefix(package_root).is_err() {
// This path points outside of the package root. `cargo package`
// will copy it into the root, so adjust the path to this location.
package.readme = Some(manifest::InheritableField::Value(
manifest::StringOrBool::String(
readme_path
.file_name()
.unwrap()
.to_str()
.unwrap()
.to_string(),
),
));
}
}
manifest::StringOrBool::Bool(_) => {}
}
}
let all = |_d: &manifest::TomlDependency| true;
return Ok(manifest::TomlManifest {
package: Some(package),
project: None,
profile: me.profile.clone(),
lib: me.lib.clone(),
bin: me.bin.clone(),
example: me.example.clone(),
test: me.test.clone(),
bench: me.bench.clone(),
dependencies: map_deps(config, me.dependencies.as_ref(), all)?,
dev_dependencies: map_deps(
config,
me.dev_dependencies(),
manifest::TomlDependency::is_version_specified,
)?,
dev_dependencies2: None,
build_dependencies: map_deps(config, me.build_dependencies(), all)?,
build_dependencies2: None,
features: me.features.clone(),
target: match me.target.as_ref().map(|target_map| {
target_map
.iter()
.map(|(k, v)| {
Ok((
k.clone(),
manifest::TomlPlatform {
dependencies: map_deps(config, v.dependencies.as_ref(), all)?,
dev_dependencies: map_deps(
config,
v.dev_dependencies(),
manifest::TomlDependency::is_version_specified,
)?,
dev_dependencies2: None,
build_dependencies: map_deps(config, v.build_dependencies(), all)?,
build_dependencies2: None,
},
))
})
.collect()
}) {
Some(Ok(v)) => Some(v),
Some(Err(e)) => return Err(e),
None => None,
},
replace: None,
patch: None,
workspace: None,
badges: me.badges.clone(),
cargo_features: me.cargo_features.clone(),
lints: me.lints.clone(),
});
fn map_deps(
config: &Config,
deps: Option<&BTreeMap<manifest::PackageName, manifest::InheritableDependency>>,
filter: impl Fn(&manifest::TomlDependency) -> bool,
) -> CargoResult<Option<BTreeMap<manifest::PackageName, manifest::InheritableDependency>>> {
let Some(deps) = deps else { return Ok(None) };
let deps = deps
.iter()
.filter(|(_k, v)| {
if let manifest::InheritableDependency::Value(def) = v {
filter(def)
} else {
false
}
})
.map(|(k, v)| Ok((k.clone(), map_dependency(config, v)?)))
.collect::<CargoResult<BTreeMap<_, _>>>()?;
Ok(Some(deps))
}
fn map_dependency(
config: &Config,
dep: &manifest::InheritableDependency,
) -> CargoResult<manifest::InheritableDependency> {
let dep = match dep {
manifest::InheritableDependency::Value(manifest::TomlDependency::Detailed(d)) => {
let mut d = d.clone();
// Path dependencies become crates.io deps.
d.path.take();
// Same with git dependencies.
d.git.take();
d.branch.take();
d.tag.take();
d.rev.take();
// registry specifications are elaborated to the index URL
if let Some(registry) = d.registry.take() {
d.registry_index = Some(config.get_registry_index(®istry)?.to_string());
}
Ok(d)
}
manifest::InheritableDependency::Value(manifest::TomlDependency::Simple(s)) => {
Ok(manifest::TomlDetailedDependency {
version: Some(s.clone()),
..Default::default()
})
}
_ => unreachable!(),
};
dep.map(manifest::TomlDependency::Detailed)
.map(manifest::InheritableDependency::Value)
}
}
pub fn to_real_manifest(
me: manifest::TomlManifest,
embedded: bool,
source_id: SourceId,
package_root: &Path,
config: &Config,
) -> CargoResult<(Manifest, Vec<PathBuf>)> {
fn get_ws(
config: &Config,
resolved_path: &Path,
workspace_config: &WorkspaceConfig,
) -> CargoResult<InheritableFields> {
match workspace_config {
WorkspaceConfig::Root(root) => Ok(root.inheritable().clone()),
WorkspaceConfig::Member {
root: Some(ref path_to_root),
} => {
let path = resolved_path
.parent()
.unwrap()
.join(path_to_root)
.join("Cargo.toml");
let root_path = paths::normalize_path(&path);
inheritable_from_path(config, root_path)
}
WorkspaceConfig::Member { root: None } => {
match find_workspace_root(&resolved_path, config)? {
Some(path_to_root) => inheritable_from_path(config, path_to_root),
None => Err(anyhow!("failed to find a workspace root")),
}
}
}
}
if !package_root.is_dir() {
bail!(
"package root '{}' is not a directory",
package_root.display()
);
};
let mut nested_paths = vec![];
let mut warnings = vec![];
let mut errors = vec![];
// Parse features first so they will be available when parsing other parts of the TOML.
let empty = Vec::new();
let cargo_features = me.cargo_features.as_ref().unwrap_or(&empty);
let features = Features::new(cargo_features, config, &mut warnings, source_id.is_path())?;
let mut package = match (&me.package, &me.project) {
(Some(_), Some(project)) => {
if source_id.is_path() {
config.shell().warn(format!(
"manifest at `{}` contains both `project` and `package`, \
this could become a hard error in the future",
package_root.display()
))?;
}
project.clone()
}
(Some(package), None) => package.clone(),
(None, Some(project)) => {
if source_id.is_path() {
config.shell().warn(format!(
"manifest at `{}` contains `[project]` instead of `[package]`, \
this could become a hard error in the future",
package_root.display()
))?;
}
project.clone()
}
(None, None) => bail!("no `package` section found"),
};
let workspace_config = match (me.workspace.as_ref(), package.workspace.as_ref()) {
(Some(toml_config), None) => {
let lints = toml_config.lints.clone();
let lints = verify_lints(lints)?;
let inheritable = InheritableFields {
package: toml_config.package.clone(),
dependencies: toml_config.dependencies.clone(),
lints,
_ws_root: package_root.to_path_buf(),
};
if let Some(ws_deps) = &inheritable.dependencies {
for (name, dep) in ws_deps {
unused_dep_keys(
name,
"workspace.dependencies",
dep.unused_keys(),
&mut warnings,
);
}
}
let ws_root_config = WorkspaceRootConfig::new(
package_root,
&toml_config.members,
&toml_config.default_members,
&toml_config.exclude,
&Some(inheritable),
&toml_config.metadata,
);
config
.ws_roots
.borrow_mut()
.insert(package_root.to_path_buf(), ws_root_config.clone());
WorkspaceConfig::Root(ws_root_config)
}
(None, root) => WorkspaceConfig::Member {
root: root.cloned(),
},
(Some(..), Some(..)) => bail!(
"cannot configure both `package.workspace` and \
`[workspace]`, only one can be specified"
),
};
let package_name = package.name.trim();
let resolved_path = package_root.join("Cargo.toml");
let inherit_cell: LazyCell<InheritableFields> = LazyCell::new();
let inherit =
|| inherit_cell.try_borrow_with(|| get_ws(config, &resolved_path, &workspace_config));
let version = package
.version
.clone()
.map(|version| field_inherit_with(version, "version", || inherit()?.version()))
.transpose()?;
package.version = version.clone().map(manifest::InheritableField::Value);
let pkgid = PackageId::new(
package.name.as_str().into(),
version
.clone()
.unwrap_or_else(|| semver::Version::new(0, 0, 0)),
source_id,
);
let edition = if let Some(edition) = package.edition.clone() {
let edition: Edition = field_inherit_with(edition, "edition", || inherit()?.edition())?
.parse()
.with_context(|| "failed to parse the `edition` key")?;
package.edition = Some(manifest::InheritableField::Value(edition.to_string()));
edition
} else {
Edition::Edition2015
};
// Add these lines if start a new unstable edition.
// ```
// if edition == Edition::Edition20xx {
// features.require(Feature::edition20xx())?;
// }
// ```
if edition == Edition::Edition2024 {
features.require(Feature::edition2024())?;
} else if !edition.is_stable() {
// Guard in case someone forgets to add .require()
return Err(util::errors::internal(format!(
"edition {} should be gated",
edition
)));
}
let rust_version = if let Some(rust_version) = &package.rust_version {
let rust_version = field_inherit_with(rust_version.clone(), "rust_version", || {
inherit()?.rust_version()
})?;
let req = rust_version.to_caret_req();
if let Some(first_version) = edition.first_version() {
let unsupported =
semver::Version::new(first_version.major, first_version.minor - 1, 9999);
if req.matches(&unsupported) {
bail!(
"rust-version {} is older than first version ({}) required by \
the specified edition ({})",
rust_version,
first_version,
edition,
)
}
}
Some(rust_version)
} else {
None
};
if package.metabuild.is_some() {
features.require(Feature::metabuild())?;
}
let resolve_behavior = match (
package.resolver.as_ref(),
me.workspace.as_ref().and_then(|ws| ws.resolver.as_ref()),
) {
(None, None) => None,
(Some(s), None) | (None, Some(s)) => Some(ResolveBehavior::from_manifest(s)?),
(Some(_), Some(_)) => {
bail!("cannot specify `resolver` field in both `[workspace]` and `[package]`")
}
};
// If we have no lib at all, use the inferred lib, if available.
// If we have a lib with a path, we're done.
// If we have a lib with no path, use the inferred lib or else the package name.
let targets = targets(
&features,
&me,
package_name,
package_root,
edition,
&package.build,
&package.metabuild,
&mut warnings,
&mut errors,
)?;
if targets.is_empty() {
debug!("manifest has no build targets");
}
if let Err(conflict_targets) = unique_build_targets(&targets, package_root) {
conflict_targets
.iter()
.for_each(|(target_path, conflicts)| {
warnings.push(format!(
"file `{}` found to be present in multiple \
build targets:\n{}",
target_path.display().to_string(),
conflicts
.iter()
.map(|t| format!(" * `{}` target `{}`", t.kind().description(), t.name(),))
.join("\n")
));
})
}
if let Some(links) = &package.links {
if !targets.iter().any(|t| t.is_custom_build()) {
bail!(
"package `{}` specifies that it links to `{}` but does not \
have a custom build script",
pkgid,
links
)
}
}
let mut deps = Vec::new();
let mut cx = Context {
deps: &mut deps,
source_id,
nested_paths: &mut nested_paths,
config,
warnings: &mut warnings,
platform: None,
root: package_root,
};
fn process_dependencies(
cx: &mut Context<'_, '_>,
new_deps: Option<&BTreeMap<manifest::PackageName, manifest::InheritableDependency>>,
kind: Option<DepKind>,
workspace_config: &WorkspaceConfig,
inherit_cell: &LazyCell<InheritableFields>,
) -> CargoResult<Option<BTreeMap<manifest::PackageName, manifest::InheritableDependency>>> {
let Some(dependencies) = new_deps else {
return Ok(None);
};
let inheritable = || {
inherit_cell.try_borrow_with(|| {
get_ws(cx.config, &cx.root.join("Cargo.toml"), &workspace_config)
})
};
let mut deps: BTreeMap<manifest::PackageName, manifest::InheritableDependency> =
BTreeMap::new();
for (n, v) in dependencies.iter() {
let resolved = dependency_inherit_with(v.clone(), n, inheritable, cx)?;
let dep = dep_to_dependency(&resolved, n, cx, kind)?;
let name_in_toml = dep.name_in_toml().as_str();
let kind_name = match kind {
Some(k) => k.kind_table(),
None => "dependencies",
};
let table_in_toml = if let Some(platform) = &cx.platform {
format!("target.{}.{kind_name}", platform.to_string())
} else {
kind_name.to_string()
};
unused_dep_keys(name_in_toml, &table_in_toml, v.unused_keys(), cx.warnings);
cx.deps.push(dep);
deps.insert(
n.clone(),
manifest::InheritableDependency::Value(resolved.clone()),
);
}
Ok(Some(deps))
}
// Collect the dependencies.
let dependencies = process_dependencies(
&mut cx,
me.dependencies.as_ref(),
None,
&workspace_config,
&inherit_cell,
)?;
if me.dev_dependencies.is_some() && me.dev_dependencies2.is_some() {
warn_on_deprecated("dev-dependencies", package_name, "package", cx.warnings);
}
let dev_deps = me.dev_dependencies();
let dev_deps = process_dependencies(
&mut cx,
dev_deps,
Some(DepKind::Development),
&workspace_config,
&inherit_cell,
)?;
if me.build_dependencies.is_some() && me.build_dependencies2.is_some() {
warn_on_deprecated("build-dependencies", package_name, "package", cx.warnings);
}
let build_deps = me.build_dependencies();
let build_deps = process_dependencies(
&mut cx,
build_deps,
Some(DepKind::Build),
&workspace_config,
&inherit_cell,
)?;
let lints = me
.lints
.clone()
.map(|mw| lints_inherit_with(mw, || inherit()?.lints()))
.transpose()?;
let lints = verify_lints(lints)?;
let default = manifest::TomlLints::default();
let rustflags = lints_to_rustflags(lints.as_ref().unwrap_or(&default));
let mut target: BTreeMap<String, manifest::TomlPlatform> = BTreeMap::new();
for (name, platform) in me.target.iter().flatten() {
cx.platform = {
let platform: Platform = name.parse()?;
platform.check_cfg_attributes(cx.warnings);
Some(platform)
};
let deps = process_dependencies(
&mut cx,
platform.dependencies.as_ref(),
None,
&workspace_config,
&inherit_cell,
)?;
if platform.build_dependencies.is_some() && platform.build_dependencies2.is_some() {
warn_on_deprecated("build-dependencies", name, "platform target", cx.warnings);
}
let build_deps = platform.build_dependencies();
let build_deps = process_dependencies(
&mut cx,
build_deps,
Some(DepKind::Build),
&workspace_config,
&inherit_cell,
)?;
if platform.dev_dependencies.is_some() && platform.dev_dependencies2.is_some() {
warn_on_deprecated("dev-dependencies", name, "platform target", cx.warnings);
}
let dev_deps = platform.dev_dependencies();
let dev_deps = process_dependencies(
&mut cx,
dev_deps,
Some(DepKind::Development),
&workspace_config,
&inherit_cell,
)?;
target.insert(
name.clone(),
manifest::TomlPlatform {
dependencies: deps,
build_dependencies: build_deps,
build_dependencies2: None,
dev_dependencies: dev_deps,
dev_dependencies2: None,
},
);
}
let target = if target.is_empty() {
None
} else {
Some(target)
};
let replace = replace(&me, &mut cx)?;
let patch = patch(&me, &mut cx)?;
{
let mut names_sources = BTreeMap::new();
for dep in &deps {
let name = dep.name_in_toml();
let prev = names_sources.insert(name, dep.source_id());
if prev.is_some() && prev != Some(dep.source_id()) {
bail!(
"Dependency '{}' has different source paths depending on the build \
target. Each dependency must have a single canonical source path \
irrespective of build target.",
name
);
}
}
}
let exclude = package
.exclude
.clone()
.map(|mw| field_inherit_with(mw, "exclude", || inherit()?.exclude()))
.transpose()?
.unwrap_or_default();
let include = package
.include
.clone()
.map(|mw| field_inherit_with(mw, "include", || inherit()?.include()))
.transpose()?
.unwrap_or_default();
let empty_features = BTreeMap::new();
let summary = Summary::new(
pkgid,
deps,
&me.features
.as_ref()
.unwrap_or(&empty_features)
.iter()
.map(|(k, v)| {
(
InternedString::new(k),
v.iter().map(InternedString::from).collect(),
)
})
.collect(),
package.links.as_deref(),
rust_version.clone(),
)?;
let metadata = ManifestMetadata {
description: package
.description
.clone()
.map(|mw| field_inherit_with(mw, "description", || inherit()?.description()))
.transpose()?,
homepage: package
.homepage
.clone()
.map(|mw| field_inherit_with(mw, "homepage", || inherit()?.homepage()))
.transpose()?,
documentation: package
.documentation
.clone()
.map(|mw| field_inherit_with(mw, "documentation", || inherit()?.documentation()))
.transpose()?,
readme: readme_for_package(
package_root,
package
.readme
.clone()
.map(|mw| field_inherit_with(mw, "readme", || inherit()?.readme(package_root)))
.transpose()?
.as_ref(),
),
authors: package
.authors
.clone()
.map(|mw| field_inherit_with(mw, "authors", || inherit()?.authors()))
.transpose()?
.unwrap_or_default(),
license: package
.license
.clone()
.map(|mw| field_inherit_with(mw, "license", || inherit()?.license()))
.transpose()?,
license_file: package
.license_file
.clone()
.map(|mw| field_inherit_with(mw, "license", || inherit()?.license_file(package_root)))
.transpose()?,
repository: package
.repository
.clone()
.map(|mw| field_inherit_with(mw, "repository", || inherit()?.repository()))
.transpose()?,
keywords: package
.keywords
.clone()
.map(|mw| field_inherit_with(mw, "keywords", || inherit()?.keywords()))
.transpose()?
.unwrap_or_default(),
categories: package
.categories
.clone()
.map(|mw| field_inherit_with(mw, "categories", || inherit()?.categories()))
.transpose()?
.unwrap_or_default(),
badges: me
.badges
.clone()
.map(|mw| field_inherit_with(mw, "badges", || inherit()?.badges()))
.transpose()?
.unwrap_or_default(),
links: package.links.clone(),
rust_version: package
.rust_version
.map(|mw| field_inherit_with(mw, "rust-version", || inherit()?.rust_version()))
.transpose()?,
};
package.description = metadata
.description
.clone()
.map(|description| manifest::InheritableField::Value(description));
package.homepage = metadata
.homepage
.clone()
.map(|homepage| manifest::InheritableField::Value(homepage));
package.documentation = metadata
.documentation
.clone()
.map(|documentation| manifest::InheritableField::Value(documentation));
package.readme = metadata
.readme
.clone()
.map(|readme| manifest::InheritableField::Value(manifest::StringOrBool::String(readme)));
package.authors = package
.authors
.as_ref()
.map(|_| manifest::InheritableField::Value(metadata.authors.clone()));
package.license = metadata
.license
.clone()
.map(|license| manifest::InheritableField::Value(license));
package.license_file = metadata
.license_file
.clone()
.map(|license_file| manifest::InheritableField::Value(license_file));
package.repository = metadata
.repository
.clone()
.map(|repository| manifest::InheritableField::Value(repository));
package.keywords = package
.keywords
.as_ref()