-
Notifications
You must be signed in to change notification settings - Fork 37
/
main.rs
1678 lines (1441 loc) · 54.1 KB
/
main.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
/*
Copyright ⓒ 2015-2017 cargo-script contributors.
Licensed under the MIT license (see LICENSE or <http://opensource.org
/licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
<http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
files in the project carrying such notice may not be copied, modified,
or distributed except according to those terms.
*/
/*!
`cargo-script` is a Cargo subcommand designed to let people quickly and easily run Rust "scripts" which can make use of Cargo's package ecosystem.
Or, to put it in other words, it lets you write useful, but small, Rust programs without having to create a new directory and faff about with `Cargo.toml`.
As such, `cargo-script` does two major things:
1. Given a script, it extracts the embedded Cargo manifest and merges it with some sensible defaults. This manifest, along with the source code, is written to a fresh Cargo package on-disk.
2. It caches the generated and compiled packages, regenerating them only if the script or its metadata have changed.
*/
extern crate clap;
extern crate env_logger;
#[macro_use] extern crate lazy_static;
#[macro_use] extern crate log;
extern crate open;
extern crate regex;
extern crate rustc_serialize;
extern crate semver;
extern crate shaman;
extern crate toml;
#[cfg(feature="chan")]
#[macro_use] extern crate chan;
/**
If this is set to `true`, the digests used for package IDs will be replaced with "stub" to make testing a bit easier. Obviously, you don't want this `true` for release...
*/
const STUB_HASHES: bool = false;
/**
If this is set to `false`, then code that automatically deletes stuff *won't*.
*/
const ALLOW_AUTO_REMOVE: bool = true;
/**
Length of time to suppress Cargo output.
*/
#[cfg(feature="suppress-cargo-output")]
const CARGO_OUTPUT_TIMEOUT: u64 = 2_000/*ms*/;
// This macro exists for 1.11 support.
#[cfg(windows)]
macro_rules! if_windows {
(@as_expr $e:expr) => { $e };
($($tts:tt)*) => { if_windows! { @as_expr { $($tts)* } } };
}
#[cfg(not(windows))]
macro_rules! if_windows {
($($tts:tt)*) => { {} };
}
mod consts;
mod error;
mod manifest;
mod platform;
mod templates;
mod util;
#[cfg(windows)]
mod file_assoc;
#[cfg(not(windows))]
mod file_assoc {}
use std::borrow::Cow;
use std::error::Error;
use std::ffi::OsString;
use std::fs;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::process::{self, Command};
use semver::Version;
use error::{Blame, MainError, Result, ResultExt};
use platform::MigrationKind;
use util::{ChainMap, Defer, PathExt};
#[derive(Debug)]
enum SubCommand {
Script(Args),
Templates(templates::Args),
#[cfg(windows)]
FileAssoc(file_assoc::Args),
}
#[derive(Debug)]
struct Args {
script: Option<String>,
args: Vec<String>,
features: Option<String>,
expr: bool,
loop_: bool,
count: bool,
pkg_path: Option<String>,
gen_pkg_only: bool,
build_only: bool,
clear_cache: bool,
debug: bool,
dep: Vec<String>,
dep_extern: Vec<String>,
extern_: Vec<String>,
force: bool,
unstable_features: Vec<String>,
use_bincache: Option<bool>,
migrate_data: Option<MigrationKind>,
build_kind: BuildKind,
template: Option<String>,
}
#[derive(Copy, Clone, Debug)]
enum BuildKind {
Normal,
Test,
Bench,
}
impl BuildKind {
fn can_exec_directly(&self) -> bool {
match *self {
BuildKind::Normal => true,
BuildKind::Test | BuildKind::Bench => false,
}
}
fn exec_command(&self) -> &'static str {
match *self {
BuildKind::Normal => panic!("asked for exec command for normal build"),
BuildKind::Test => "test",
BuildKind::Bench => "bench",
}
}
fn from_flags(test: bool, bench: bool) -> Self {
match (test, bench) {
(false, false) => BuildKind::Normal,
(true, false) => BuildKind::Test,
(false, true) => BuildKind::Bench,
_ => panic!("got both test and bench")
}
}
}
fn parse_args() -> SubCommand {
use clap::{App, Arg, ArgGroup, SubCommand, AppSettings};
let version = option_env!("CARGO_PKG_VERSION").unwrap_or("unknown");
let about = r#"Compiles and runs "Cargoified Rust scripts"."#;
// "const str array slice"
macro_rules! csas {
($($es:expr),*) => {
{
const PIN: &'static [&'static str] = &[$($es),*];
PIN
}
}
}
// We have to kinda lie about who we are for the output to look right...
let m = App::new("cargo")
.bin_name("cargo")
.version(version)
.about(about)
.setting(AppSettings::SubcommandRequiredElseHelp)
.subcommand(SubCommand::with_name("script")
.version(version)
.about(about)
.usage("cargo script [FLAGS OPTIONS] [--] <script> <args>...")
/*
Major script modes.
*/
.arg(Arg::with_name("script")
.help("Script file (with or without extension) to execute.")
.index(1)
)
.arg(Arg::with_name("args")
.help("Additional arguments passed to the script.")
.index(2)
.multiple(true)
)
.arg(Arg::with_name("expr")
.help("Execute <script> as a literal expression and display the result.")
.long("expr")
.short("e")
.conflicts_with_all(csas!["loop"])
.requires("script")
)
.arg(Arg::with_name("loop")
.help("Execute <script> as a literal closure once for each line from stdin.")
.long("loop")
.short("l")
.conflicts_with_all(csas!["expr"])
.requires("script")
)
.group(ArgGroup::with_name("expr_or_loop")
.args(&["expr", "loop"])
)
/*
Options that impact the script being executed.
*/
.arg(Arg::with_name("count")
.help("Invoke the loop closure with two arguments: line, and line number.")
.long("count")
.requires("loop")
)
.arg(Arg::with_name("debug")
.help("Build a debug executable, not an optimised one.")
.long("debug")
.requires("script")
)
.arg(Arg::with_name("dep")
.help("Add an additional Cargo dependency. Each SPEC can be either just the package name (which will assume the latest version) or a full `name=version` spec.")
.long("dep")
.short("d")
.takes_value(true)
.multiple(true)
.number_of_values(1)
.requires("script")
)
.arg(Arg::with_name("dep_extern")
.help("Like `dep`, except that it *also* adds a `#[macro_use] extern crate name;` item for expression and loop scripts. Note that this only works if the name of the dependency and the name of the library it generates are exactly the same.")
.long("dep-extern")
.short("D")
.takes_value(true)
.multiple(true)
.requires("expr_or_loop")
)
.arg(Arg::with_name("extern")
.help("Adds an `#[macro_use] extern crate name;` item for expressions and loop scripts.")
.long("extern")
.short("x")
.takes_value(true)
.multiple(true)
.requires("expr_or_loop")
)
.arg(Arg::with_name("features")
.help("Cargo features to pass when building and running.")
.long("features")
.takes_value(true)
)
.arg(Arg::with_name("unstable_features")
.help("Add a #![feature] declaration to the crate.")
.long("unstable-feature")
.short("u")
.takes_value(true)
.multiple(true)
.requires("expr_or_loop")
)
/*
Options that change how cargo script itself behaves, and don't alter what the script will do.
*/
.arg(Arg::with_name("build_only")
.help("Build the script, but don't run it.")
.long("build-only")
.requires("script")
.conflicts_with_all(csas!["args"])
)
.arg(Arg::with_name("clear_cache")
.help("Clears out the script cache.")
.long("clear-cache")
)
.arg(Arg::with_name("force")
.help("Force the script to be rebuilt.")
.long("force")
.requires("script")
)
.arg(Arg::with_name("gen_pkg_only")
.help("Generate the Cargo package, but don't compile or run it.")
.long("gen-pkg-only")
.requires("script")
.conflicts_with_all(csas!["args", "build_only", "debug", "force", "test", "bench"])
)
.arg(Arg::with_name("pkg_path")
.help("Specify where to place the generated Cargo package.")
.long("pkg-path")
.takes_value(true)
.requires("script")
.conflicts_with_all(csas!["clear_cache", "force"])
)
.arg(Arg::with_name("use_bincache")
.help("Override whether or not the shared binary cache will be used for compilation.")
.long("use-shared-binary-cache")
.takes_value(true)
.possible_values(csas!["no", "yes"])
)
.arg(Arg::with_name("migrate_data")
.help("Migrate data from older versions.")
.long("migrate-data")
.takes_value(true)
.possible_values(csas!["dry-run", "for-real"])
)
.arg(Arg::with_name("test")
.help("Compile and run tests.")
.long("test")
.conflicts_with_all(csas!["bench", "debug", "args", "force"])
)
.arg(Arg::with_name("bench")
.help("Compile and run benchmarks. Requires a nightly toolchain.")
.long("bench")
.conflicts_with_all(csas!["test", "debug", "args", "force"])
)
.arg(Arg::with_name("template")
.help("Specify a template to use for expression scripts.")
.long("template")
.short("t")
.takes_value(true)
.requires("expr")
)
)
.subcommand(templates::Args::subcommand())
.chain_map(|mut app| {
drop(&mut app); // avoid warning
if_windows! {
app = app.subcommand(file_assoc::Args::subcommand());
}
app
})
.get_matches();
if let Some(m) = m.subcommand_matches("templates") {
return ::SubCommand::Templates(templates::Args::parse(m));
}
if_windows! {
if let Some(m) = m.subcommand_matches("file-association") {
return ::SubCommand::FileAssoc(file_assoc::Args::parse(m));
}
}
let m = m.subcommand_matches("script").unwrap();
fn owned_vec_string<'a, I>(v: Option<I>) -> Vec<String>
where I: ::std::iter::Iterator<Item=&'a str> {
v.map(|itr| itr.map(Into::into).collect()).unwrap_or(vec![])
}
fn yes_or_no(v: Option<&str>) -> Option<bool> {
v.map(|v| match v {
"yes" => true,
"no" => false,
_ => unreachable!()
})
}
fn run_kind(v: Option<&str>) -> Option<MigrationKind> {
v.map(|v| match v {
"dry-run" => MigrationKind::DryRun,
"for-real" => MigrationKind::ForReal,
_ => unreachable!()
})
}
::SubCommand::Script(Args {
script: m.value_of("script").map(Into::into),
args: owned_vec_string(m.values_of("args")),
features: m.value_of("features").map(Into::into),
expr: m.is_present("expr"),
loop_: m.is_present("loop"),
count: m.is_present("count"),
pkg_path: m.value_of("pkg_path").map(Into::into),
gen_pkg_only: m.is_present("gen_pkg_only"),
build_only: m.is_present("build_only"),
clear_cache: m.is_present("clear_cache"),
debug: m.is_present("debug"),
dep: owned_vec_string(m.values_of("dep")),
dep_extern: owned_vec_string(m.values_of("dep_extern")),
extern_: owned_vec_string(m.values_of("extern")),
force: m.is_present("force"),
unstable_features: owned_vec_string(m.values_of("unstable_features")),
use_bincache: yes_or_no(m.value_of("use_bincache")),
migrate_data: run_kind(m.value_of("migrate_data")),
build_kind: BuildKind::from_flags(m.is_present("test"), m.is_present("bench")),
template: m.value_of("template").map(Into::into),
})
}
fn main() {
env_logger::init().unwrap();
info!("starting");
info!("args: {:?}", std::env::args().collect::<Vec<_>>());
let stderr = &mut std::io::stderr();
match try_main() {
Ok(0) => (),
Ok(code) => {
std::process::exit(code);
},
Err(ref err) if err.is_human() => {
writeln!(stderr, "error: {}", err).unwrap();
std::process::exit(1);
},
Err(ref err) => {
writeln!(stderr, "internal error: {}", err).unwrap();
std::process::exit(1);
}
}
}
fn try_main() -> Result<i32> {
let args = parse_args();
info!("Arguments: {:?}", args);
let args = match args {
SubCommand::Script(args) => args,
SubCommand::Templates(args) => return templates::try_main(args),
#[cfg(windows)]
SubCommand::FileAssoc(args) => return file_assoc::try_main(args),
};
/*
Do data migration before anything else, since it can cause the location of stuff to change.
*/
if let Some(run_kind) = args.migrate_data {
println!("Migrating data...");
let (log, res) = platform::migrate_old_data(run_kind);
match (log.len(), res) {
(0, Ok(())) => {
println!("Nothing to do.");
return Ok(0);
},
(_, Ok(())) => {
for entry in log {
println!("- {}", entry);
}
return Ok(0);
},
(_, Err(err)) => {
for entry in log {
println!("- {}", entry);
}
return Err(err);
}
}
}
if log_enabled!(log::LogLevel::Debug) {
let scp = try!(get_script_cache_path());
let bcp = try!(get_binary_cache_path());
debug!("script-cache path: {:?}", scp);
debug!("binary-cache path: {:?}", bcp);
}
/*
If we've been asked to clear the cache, do that *now*. There are two reasons:
1. Do it *before* we call `decide_action_for` such that this flag *also* acts as a synonym for `--force`.
2. Do it *before* we start trying to read the input so that, later on, we can make `<script>` optional, but still supply `--clear-cache`.
*/
if args.clear_cache {
try!(clean_cache(0));
// If we *did not* get a `<script>` argument, that's OK.
if args.script.is_none() {
// Just let the user know that we did *actually* run.
println!("cargo script cache cleared.");
return Ok(0);
}
}
// Take the arguments and work out what our input is going to be. Primarily, this gives us the content, a user-friendly name, and a cache-friendly ID.
// These three are just storage for the borrows we'll actually use.
let script_name: String;
let script_path: PathBuf;
let content: String;
let input = match (args.script, args.expr, args.loop_) {
(Some(script), false, false) => {
let (path, mut file) = try!(find_script(script).ok_or("could not find script"));
script_name = path.file_stem()
.map(|os| os.to_string_lossy().into_owned())
.unwrap_or("unknown".into());
let mut body = String::new();
try!(file.read_to_string(&mut body));
let mtime = platform::file_last_modified(&file);
script_path = try!(std::env::current_dir()).join(path);
content = body;
Input::File(&script_name, &script_path, &content, mtime)
},
(Some(expr), true, false) => {
content = expr;
Input::Expr(&content, args.template.as_ref().map(|s| &**s))
},
(Some(loop_), false, true) => {
content = loop_;
Input::Loop(&content, args.count)
},
(None, _, _) => try!(Err((Blame::Human, consts::NO_ARGS_MESSAGE))),
_ => try!(Err((Blame::Human,
"cannot specify both --expr and --loop")))
};
info!("input: {:?}", input);
/*
Sort out the dependencies. We want to do a few things:
- Sort them so that they hash consistently.
- Check for duplicates.
- Expand `pkg` into `pkg=*`.
*/
let deps = {
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
let mut deps: HashMap<String, String> = HashMap::new();
for dep in args.dep.iter().chain(args.dep_extern.iter()).cloned() {
// Append '=*' if it needs it.
let dep = match dep.find('=') {
Some(_) => dep,
None => dep + "=*"
};
let mut parts = dep.splitn(2, '=');
let name = parts.next().expect("dependency is missing name");
let version = parts.next().expect("dependency is missing version");
assert!(parts.next().is_none(), "dependency somehow has three parts?!");
if name == "" {
try!(Err((Blame::Human, "cannot have empty dependency package name")));
}
if version == "" {
try!(Err((Blame::Human, "cannot have empty dependency version")));
}
match deps.entry(name.into()) {
Vacant(ve) => {
ve.insert(version.into());
},
Occupied(oe) => {
// This is *only* a problem if the versions don't match. We won't try to do anything clever in terms of upgrading or resolving or anything... exact match or go home.
let existing = oe.get();
if &version != existing {
try!(Err((Blame::Human,
format!("conflicting versions for dependency '{}': '{}', '{}'",
name, existing, version))));
}
}
}
}
// Sort and turn into a regular vec.
let mut deps: Vec<(String, String)> = deps.into_iter().collect();
deps.sort();
deps
};
info!("deps: {:?}", deps);
/*
Generate the prelude items, if we need any. Again, ensure consistent and *valid* sorting.
*/
let prelude_items = {
let unstable_features = args.unstable_features.iter()
.map(|uf| format!("#![feature({})]", uf));
let dep_externs = args.dep_extern.iter()
.map(|d| match d.find('=') {
Some(i) => &d[..i],
None => &d[..]
})
.map(|d| match d.contains('-') {
true => Cow::from(d.replace("-", "_")),
false => Cow::from(d)
})
.map(|d| format!("#[macro_use] extern crate {};", d));
let externs = args.extern_.iter()
.map(|n| format!("#[macro_use] extern crate {};", n));
let mut items: Vec<_> = unstable_features.chain(dep_externs).chain(externs).collect();
items.sort();
items
};
info!("prelude_items: {:?}", prelude_items);
// Work out what to do.
let action = try!(decide_action_for(
&input,
deps,
prelude_items,
args.debug,
args.pkg_path,
args.gen_pkg_only,
args.build_only,
args.force,
args.features,
args.use_bincache,
args.build_kind,
));
info!("action: {:?}", action);
try!(gen_pkg_and_compile(&input, &action));
// Once we're done, clean out old packages from the cache. There's no point if we've already done a full clear, though.
let _defer_clear = {
// To get around partially moved args problems.
let cc = args.clear_cache;
Defer::<_, MainError>::defer(move || {
if !cc {
try!(clean_cache(consts::MAX_CACHE_AGE_MS));
}
Ok(())
})
};
// Run it!
if action.execute {
fn hint<F: FnOnce(&mut Command) -> &mut Command>(f: F) -> F { f }
let add_env = hint(move |cmd| {
cmd.env("CARGO_SCRIPT_SCRIPT_PATH", input.path().unwrap_or(Path::new("")));
cmd.env("CARGO_SCRIPT_SAFE_NAME", input.safe_name());
cmd.env("CARGO_SCRIPT_PKG_NAME", input.package_name());
cmd.env("CARGO_SCRIPT_BASE_PATH", input.base_path());
cmd
});
if action.build_kind.can_exec_directly() {
let exe_path = try!(get_exe_path(action.build_kind, &action.pkg_path));
info!("executing {:?}", exe_path);
match try!({
Command::new(exe_path)
.args(&args.args)
.chain_map(add_env)
.status()
.map(|st| st.code().unwrap_or(1))
}) {
0 => (),
n => return Ok(n)
}
} else {
let cmd_name = action.build_kind.exec_command();
info!("running `cargo {}`", cmd_name);
let mut cmd = try!(action.cargo(cmd_name));
add_env(&mut cmd);
match try!(cmd.status().map(|st| st.code().unwrap_or(1))) {
0 => (),
n => return Ok(n)
}
}
}
// If nothing else failed, I suppose we succeeded.
Ok(0)
}
/**
Clean up the cache folder.
Looks for all folders whose metadata says they were created at least `max_age` in the past and kills them dead.
*/
fn clean_cache(max_age: u64) -> Result<()> {
info!("cleaning cache with max_age: {:?}", max_age);
if max_age == 0 {
info!("max_age is 0, clearing binary cache...");
let cache_dir = try!(get_binary_cache_path());
if ALLOW_AUTO_REMOVE {
if let Err(err) = fs::remove_dir_all(&cache_dir) {
error!("failed to remove binary cache {:?}: {}", cache_dir, err);
}
}
}
let cutoff = platform::current_time() - max_age;
info!("cutoff: {:>20?} ms", cutoff);
let cache_dir = try!(get_script_cache_path());
for child in try!(fs::read_dir(cache_dir)) {
let child = try!(child);
let path = child.path();
if path.is_file_polyfill() { continue }
info!("checking: {:?}", path);
let remove_dir = || {
/*
Ok, so *why* aren't we using `modified in the package metadata? The point of *that* is to track what we know about the input. The problem here is that `--expr` and `--loop` don't *have* modification times; they just *are*.
Now, `PackageMetadata` *could* be modified to store, say, the moment in time the input was compiled, but then we couldn't use that field for metadata matching when decided whether or not a *file* input should be recompiled.
So, instead, we're just going to go by the timestamp on the metadata file *itself*.
*/
let meta_mtime = {
let meta_path = get_pkg_metadata_path(&path);
let meta_file = match fs::File::open(&meta_path) {
Ok(file) => file,
Err(..) => {
info!("couldn't open metadata for {:?}", path);
return true
}
};
platform::file_last_modified(&meta_file)
};
info!("meta_mtime: {:>20?} ms", meta_mtime);
(meta_mtime <= cutoff)
};
if remove_dir() {
info!("removing {:?}", path);
if ALLOW_AUTO_REMOVE {
if let Err(err) = fs::remove_dir_all(&path) {
error!("failed to remove {:?} from cache: {}", path, err);
}
} else {
info!("(suppressed remove)");
}
}
}
info!("done cleaning cache.");
Ok(())
}
/**
Generate and compile a package from the input.
Why take `PackageMetadata`? To ensure that any information we need to depend on for compilation *first* passes through `decide_action_for` *and* is less likely to not be serialised with the rest of the metadata.
*/
fn gen_pkg_and_compile(
input: &Input,
action: &InputAction,
) -> Result<()> {
let pkg_path = &action.pkg_path;
let meta = &action.metadata;
let old_meta = action.old_metadata.as_ref();
let mani_str = &action.manifest;
let script_str = &action.script;
info!("creating pkg dir...");
try!(fs::create_dir_all(pkg_path));
let cleanup_dir: Defer<_, MainError> = Defer::defer(|| {
// DO NOT try deleting ANYTHING if we're not cleaning up inside our own cache. We *DO NOT* want to risk killing user files.
if action.using_cache {
info!("cleaning up cache directory {:?}", pkg_path);
if ALLOW_AUTO_REMOVE {
try!(fs::remove_dir_all(pkg_path));
} else {
info!("(suppressed remove)");
}
}
Ok(())
});
let mut meta = meta.clone();
info!("generating Cargo package...");
let mani_path = {
let mani_path = action.manifest_path();
let mani_hash = old_meta.map(|m| &*m.manifest_hash);
match try!(overwrite_file(&mani_path, mani_str, mani_hash)) {
FileOverwrite::Same => (),
FileOverwrite::Changed { new_hash } => {
meta.manifest_hash = new_hash;
},
}
mani_path
};
{
let script_path = pkg_path.join(format!("{}.rs", input.safe_name()));
/*
There are times (particularly involving shared target dirs) where we can't rely on Cargo to correctly detect invalidated builds. As such, if we've been told to *force* a recompile, we'll deliberately force the script to be overwritten, which will invalidate the timestamp, which will lead to a recompile.
*/
let script_hash = if action.force_compile {
debug!("told to force compile, ignoring script hash");
None
} else {
old_meta.map(|m| &*m.script_hash)
};
match try!(overwrite_file(&script_path, script_str, script_hash)) {
FileOverwrite::Same => (),
FileOverwrite::Changed { new_hash } => {
meta.script_hash = new_hash;
},
}
}
let meta = meta;
/*
*bursts through wall* It's Cargo Time! (Possibly)
Note that there's a complication here: we want to *temporarily* continue *even if compilation fails*. This is because if we don't, then every time you run `cargo script` on a script you're currently modifying, and it fails to compile, your compiled dependencies get obliterated.
This is *really* annoying.
As such, we want to ignore any compilation problems until *after* we've written the metadata and disarmed the cleanup callback.
*/
let mut compile_err = Ok(());
if action.compile {
info!("compiling...");
let mut cmd = try!(cargo("build", &*mani_path.to_string_lossy(), action.use_bincache, &meta));
#[cfg(feature="suppress-cargo-output")]
macro_rules! get_status {
($cmd:expr) => {
// `try!` doesn't work here on <=1.12.
(match util::suppress_child_output(
&mut $cmd,
::std::time::Duration::from_millis(CARGO_OUTPUT_TIMEOUT)
) {
Ok(v) => v,
Err(e) => return Err(e),
}).status()
}
}
#[cfg(not(feature="suppress-cargo-output"))]
macro_rules! get_status {
($cmd:expr) => {
$cmd.status()
}
}
compile_err = get_status!(cmd).map_err(|e| Into::<MainError>::into(e))
.and_then(|st|
match st.code() {
Some(0) => Ok(()),
Some(st) => Err(format!("cargo failed with status {}", st).into()),
None => Err("cargo failed".into())
});
// Drop out now if compilation failed.
let _ = try!(compile_err);
// Find out and cache what the executable was called.
let _ = try!(cargo_target(input, pkg_path, &*mani_path.to_string_lossy(), action.use_bincache, &meta));
if action.use_bincache {
// Write out the metadata hash to tie this executable to a particular chunk of metadata. This is to avoid issues with multiple scripts with the same name being compiled to a common target directory.
let meta_hash = action.metadata.sha1_hash();
info!("writing meta hash: {:?}...", meta_hash);
let exe_meta_hash_path = try!(get_meta_hash_path(action.use_bincache, pkg_path));
let mut f = try!(fs::File::create(&exe_meta_hash_path));
try!(write!(&mut f, "{}", meta_hash));
}
}
// Write out metadata *now*. Remember that we check the timestamp in the metadata, *not* on the executable.
if action.emit_metadata {
info!("emitting metadata...");
try!(write_pkg_metadata(pkg_path, &meta));
}
info!("disarming pkg dir cleanup...");
cleanup_dir.disarm();
compile_err
}
/**
This represents what to do with the input provided by the user.
*/
#[derive(Debug)]
struct InputAction {
/// Compile the input into a fresh executable?
compile: bool,
/**
Force Cargo to do a recompile, even if it thinks it doesn't have to.
`compile` must be `true` for this to have any effect.
*/
force_compile: bool,
/// Emit a metadata file?
emit_metadata: bool,
/// Execute the compiled binary?
execute: bool,
/// Directory where the package should live.
pkg_path: PathBuf,
/**
Is the package directory in the cache?
Currently, this can be inferred from `emit_metadata`, but there's no *intrinsic* reason they should be tied together.
*/
using_cache: bool,
/// Use shared binary cache?
use_bincache: bool,
/// The package metadata structure for the current invocation.
metadata: PackageMetadata,
/// The package metadata structure for the *previous* invocation, if it exists.
old_metadata: Option<PackageMetadata>,
/// The package manifest contents.
manifest: String,
/// The script source.
script: String,
/// Did the user ask to run tests or benchmarks?
build_kind: BuildKind,
}
impl InputAction {
fn manifest_path(&self) -> PathBuf {
self.pkg_path.join("Cargo.toml")
}
fn cargo(&self, cmd: &str) -> Result<Command> {
cargo(cmd, &*self.manifest_path().to_string_lossy(), self.use_bincache, &self.metadata)
}
}
/**
The metadata here serves two purposes:
1. It records everything necessary for compilation and execution of a package.
2. It records everything that must be exactly the same in order for a cached executable to still be valid, in addition to the content hash.
*/
#[derive(Clone, Debug, Eq, PartialEq, RustcDecodable, RustcEncodable)]
struct PackageMetadata {
/// Path to the script file.
path: Option<String>,
/// Last-modified timestamp for script file.
modified: Option<u64>,
/// Template used.
template: Option<String>,
/// Was the script compiled in debug mode?
debug: bool,
/// Sorted list of dependencies.
deps: Vec<(String, String)>,
/// Sorted list of injected prelude items.
prelude: Vec<String>,
/// Cargo features
features: Option<String>,
/// Hash of the generated `Cargo.toml` file.
manifest_hash: String,
/// Hash of the generated source file.
script_hash: String,
}
impl PackageMetadata {
pub fn sha1_hash(&self) -> String {
// Yes, I *do* feel dirty for doing it like this. :D
hash_str(&format!("{:?}", self))
}
}
/**
For the given input, this constructs the package metadata and checks the cache to see what should be done.
*/
fn decide_action_for(
input: &Input,
deps: Vec<(String, String)>,
prelude: Vec<String>,
debug: bool,
pkg_path: Option<String>,
gen_pkg_only: bool,
build_only: bool,
force: bool,
features: Option<String>,
use_bincache: Option<bool>,
build_kind: BuildKind,
) -> Result<InputAction> {
let (pkg_path, using_cache) = pkg_path.map(|p| (p.into(), false))
.unwrap_or_else(|| {
// This can't fail. Seriously, we're *fucked* if we can't work this out.
let cache_path = get_script_cache_path().unwrap();
info!("cache_path: {:?}", cache_path);
let id = {
let deps_iter = deps.iter()
.map(|&(ref n, ref v)| (n as &str, v as &str));
// Again, also fucked if we can't work this out.