-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
toml.rs
1278 lines (1150 loc) · 45.1 KB
/
toml.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 std::collections::{HashMap, HashSet};
use std::default::Default;
use std::fmt;
use std::fs;
use std::path::{Path, PathBuf};
use std::str;
use toml;
use semver::{self, VersionReq};
use rustc_serialize::{Decodable, Decoder};
use core::{SourceId, Profiles, PackageIdSpec, GitReference, WorkspaceConfig};
use core::{Summary, Manifest, Target, Dependency, DependencyInner, PackageId};
use core::{EitherManifest, VirtualManifest};
use core::dependency::{Kind, Platform};
use core::manifest::{LibKind, Profile, ManifestMetadata};
use core::package_id::Metadata;
use sources::CRATES_IO;
use util::{self, CargoResult, human, ToUrl, ToSemver, ChainError, Config};
/// Representation of the projects file layout.
///
/// This structure is used to hold references to all project files that are relevant to cargo.
#[derive(Clone)]
pub struct Layout {
pub root: PathBuf,
lib: Option<PathBuf>,
bins: Vec<PathBuf>,
examples: Vec<PathBuf>,
tests: Vec<PathBuf>,
benches: Vec<PathBuf>,
}
impl Layout {
/// Returns a new `Layout` for a given root path.
/// The `root_path` represents the directory that contains the `Cargo.toml` file.
pub fn from_project_path(root_path: &Path) -> Layout {
let mut lib = None;
let mut bins = vec![];
let mut examples = vec![];
let mut tests = vec![];
let mut benches = vec![];
let lib_canidate = root_path.join("src").join("lib.rs");
if fs::metadata(&lib_canidate).is_ok() {
lib = Some(lib_canidate);
}
try_add_file(&mut bins, root_path.join("src").join("main.rs"));
try_add_files(&mut bins, root_path.join("src").join("bin"));
try_add_files(&mut examples, root_path.join("examples"));
try_add_files(&mut tests, root_path.join("tests"));
try_add_files(&mut benches, root_path.join("benches"));
Layout {
root: root_path.to_path_buf(),
lib: lib,
bins: bins,
examples: examples,
tests: tests,
benches: benches,
}
}
fn main(&self) -> Option<&PathBuf> {
self.bins.iter().find(|p| {
match p.file_name().and_then(|s| s.to_str()) {
Some(s) => s == "main.rs",
None => false
}
})
}
}
fn try_add_file(files: &mut Vec<PathBuf>, file: PathBuf) {
if fs::metadata(&file).is_ok() {
files.push(file);
}
}
fn try_add_files(files: &mut Vec<PathBuf>, root: PathBuf) {
match fs::read_dir(&root) {
Ok(new) => {
files.extend(new.filter_map(|dir| {
dir.map(|d| d.path()).ok()
}).filter(|f| {
f.extension().and_then(|s| s.to_str()) == Some("rs")
}).filter(|f| {
// Some unix editors may create "dotfiles" next to original
// source files while they're being edited, but these files are
// rarely actually valid Rust source files and sometimes aren't
// even valid UTF-8. Here we just ignore all of them and require
// that they are explicitly specified in Cargo.toml if desired.
f.file_name().and_then(|s| s.to_str()).map(|s| {
!s.starts_with('.')
}).unwrap_or(true)
}))
}
Err(_) => {/* just don't add anything if the directory doesn't exist, etc. */}
}
}
pub fn to_manifest(contents: &str,
source_id: &SourceId,
layout: Layout,
config: &Config)
-> CargoResult<(EitherManifest, Vec<PathBuf>)> {
let manifest = layout.root.join("Cargo.toml");
let manifest = match util::without_prefix(&manifest, config.cwd()) {
Some(path) => path.to_path_buf(),
None => manifest.clone(),
};
let root = try!(parse(contents, &manifest, config));
let mut d = toml::Decoder::new(toml::Value::Table(root));
let manifest: TomlManifest = try!(Decodable::decode(&mut d).map_err(|e| {
human(e.to_string())
}));
return match manifest.to_real_manifest(source_id, &layout, config) {
Ok((mut manifest, paths)) => {
if let Some(ref toml) = d.toml {
add_unused_keys(&mut manifest, toml, String::new());
}
if !manifest.targets().iter().any(|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))
}
Err(e) => {
match manifest.to_virtual_manifest(source_id, &layout, config) {
Ok((m, paths)) => Ok((EitherManifest::Virtual(m), paths)),
Err(..) => Err(e),
}
}
};
fn add_unused_keys(m: &mut Manifest, toml: &toml::Value, key: String) {
if key == "package.metadata" {
return
}
match *toml {
toml::Value::Table(ref table) => {
for (k, v) in table.iter() {
add_unused_keys(m, v, if key.is_empty() {
k.clone()
} else {
key.clone() + "." + k
})
}
}
toml::Value::Array(ref arr) => {
for v in arr.iter() {
add_unused_keys(m, v, key.clone());
}
}
_ => m.add_warning(format!("unused manifest key: {}", key)),
}
}
}
pub fn parse(toml: &str,
file: &Path,
config: &Config) -> CargoResult<toml::Table> {
let mut first_parser = toml::Parser::new(&toml);
if let Some(toml) = first_parser.parse() {
return Ok(toml);
}
let mut second_parser = toml::Parser::new(toml);
second_parser.set_require_newline_after_table(false);
if let Some(toml) = second_parser.parse() {
let msg = format!("\
TOML file found which contains invalid syntax and will soon not parse
at `{}`.
The TOML spec requires newlines after table definitions (e.g. `[a] b = 1` is
invalid), but this file has a table header which does not have a newline after
it. A newline needs to be added and this warning will soon become a hard error
in the future.", file.display());
try!(config.shell().warn(&msg));
return Ok(toml)
}
let mut error_str = format!("could not parse input as TOML\n");
for error in first_parser.errors.iter() {
let (loline, locol) = first_parser.to_linecol(error.lo);
let (hiline, hicol) = first_parser.to_linecol(error.hi);
error_str.push_str(&format!("{}:{}:{}{} {}\n",
file.display(),
loline + 1, locol + 1,
if loline != hiline || locol != hicol {
format!("-{}:{}", hiline + 1,
hicol + 1)
} else {
"".to_string()
},
error.desc));
}
Err(human(error_str))
}
type TomlLibTarget = TomlTarget;
type TomlBinTarget = TomlTarget;
type TomlExampleTarget = TomlTarget;
type TomlTestTarget = TomlTarget;
type TomlBenchTarget = TomlTarget;
#[derive(RustcDecodable)]
pub enum TomlDependency {
Simple(String),
Detailed(DetailedTomlDependency)
}
#[derive(RustcDecodable, Clone, Default)]
pub struct DetailedTomlDependency {
version: Option<String>,
path: Option<String>,
git: Option<String>,
branch: Option<String>,
tag: Option<String>,
rev: Option<String>,
features: Option<Vec<String>>,
optional: Option<bool>,
default_features: Option<bool>,
}
#[derive(RustcDecodable)]
pub struct TomlManifest {
package: Option<Box<TomlProject>>,
project: Option<Box<TomlProject>>,
profile: Option<TomlProfiles>,
lib: Option<TomlLibTarget>,
bin: Option<Vec<TomlBinTarget>>,
example: Option<Vec<TomlExampleTarget>>,
test: Option<Vec<TomlTestTarget>>,
bench: Option<Vec<TomlTestTarget>>,
dependencies: Option<HashMap<String, TomlDependency>>,
dev_dependencies: Option<HashMap<String, TomlDependency>>,
build_dependencies: Option<HashMap<String, TomlDependency>>,
features: Option<HashMap<String, Vec<String>>>,
target: Option<HashMap<String, TomlPlatform>>,
replace: Option<HashMap<String, TomlDependency>>,
workspace: Option<TomlWorkspace>,
}
#[derive(RustcDecodable, Clone, Default)]
pub struct TomlProfiles {
test: Option<TomlProfile>,
doc: Option<TomlProfile>,
bench: Option<TomlProfile>,
dev: Option<TomlProfile>,
release: Option<TomlProfile>,
}
#[derive(Clone)]
pub struct TomlOptLevel(String);
impl Decodable for TomlOptLevel {
fn decode<D: Decoder>(d: &mut D) -> Result<TomlOptLevel, D::Error> {
match d.read_u32() {
Ok(i) => Ok(TomlOptLevel(i.to_string())),
Err(_) => {
match d.read_str() {
Ok(ref s) if s == "s" || s == "z" =>
Ok(TomlOptLevel(s.to_string())),
Ok(_) | Err(_) =>
Err(d.error("expected an integer, a string \"z\" or a string \"s\""))
}
}
}
}
}
#[derive(RustcDecodable, Clone, Default)]
pub struct TomlProfile {
opt_level: Option<TomlOptLevel>,
lto: Option<bool>,
codegen_units: Option<u32>,
debug: Option<bool>,
debug_assertions: Option<bool>,
rpath: Option<bool>,
panic: Option<String>,
}
#[derive(RustcDecodable)]
pub struct TomlProject {
name: String,
version: TomlVersion,
authors: Vec<String>,
build: Option<String>,
links: Option<String>,
exclude: Option<Vec<String>>,
include: Option<Vec<String>>,
publish: Option<bool>,
workspace: Option<String>,
// package metadata
description: Option<String>,
homepage: Option<String>,
documentation: Option<String>,
readme: Option<String>,
keywords: Option<Vec<String>>,
license: Option<String>,
license_file: Option<String>,
repository: Option<String>,
}
#[derive(RustcDecodable)]
pub struct TomlWorkspace {
members: Option<Vec<String>>,
}
pub struct TomlVersion {
version: semver::Version,
}
impl Decodable for TomlVersion {
fn decode<D: Decoder>(d: &mut D) -> Result<TomlVersion, D::Error> {
let s = try!(d.read_str());
match s.to_semver() {
Ok(s) => Ok(TomlVersion { version: s }),
Err(e) => Err(d.error(&e)),
}
}
}
impl TomlProject {
pub fn to_package_id(&self, source_id: &SourceId) -> CargoResult<PackageId> {
PackageId::new(&self.name, self.version.version.clone(),
source_id)
}
}
struct Context<'a, 'b> {
pkgid: Option<&'a PackageId>,
deps: &'a mut Vec<Dependency>,
source_id: &'a SourceId,
nested_paths: &'a mut Vec<PathBuf>,
config: &'b Config,
warnings: &'a mut Vec<String>,
platform: Option<Platform>,
layout: &'a Layout,
}
// These functions produce the equivalent of specific manifest entries. One
// wrinkle is that certain paths cannot be represented in the manifest due
// to Toml's UTF-8 requirement. This could, in theory, mean that certain
// otherwise acceptable executable names are not used when inside of
// `src/bin/*`, but it seems ok to not build executables with non-UTF8
// paths.
fn inferred_lib_target(name: &str, layout: &Layout) -> Option<TomlTarget> {
layout.lib.as_ref().map(|lib| {
TomlTarget {
name: Some(name.to_string()),
path: Some(PathValue::Path(lib.clone())),
.. TomlTarget::new()
}
})
}
fn inferred_bin_targets(name: &str, layout: &Layout) -> Vec<TomlTarget> {
layout.bins.iter().filter_map(|bin| {
let name = if &**bin == Path::new("src/main.rs") ||
*bin == layout.root.join("src").join("main.rs") {
Some(name.to_string())
} else {
bin.file_stem().and_then(|s| s.to_str()).map(|f| f.to_string())
};
name.map(|name| {
TomlTarget {
name: Some(name),
path: Some(PathValue::Path(bin.clone())),
.. TomlTarget::new()
}
})
}).collect()
}
fn inferred_example_targets(layout: &Layout) -> Vec<TomlTarget> {
layout.examples.iter().filter_map(|ex| {
ex.file_stem().and_then(|s| s.to_str()).map(|name| {
TomlTarget {
name: Some(name.to_string()),
path: Some(PathValue::Path(ex.clone())),
.. TomlTarget::new()
}
})
}).collect()
}
fn inferred_test_targets(layout: &Layout) -> Vec<TomlTarget> {
layout.tests.iter().filter_map(|ex| {
ex.file_stem().and_then(|s| s.to_str()).map(|name| {
TomlTarget {
name: Some(name.to_string()),
path: Some(PathValue::Path(ex.clone())),
.. TomlTarget::new()
}
})
}).collect()
}
fn inferred_bench_targets(layout: &Layout) -> Vec<TomlTarget> {
layout.benches.iter().filter_map(|ex| {
ex.file_stem().and_then(|s| s.to_str()).map(|name| {
TomlTarget {
name: Some(name.to_string()),
path: Some(PathValue::Path(ex.clone())),
.. TomlTarget::new()
}
})
}).collect()
}
impl TomlManifest {
fn to_real_manifest(&self,
source_id: &SourceId,
layout: &Layout,
config: &Config)
-> CargoResult<(Manifest, Vec<PathBuf>)> {
let mut nested_paths = vec![];
let mut warnings = vec![];
let project = self.project.as_ref().or_else(|| self.package.as_ref());
let project = try!(project.chain_error(|| {
human("no `package` or `project` section found.")
}));
if project.name.trim().is_empty() {
bail!("package name cannot be an empty string.")
}
let pkgid = try!(project.to_package_id(source_id));
let metadata = pkgid.generate_metadata();
// 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 package name
let lib = match self.lib {
Some(ref lib) => {
try!(lib.validate_library_name());
try!(lib.validate_crate_type());
Some(
TomlTarget {
name: lib.name.clone().or(Some(project.name.clone())),
path: lib.path.clone().or(
layout.lib.as_ref().map(|p| PathValue::Path(p.clone()))
),
..lib.clone()
}
)
}
None => inferred_lib_target(&project.name, layout),
};
let bins = match self.bin {
Some(ref bins) => {
let bin = layout.main();
for target in bins {
try!(target.validate_binary_name());
}
bins.iter().map(|t| {
if bin.is_some() && t.path.is_none() {
TomlTarget {
path: bin.as_ref().map(|&p| PathValue::Path(p.clone())),
.. t.clone()
}
} else {
t.clone()
}
}).collect()
}
None => inferred_bin_targets(&project.name, layout)
};
let blacklist = vec!["build", "deps", "examples", "native"];
for bin in bins.iter() {
if blacklist.iter().find(|&x| *x == bin.name()) != None {
bail!("the binary target name `{}` is forbidden",
bin.name())
}
}
let examples = match self.example {
Some(ref examples) => {
for target in examples {
try!(target.validate_example_name());
}
examples.clone()
}
None => inferred_example_targets(layout)
};
let tests = match self.test {
Some(ref tests) => {
for target in tests {
try!(target.validate_test_name());
}
tests.clone()
}
None => inferred_test_targets(layout)
};
let benches = match self.bench {
Some(ref benches) => {
for target in benches {
try!(target.validate_bench_name());
}
benches.clone()
}
None => inferred_bench_targets(layout)
};
if let Err(e) = unique_names_in_targets(&bins) {
bail!("found duplicate binary name {}, but all binary targets \
must have a unique name", e);
}
if let Err(e) = unique_names_in_targets(&examples) {
bail!("found duplicate example name {}, but all binary targets \
must have a unique name", e);
}
if let Err(e) = unique_names_in_targets(&benches) {
bail!("found duplicate bench name {}, but all binary targets must \
have a unique name", e);
}
if let Err(e) = unique_names_in_targets(&tests) {
bail!("found duplicate test name {}, but all binary targets must \
have a unique name", e)
}
// processing the custom build script
let new_build = project.build.as_ref().map(PathBuf::from);
// Get targets
let targets = normalize(&lib,
&bins,
new_build,
&examples,
&tests,
&benches,
&metadata);
if targets.is_empty() {
debug!("manifest has no build targets");
}
if let Err(e) = unique_build_targets(&targets, layout) {
warnings.push(format!("file found to be present in multiple \
build targets: {}", e));
}
let mut deps = Vec::new();
let replace;
{
let mut cx = Context {
pkgid: Some(&pkgid),
deps: &mut deps,
source_id: source_id,
nested_paths: &mut nested_paths,
config: config,
warnings: &mut warnings,
platform: None,
layout: &layout,
};
fn process_dependencies(
cx: &mut Context,
new_deps: Option<&HashMap<String, TomlDependency>>,
kind: Option<Kind>)
-> CargoResult<()>
{
let dependencies = match new_deps {
Some(ref dependencies) => dependencies,
None => return Ok(())
};
for (n, v) in dependencies.iter() {
let dep = try!(v.to_dependency(n, cx, kind));
cx.deps.push(dep);
}
Ok(())
}
// Collect the deps
try!(process_dependencies(&mut cx, self.dependencies.as_ref(),
None));
try!(process_dependencies(&mut cx, self.dev_dependencies.as_ref(),
Some(Kind::Development)));
try!(process_dependencies(&mut cx, self.build_dependencies.as_ref(),
Some(Kind::Build)));
for (name, platform) in self.target.iter().flat_map(|t| t) {
cx.platform = Some(try!(name.parse()));
try!(process_dependencies(&mut cx,
platform.dependencies.as_ref(),
None));
try!(process_dependencies(&mut cx,
platform.build_dependencies.as_ref(),
Some(Kind::Build)));
try!(process_dependencies(&mut cx,
platform.dev_dependencies.as_ref(),
Some(Kind::Development)));
}
replace = try!(self.replace(&mut cx));
}
{
let mut names_sources = HashMap::new();
for dep in deps.iter() {
let name = dep.name();
let prev = names_sources.insert(name, dep.source_id());
if prev.is_some() && prev != Some(dep.source_id()) {
bail!("found duplicate dependency name {}, but all \
dependencies must have a unique name", name);
}
}
}
let exclude = project.exclude.clone().unwrap_or(Vec::new());
let include = project.include.clone().unwrap_or(Vec::new());
let summary = try!(Summary::new(pkgid, deps,
self.features.clone()
.unwrap_or(HashMap::new())));
let metadata = ManifestMetadata {
description: project.description.clone(),
homepage: project.homepage.clone(),
documentation: project.documentation.clone(),
readme: project.readme.clone(),
authors: project.authors.clone(),
license: project.license.clone(),
license_file: project.license_file.clone(),
repository: project.repository.clone(),
keywords: project.keywords.clone().unwrap_or(Vec::new()),
};
let workspace_config = match (self.workspace.as_ref(),
project.workspace.as_ref()) {
(Some(config), None) => {
WorkspaceConfig::Root { members: config.members.clone() }
}
(None, root) => {
WorkspaceConfig::Member { root: root.cloned() }
}
(Some(..), Some(..)) => {
bail!("cannot configure both `package.workspace` and \
`[workspace]`, only one can be specified")
}
};
let profiles = build_profiles(&self.profile);
let publish = project.publish.unwrap_or(true);
let mut manifest = Manifest::new(summary,
targets,
exclude,
include,
project.links.clone(),
metadata,
profiles,
publish,
replace,
workspace_config);
if project.license_file.is_some() && project.license.is_some() {
manifest.add_warning("only one of `license` or \
`license-file` is necessary".to_string());
}
for warning in warnings {
manifest.add_warning(warning.clone());
}
Ok((manifest, nested_paths))
}
fn to_virtual_manifest(&self,
source_id: &SourceId,
layout: &Layout,
config: &Config)
-> CargoResult<(VirtualManifest, Vec<PathBuf>)> {
if self.project.is_some() {
bail!("virtual manifests do not define [project]");
}
if self.package.is_some() {
bail!("virtual manifests do not define [package]");
}
if self.lib.is_some() {
bail!("virtual manifests do not specifiy [lib]");
}
if self.bin.is_some() {
bail!("virtual manifests do not specifiy [[bin]]");
}
if self.example.is_some() {
bail!("virtual manifests do not specifiy [[example]]");
}
if self.test.is_some() {
bail!("virtual manifests do not specifiy [[test]]");
}
if self.bench.is_some() {
bail!("virtual manifests do not specifiy [[bench]]");
}
let mut nested_paths = Vec::new();
let mut warnings = Vec::new();
let mut deps = Vec::new();
let replace = try!(self.replace(&mut Context {
pkgid: None,
deps: &mut deps,
source_id: source_id,
nested_paths: &mut nested_paths,
config: config,
warnings: &mut warnings,
platform: None,
layout: layout,
}));
let profiles = build_profiles(&self.profile);
let workspace_config = match self.workspace {
Some(ref config) => {
WorkspaceConfig::Root { members: config.members.clone() }
}
None => {
bail!("virtual manifests must be configured with [workspace]");
}
};
Ok((VirtualManifest::new(replace, workspace_config, profiles), nested_paths))
}
fn replace(&self, cx: &mut Context)
-> CargoResult<Vec<(PackageIdSpec, Dependency)>> {
let mut replace = Vec::new();
for (spec, replacement) in self.replace.iter().flat_map(|x| x) {
let mut spec = try!(PackageIdSpec::parse(spec).chain_error(|| {
human(format!("replacements must specify a valid semver \
version to replace, but `{}` does not",
spec))
}));
if spec.url().is_none() {
spec.set_url(CRATES_IO.parse().unwrap());
}
let version_specified = match *replacement {
TomlDependency::Detailed(ref d) => d.version.is_some(),
TomlDependency::Simple(..) => true,
};
if version_specified {
bail!("replacements cannot specify a version \
requirement, but found one for `{}`", spec);
}
let dep = try!(replacement.to_dependency(spec.name(), cx, None));
let dep = {
let version = try!(spec.version().chain_error(|| {
human(format!("replacements must specify a version \
to replace, but `{}` does not",
spec))
}));
let req = VersionReq::exact(version);
dep.clone_inner().set_version_req(req)
.into_dependency()
};
replace.push((spec, dep));
}
Ok(replace)
}
}
/// Will check a list of toml targets, and make sure the target names are unique within a vector.
/// If not, the name of the offending binary target is returned.
fn unique_names_in_targets(targets: &[TomlTarget]) -> Result<(), String> {
let mut seen = HashSet::new();
for v in targets.iter().map(|e| e.name()) {
if !seen.insert(v.clone()) {
return Err(v);
}
}
Ok(())
}
/// Will check a list of build targets, and make sure the target names are unique within a vector.
/// If not, the name of the offending build target is returned.
fn unique_build_targets(targets: &[Target], layout: &Layout) -> Result<(), String> {
let mut seen = HashSet::new();
for v in targets.iter().map(|e| layout.root.join(e.src_path())) {
if !seen.insert(v.clone()) {
return Err(v.display().to_string());
}
}
Ok(())
}
impl TomlDependency {
fn to_dependency(&self,
name: &str,
cx: &mut Context,
kind: Option<Kind>)
-> CargoResult<Dependency> {
let details = match *self {
TomlDependency::Simple(ref version) => DetailedTomlDependency {
version: Some(version.clone()),
.. Default::default()
},
TomlDependency::Detailed(ref details) => details.clone(),
};
if details.version.is_none() && details.path.is_none() &&
details.git.is_none() {
let msg = format!("dependency ({}) specified without \
providing a local path, Git repository, or \
version to use. This will be considered an \
error in future versions", name);
cx.warnings.push(msg);
}
if details.git.is_none() {
let git_only_keys = [
(&details.branch, "branch"),
(&details.tag, "tag"),
(&details.rev, "rev")
];
for &(key, key_name) in git_only_keys.iter() {
if key.is_some() {
let msg = format!("key `{}` is ignored for dependency ({}). \
This will be considered an error in future versions",
key_name, name);
cx.warnings.push(msg)
}
}
}
let new_source_id = match (details.git.as_ref(), details.path.as_ref()) {
(Some(git), maybe_path) => {
if maybe_path.is_some() {
let msg = format!("dependency ({}) specification is ambiguous. \
Only one of `git` or `path` is allowed. \
This will be considered an error in future versions", name);
cx.warnings.push(msg)
}
let n_details = [&details.branch, &details.tag, &details.rev]
.iter()
.filter(|d| d.is_some())
.count();
if n_details > 1 {
let msg = format!("dependency ({}) specification is ambiguous. \
Only one of `branch`, `tag` or `rev` is allowed. \
This will be considered an error in future versions", name);
cx.warnings.push(msg)
}
let reference = details.branch.clone().map(GitReference::Branch)
.or_else(|| details.tag.clone().map(GitReference::Tag))
.or_else(|| details.rev.clone().map(GitReference::Rev))
.unwrap_or_else(|| GitReference::Branch("master".to_string()));
let loc = try!(git.to_url());
SourceId::for_git(&loc, reference)
},
(None, Some(path)) => {
cx.nested_paths.push(PathBuf::from(path));
// If the source id for the package we're parsing is a path
// source, then we normalize the path here to get rid of
// components like `..`.
//
// The purpose of this is to get a canonical id for the package
// that we're depending on to ensure that builds of this package
// always end up hashing to the same value no matter where it's
// built from.
if cx.source_id.is_path() {
let path = cx.layout.root.join(path);
let path = util::normalize_path(&path);
try!(SourceId::for_path(&path))
} else {
cx.source_id.clone()
}
},
(None, None) => try!(SourceId::crates_io(cx.config)),
};
let version = details.version.as_ref().map(|v| &v[..]);
let mut dep = match cx.pkgid {
Some(id) => {
try!(DependencyInner::parse(name, version, &new_source_id,
Some((id, cx.config))))
}
None => try!(DependencyInner::parse(name, version, &new_source_id, None)),
};
dep = dep.set_features(details.features.unwrap_or(Vec::new()))
.set_default_features(details.default_features.unwrap_or(true))
.set_optional(details.optional.unwrap_or(false))
.set_platform(cx.platform.clone());
if let Some(kind) = kind {
dep = dep.set_kind(kind);
}
Ok(dep.into_dependency())
}
}
#[derive(RustcDecodable, Debug, Clone)]
struct TomlTarget {
name: Option<String>,
crate_type: Option<Vec<String>>,
path: Option<PathValue>,
test: Option<bool>,
doctest: Option<bool>,
bench: Option<bool>,
doc: Option<bool>,
plugin: Option<bool>,
proc_macro: Option<bool>,
harness: Option<bool>,
}
#[derive(RustcDecodable, Clone)]
enum PathValue {
String(String),
Path(PathBuf),
}
/// Corresponds to a `target` entry, but `TomlTarget` is already used.
#[derive(RustcDecodable)]
struct TomlPlatform {
dependencies: Option<HashMap<String, TomlDependency>>,
build_dependencies: Option<HashMap<String, TomlDependency>>,
dev_dependencies: Option<HashMap<String, TomlDependency>>,
}
impl TomlTarget {
fn new() -> TomlTarget {
TomlTarget {
name: None,
crate_type: None,
path: None,
test: None,
doctest: None,
bench: None,
doc: None,
plugin: None,
proc_macro: None,
harness: None,
}
}
fn name(&self) -> String {
match self.name {
Some(ref name) => name.clone(),
None => panic!("target name is required")
}
}
fn validate_library_name(&self) -> CargoResult<()> {
match self.name {
Some(ref name) => {
if name.trim().is_empty() {
Err(human("library target names cannot be empty.".to_string()))
} else if name.contains('-') {
Err(human(format!("library target names cannot contain hyphens: {}",
name)))
} else {
Ok(())
}
},
None => Ok(())
}
}
fn validate_binary_name(&self) -> CargoResult<()> {
match self.name {
Some(ref name) => {
if name.trim().is_empty() {
Err(human("binary target names cannot be empty.".to_string()))
} else {
Ok(())
}
},
None => Err(human("binary target bin.name is required".to_string()))
}
}
fn validate_example_name(&self) -> CargoResult<()> {
match self.name {
Some(ref name) => {
if name.trim().is_empty() {
Err(human("example target names cannot be empty".to_string()))
} else {
Ok(())
}
},