/
nodes.rs
1213 lines (1091 loc) · 34.6 KB
/
nodes.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 2017 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
extern crate bazel_protos;
extern crate tempdir;
use std::error::Error;
use std::collections::BTreeMap;
use std::fmt;
use std::os::unix::ffi::OsStrExt;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use futures::future::{self, Future};
use tempdir::TempDir;
use boxfuture::{BoxFuture, Boxable};
use context::Context;
use core::{throw, Failure, Key, Noop, TypeConstraint, Value, Variants};
use externs;
use fs::{self, Dir, File, FileContent, Link, PathGlobs, PathStat, StoreFileByDigest, VFS};
use process_execution;
use hashing;
use rule_graph;
use selectors::{self, Selector};
use tasks::{self, Intrinsic, IntrinsicKind};
pub type NodeFuture<T> = BoxFuture<T, Failure>;
fn ok<O: Send + 'static>(value: O) -> NodeFuture<O> {
future::ok(value).to_boxed()
}
fn err<O: Send + 'static>(failure: Failure) -> NodeFuture<O> {
future::err(failure).to_boxed()
}
///
/// A helper to indicate that the value represented by the Failure was required, and thus
/// fatal if not present.
///
fn was_required(failure: Failure) -> Failure {
match failure {
Failure::Noop(noop) => throw(&format!("No source of required dependency: {:?}", noop)),
f => f,
}
}
pub trait GetNode {
fn get<N: Node>(&self, node: N) -> NodeFuture<N::Output>;
}
impl VFS<Failure> for Context {
fn read_link(&self, link: Link) -> NodeFuture<PathBuf> {
self.get(ReadLink(link)).map(|res| res.0).to_boxed()
}
fn scandir(&self, dir: Dir) -> NodeFuture<Vec<fs::Stat>> {
self.get(Scandir(dir)).map(|res| res.0).to_boxed()
}
fn is_ignored(&self, stat: &fs::Stat) -> bool {
self.core.vfs.is_ignored(stat)
}
fn mk_error(msg: &str) -> Failure {
Failure::Throw(
externs::create_exception(msg),
"<pants native internals>".to_string(),
)
}
}
impl StoreFileByDigest<Failure> for Context {
fn store_by_digest(&self, file: File) -> BoxFuture<hashing::Digest, Failure> {
self.get(DigestFile(file))
}
}
///
/// Defines executing a cacheable/memoizable step for the given context.
///
/// The Output type of a Node is bounded to values that can be stored and retrieved from
/// the NodeResult enum. Due to the semantics of memoization, retrieving the typed result
/// stored inside the NodeResult requires an implementation of TryFrom<NodeResult>. But the
/// combination of bounds at usage sites should mean that a failure to unwrap the result is
/// exceedingly rare.
///
pub trait Node: Into<NodeKey> {
type Output: Clone + fmt::Debug + Into<NodeResult> + TryFrom<NodeResult> + Send + 'static;
fn run(self, context: Context) -> NodeFuture<Self::Output>;
}
///
/// A Node that selects a product for a subject.
///
/// A Select can be satisfied by multiple sources, but fails if multiple sources produce a value.
/// The 'variants' field represents variant configuration that is propagated to dependencies. When
/// a task needs to consume a product as configured by the variants map, it can pass variant_key,
/// which matches a 'variant' value to restrict the names of values selected by a SelectNode.
///
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Select {
pub subject: Key,
pub variants: Variants,
pub selector: selectors::Select,
entries: rule_graph::Entries,
}
impl Select {
pub fn new(
product: TypeConstraint,
subject: Key,
variants: Variants,
edges: &rule_graph::RuleEdges,
) -> Select {
let selector = selectors::Select::without_variant(product);
let select_key = rule_graph::SelectKey::JustSelect(selector.clone());
Select {
selector: selector,
subject: subject,
variants: variants,
entries: edges.entries_for(&select_key),
}
}
pub fn new_with_entries(
product: TypeConstraint,
subject: Key,
variants: Variants,
entries: rule_graph::Entries,
) -> Select {
let selector = selectors::Select::without_variant(product);
Select {
selector: selector,
subject: subject,
variants: variants,
entries: entries,
}
}
pub fn new_with_selector(
selector: selectors::Select,
subject: Key,
variants: Variants,
edges: &rule_graph::RuleEdges,
) -> Select {
let select_key = rule_graph::SelectKey::JustSelect(selector.clone());
Select {
selector: selector,
subject: subject,
variants: variants,
entries: edges
.entries_for(&select_key)
.into_iter()
.filter(|e| e.matches_subject_type(subject.type_id().clone()))
.collect(),
}
}
fn product(&self) -> &TypeConstraint {
&self.selector.product
}
fn select_literal_single<'a>(
&self,
candidate: &'a Value,
variant_value: &Option<String>,
) -> bool {
if !externs::satisfied_by(&self.selector.product, candidate) {
return false;
}
return match variant_value {
&Some(ref vv) if externs::project_str(candidate, "name") != *vv =>
// There is a variant value, and it doesn't match.
false,
_ =>
true,
};
}
///
/// Looks for has-a or is-a relationships between the given value and the requested product.
///
/// Returns the resulting product value, or None if no match was made.
///
fn select_literal(
&self,
context: &Context,
candidate: Value,
variant_value: &Option<String>,
) -> Option<Value> {
// Check whether the subject is-a instance of the product.
if self.select_literal_single(&candidate, variant_value) {
return Some(candidate);
}
// Else, check whether it has-a instance of the product.
// TODO: returning only the first literal configuration of a given type/variant. Need to
// define mergeability for products.
if externs::satisfied_by(&context.core.types.has_products, &candidate) {
for child in externs::project_multi(&candidate, "products") {
if self.select_literal_single(&child, variant_value) {
return Some(child);
}
}
}
None
}
///
/// Given the results of configured Task nodes, select a single successful value, or fail.
///
fn choose_task_result(
&self,
context: Context,
results: Vec<Result<Value, Failure>>,
variant_value: &Option<String>,
) -> Result<Value, Failure> {
let mut matches = Vec::new();
let mut max_noop = Noop::NoTask;
for result in results {
match result {
Ok(value) => {
if let Some(v) = self.select_literal(&context, value, variant_value) {
matches.push(v);
}
}
Err(err) => {
match err {
Failure::Noop(noop) => {
// Record the highest priority Noop value.
if noop > max_noop {
max_noop = noop;
}
continue;
}
i @ Failure::Invalidated => return Err(i),
f @ Failure::Throw(..) => return Err(f),
}
}
}
}
if matches.len() > 1 {
// TODO: Multiple successful tasks are not currently supported. We could allow for this
// by adding support for "mergeable" products. see:
// https://github.com/pantsbuild/pants/issues/2526
return Err(throw("Conflicting values produced for subject and type."));
}
match matches.pop() {
Some(matched) =>
// Exactly one value was available.
Ok(matched),
None =>
// Propagate the highest priority Noop value.
Err(Failure::Noop(max_noop)),
}
}
fn snapshot(&self, context: &Context, entry: &rule_graph::Entry) -> NodeFuture<fs::Snapshot> {
let ref edges = context
.core
.rule_graph
.edges_for_inner(entry)
.expect("Expected edges to exist for Snapshot intrinsic.");
// Compute PathGlobs for the subject.
let context = context.clone();
Select::new(
context.core.types.path_globs.clone(),
self.subject.clone(),
self.variants.clone(),
edges,
).run(context.clone())
.and_then(move |path_globs_val| context.get(Snapshot(externs::key_for(path_globs_val))))
.to_boxed()
}
fn execute_process(
&self,
context: &Context,
entry: &rule_graph::Entry,
) -> NodeFuture<ProcessResult> {
let ref edges = context
.core
.rule_graph
.edges_for_inner(entry)
.expect("Expected edges to exist for ExecuteProcess intrinsic.");
// Compute an ExecuteProcessRequest for the subject.
let context = context.clone();
Select::new(
context.core.types.process_request.clone(),
self.subject.clone(),
self.variants.clone(),
edges,
).run(context.clone())
.and_then(|process_request_val| {
ExecuteProcess::lift(&process_request_val)
.map_err(|str| throw(&format!("Error lifting ExecuteProcess: {}", str)))
})
.and_then(move |process_request| context.get(process_request))
.to_boxed()
}
///
/// Return Futures for each Task/Node that might be able to compute the given product for the
/// given subject and variants.
///
fn gen_nodes(&self, context: &Context) -> Vec<NodeFuture<Value>> {
if let Some(&(_, ref value)) = context.core.tasks.gen_singleton(self.product()) {
return vec![future::ok(value.clone()).to_boxed()];
}
self
.entries
.iter()
.map(
|entry| match context.core.rule_graph.rule_for_inner(entry) {
&rule_graph::Rule::Task(ref task) => context.get(Task {
subject: self.subject.clone(),
product: self.product().clone(),
variants: self.variants.clone(),
task: task.clone(),
entry: Arc::new(entry.clone()),
}),
&rule_graph::Rule::Intrinsic(Intrinsic {
kind: IntrinsicKind::Snapshot,
..
}) => {
let context = context.clone();
self
.snapshot(&context, &entry)
.map(move |snapshot| Snapshot::store_snapshot(&context, &snapshot))
.to_boxed()
}
&rule_graph::Rule::Intrinsic(Intrinsic {
kind: IntrinsicKind::FilesContent,
..
}) => {
let context = context.clone();
self
.snapshot(&context, &entry)
.and_then(move |snapshot| {
// Request the file contents of the Snapshot, and then store them.
snapshot
.contents(context.core.store.clone())
.map_err(|e| throw(&e))
.map(move |files_content| Snapshot::store_files_content(&context, &files_content))
})
.to_boxed()
}
&rule_graph::Rule::Intrinsic(Intrinsic {
kind: IntrinsicKind::ProcessExecution,
..
}) => {
let context = context.clone();
self
.execute_process(&context, &entry)
.map(move |result| {
externs::unsafe_call(
&context.core.types.construct_process_result,
&[
externs::store_bytes(&result.0.stdout),
externs::store_bytes(&result.0.stderr),
externs::store_i32(result.0.exit_code),
],
)
})
.to_boxed()
}
},
)
.collect::<Vec<NodeFuture<Value>>>()
}
}
// TODO: This is a Node only because it is used as a root in the graph, but it should never be
// requested using context.get
impl Node for Select {
type Output = Value;
fn run(self, context: Context) -> NodeFuture<Value> {
// TODO add back support for variants https://github.com/pantsbuild/pants/issues/4020
// If there is a variant_key, see whether it has been configured; if not, no match.
let variant_value: Option<String> = match self.selector.variant_key {
Some(ref variant_key) => {
let variant_value = self.variants.find(variant_key);
if variant_value.is_none() {
return err(Failure::Noop(Noop::NoVariant));
}
variant_value.map(|v| v.to_string())
}
None => None,
};
// If the Subject "is a" or "has a" Product, then we're done.
if let Some(literal_value) =
self.select_literal(&context, externs::val_for(&self.subject), &variant_value)
{
return ok(literal_value);
}
// Else, attempt to use the configured tasks to compute the value.
let deps_future = future::join_all(
self
.gen_nodes(&context)
.into_iter()
.map(|node_future| {
// Don't fail the join if one fails.
node_future.then(|r| future::ok(r))
})
.collect::<Vec<_>>(),
);
let variant_value = variant_value.map(|s| s.to_string());
deps_future
.and_then(move |dep_results| {
future::result(self.choose_task_result(context, dep_results, &variant_value))
})
.to_boxed()
}
}
impl From<Select> for NodeKey {
fn from(n: Select) -> Self {
NodeKey::Select(n)
}
}
///
/// A Node that selects the given Product for each of the items in `field` on `dep_product`.
///
/// Begins by selecting the `dep_product` for the subject, and then selects a product for each
/// member of a collection named `field` on the dep_product.
///
/// The value produced by this Node guarantees that the order of the provided values matches the
/// order of declaration in the list `field` of the `dep_product`.
///
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct SelectDependencies {
pub subject: Key,
pub variants: Variants,
pub selector: selectors::SelectDependencies,
pub dep_product_entries: rule_graph::Entries,
pub product_entries: rule_graph::Entries,
}
impl SelectDependencies {
pub fn new(
selector: selectors::SelectDependencies,
subject: Key,
variants: Variants,
edges: &rule_graph::RuleEdges,
) -> SelectDependencies {
// filters entries by whether the subject type is the right subject type
let dep_p_entries = edges.entries_for(&rule_graph::SelectKey::NestedSelect(
Selector::SelectDependencies(selector.clone()),
selectors::Select::without_variant(selector.clone().dep_product),
));
let p_entries = edges.entries_for(&rule_graph::SelectKey::ProjectedMultipleNestedSelect(
Selector::SelectDependencies(selector.clone()),
selector.field_types.clone(),
selectors::Select::without_variant(selector.product.clone()),
));
SelectDependencies {
subject: subject,
variants: variants,
selector: selector.clone(),
dep_product_entries: dep_p_entries,
product_entries: p_entries,
}
}
fn get_dep(&self, context: &Context, dep_subject: Value) -> NodeFuture<Value> {
// TODO: This method needs to consider whether the `dep_subject` is an Address,
// and if so, attempt to parse Variants there. See:
// https://github.com/pantsbuild/pants/issues/4020
let dep_subject_key = externs::key_for(dep_subject);
Select {
selector: selectors::Select::without_variant(self.selector.product),
subject: dep_subject_key,
variants: self.variants.clone(),
// NB: We're filtering out all of the entries for field types other than
// dep_subject's since none of them will match.
entries: self
.product_entries
.clone()
.into_iter()
.filter(|e| e.matches_subject_type(dep_subject_key.type_id().clone()))
.collect(),
}.run(context.clone())
}
}
impl SelectDependencies {
fn run(self, context: Context) -> NodeFuture<Value> {
// Select the product holding the dependency list.
Select {
selector: selectors::Select::without_variant(self.selector.dep_product),
subject: self.subject.clone(),
variants: self.variants.clone(),
entries: self.dep_product_entries.clone(),
}.run(context.clone())
.then(move |dep_product_res| {
match dep_product_res {
Ok(dep_product) => {
// The product and its dependency list are available: project them.
let deps = future::join_all(
externs::project_multi(&dep_product, &self.selector.field)
.into_iter()
.map(|dep_subject| self.get_dep(&context, dep_subject))
.collect::<Vec<_>>(),
);
deps
.then(move |dep_values_res| {
// Finally, store the resulting values.
match dep_values_res {
Ok(dep_values) => Ok(externs::store_tuple(&dep_values)),
Err(failure) => Err(was_required(failure)),
}
})
.to_boxed()
}
Err(failure) => err(failure),
}
})
.to_boxed()
}
}
///
/// A Node that represents executing a process.
///
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct ExecuteProcess(process_execution::ExecuteProcessRequest);
impl ExecuteProcess {
fn lift_digest(digest: &Value) -> Result<hashing::Digest, String> {
let fingerprint = externs::project_str(&digest, "fingerprint");
let digest_length = externs::project_str(&digest, "serialized_bytes_length");
let digest_length_as_usize = digest_length
.parse::<usize>()
.map_err(|err| format!("Length was not a usize: {:?}", err))?;
Ok(hashing::Digest(
hashing::Fingerprint::from_hex_string(&fingerprint)?,
digest_length_as_usize,
))
}
///
/// Lifts a Key representing a python ExecuteProcessRequest value into a ExecuteProcess Node.
///
fn lift(value: &Value) -> Result<ExecuteProcess, String> {
let mut env: BTreeMap<String, String> = BTreeMap::new();
let env_var_parts = externs::project_multi_strs(&value, "env");
if env_var_parts.len() % 2 != 0 {
return Err(format!("Error parsing env: odd number of parts"));
}
for i in 0..(env_var_parts.len() / 2) {
env.insert(
env_var_parts[2 * i].clone(),
env_var_parts[2 * i + 1].clone(),
);
}
let digest = Self::lift_digest(&externs::project_ignoring_type(&value, "input_files"))
.map_err(|err| format!("Error parsing digest {}", err))?;
Ok(ExecuteProcess(process_execution::ExecuteProcessRequest {
argv: externs::project_multi_strs(&value, "argv"),
env: env,
input_files: digest,
}))
}
}
#[derive(Clone, Debug)]
pub struct ProcessResult(process_execution::ExecuteProcessResult);
impl Node for ExecuteProcess {
type Output = ProcessResult;
fn run(self, context: Context) -> NodeFuture<ProcessResult> {
let request = self.0;
let context2 = context.clone();
// TODO: Process pool management should likely move into the `process_execution` crate, which
// will have different strategies depending on remote/local execution.
context
.core
.pool
.spawn_fn(move || {
let tmpdir = TempDir::new("process-execution").unwrap();
context2
.core
.store
.materialize_directory(tmpdir.path().to_owned(), request.input_files)
.map(move |_| {
ProcessResult(
process_execution::local::run_command_locally(request, tmpdir.path()).unwrap(),
)
})
.map_err(|e| throw(&format!("Failed to execute process: {}", e)))
})
.to_boxed()
}
}
impl From<ExecuteProcess> for NodeKey {
fn from(n: ExecuteProcess) -> Self {
NodeKey::ExecuteProcess(n)
}
}
///
/// A Node that represents reading the destination of a symlink (non-recursively).
///
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct ReadLink(Link);
#[derive(Clone, Debug)]
pub struct LinkDest(PathBuf);
impl Node for ReadLink {
type Output = LinkDest;
fn run(self, context: Context) -> NodeFuture<LinkDest> {
let link = self.0.clone();
context
.core
.vfs
.read_link(&self.0)
.map(|dest_path| LinkDest(dest_path))
.map_err(move |e| throw(&format!("Failed to read_link for {:?}: {:?}", link, e)))
.to_boxed()
}
}
impl From<ReadLink> for NodeKey {
fn from(n: ReadLink) -> Self {
NodeKey::ReadLink(n)
}
}
///
/// A Node that represents reading a file and fingerprinting its contents.
///
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct DigestFile(pub File);
impl Node for DigestFile {
type Output = hashing::Digest;
fn run(self, context: Context) -> NodeFuture<hashing::Digest> {
let file = self.0.clone();
context
.core
.vfs
.read_file(&self.0)
.map_err(move |e| {
throw(&format!(
"Error reading file {:?}: {}",
file,
e.description()
))
})
.and_then(move |c| {
context
.core
.store
.store_file_bytes(c.content, true)
.map_err(|e| throw(&e))
})
.to_boxed()
}
}
impl From<DigestFile> for NodeKey {
fn from(n: DigestFile) -> Self {
NodeKey::DigestFile(n)
}
}
///
/// A Node that represents executing a directory listing that returns a Stat per directory
/// entry (generally in one syscall). No symlinks are expanded.
///
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Scandir(Dir);
#[derive(Clone, Debug)]
pub struct DirectoryListing(Vec<fs::Stat>);
impl Node for Scandir {
type Output = DirectoryListing;
fn run(self, context: Context) -> NodeFuture<DirectoryListing> {
let dir = self.0.clone();
context
.core
.vfs
.scandir(&self.0)
.then(move |listing_res| match listing_res {
Ok(listing) => Ok(DirectoryListing(listing)),
Err(e) => Err(throw(&format!("Failed to scandir for {:?}: {:?}", dir, e))),
})
.to_boxed()
}
}
impl From<Scandir> for NodeKey {
fn from(n: Scandir) -> Self {
NodeKey::Scandir(n)
}
}
///
/// A Node that captures an fs::Snapshot for a PathGlobs subject.
///
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Snapshot(Key);
impl Snapshot {
fn create(context: Context, path_globs: PathGlobs) -> NodeFuture<fs::Snapshot> {
// Recursively expand PathGlobs into PathStats.
// We rely on Context::expand tracking dependencies for scandirs,
// and fs::Snapshot::from_path_stats tracking dependencies for file digests.
context
.expand(path_globs)
.map_err(|e| format!("PathGlobs expansion failed: {:?}", e))
.and_then(move |path_stats| {
fs::Snapshot::from_path_stats(context.core.store.clone(), context.clone(), path_stats)
.map_err(move |e| format!("Snapshot failed: {}", e))
})
.map_err(|e| throw(&e))
.to_boxed()
}
fn lift_path_globs(item: &Value) -> Result<PathGlobs, String> {
let include = externs::project_multi_strs(item, "include");
let exclude = externs::project_multi_strs(item, "exclude");
PathGlobs::create(&include, &exclude).map_err(|e| {
format!(
"Failed to parse PathGlobs for include({:?}), exclude({:?}): {}",
include, exclude, e
)
})
}
fn store_directory(context: &Context, item: &hashing::Digest) -> Value {
externs::unsafe_call(
&context.core.types.construct_directory_digest,
&[
externs::store_bytes(item.0.to_hex().as_bytes()),
externs::store_i32(item.1 as i32),
],
)
}
fn store_snapshot(context: &Context, item: &fs::Snapshot) -> Value {
let path_stats: Vec<_> = item
.path_stats
.iter()
.map(|ps| Self::store_path_stat(context, ps))
.collect();
externs::unsafe_call(
&context.core.types.construct_snapshot,
&[
Self::store_directory(context, &item.digest),
externs::store_tuple(&path_stats),
],
)
}
fn store_path(item: &Path) -> Value {
externs::store_bytes(item.as_os_str().as_bytes())
}
fn store_dir(context: &Context, item: &Dir) -> Value {
let args = [Self::store_path(item.0.as_path())];
externs::unsafe_call(&context.core.types.construct_dir, &args)
}
fn store_file(context: &Context, item: &File) -> Value {
let args = [Self::store_path(item.path.as_path())];
externs::unsafe_call(&context.core.types.construct_file, &args)
}
fn store_path_stat(context: &Context, item: &PathStat) -> Value {
let args = match item {
&PathStat::Dir { ref path, ref stat } => {
vec![Self::store_path(path), Self::store_dir(context, stat)]
}
&PathStat::File { ref path, ref stat } => {
vec![Self::store_path(path), Self::store_file(context, stat)]
}
};
externs::unsafe_call(&context.core.types.construct_path_stat, &args)
}
fn store_file_content(context: &Context, item: &FileContent) -> Value {
externs::unsafe_call(
&context.core.types.construct_file_content,
&[
Self::store_path(&item.path),
externs::store_bytes(&item.content),
],
)
}
fn store_files_content(context: &Context, item: &Vec<FileContent>) -> Value {
let entries: Vec<_> = item
.iter()
.map(|e| Self::store_file_content(context, e))
.collect();
externs::unsafe_call(
&context.core.types.construct_files_content,
&[externs::store_tuple(&entries)],
)
}
}
impl Node for Snapshot {
type Output = fs::Snapshot;
fn run(self, context: Context) -> NodeFuture<fs::Snapshot> {
match Self::lift_path_globs(&externs::val_for(&self.0)) {
Ok(pgs) => Self::create(context, pgs),
Err(e) => err(throw(&format!("Failed to parse PathGlobs: {}", e))),
}
}
}
impl From<Snapshot> for NodeKey {
fn from(n: Snapshot) -> Self {
NodeKey::Snapshot(n)
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Task {
subject: Key,
product: TypeConstraint,
variants: Variants,
task: tasks::Task,
entry: Arc<rule_graph::Entry>,
}
impl Task {
fn get(&self, context: &Context, selector: Selector) -> NodeFuture<Value> {
let ref edges = context
.core
.rule_graph
.edges_for_inner(&self.entry)
.expect("edges for task exist.");
match selector {
Selector::Select(s) => {
Select::new_with_selector(s, self.subject.clone(), self.variants.clone(), edges)
.run(context.clone())
}
Selector::SelectDependencies(s) => {
SelectDependencies::new(s, self.subject.clone(), self.variants.clone(), edges)
.run(context.clone())
}
}
}
fn gen_get(
context: &Context,
entry: Arc<rule_graph::Entry>,
gets: Vec<externs::Get>,
) -> NodeFuture<Vec<Value>> {
let get_futures = gets
.into_iter()
.map(|get| {
let externs::Get(product, subject) = get;
let entries = context
.core
.rule_graph
.edges_for_inner(&entry)
.expect("edges for task exist.")
.entries_for(&rule_graph::SelectKey::JustGet(selectors::Get {
product: product,
subject: subject.type_id().clone(),
}));
Select::new_with_entries(product, subject, Default::default(), entries)
.run(context.clone())
.map_err(|e| was_required(e))
})
.collect::<Vec<_>>();
future::join_all(get_futures).to_boxed()
}
///
/// Given a python generator Value, loop to request the generator's dependencies until
/// it completes with a result Value.
///
fn generate(
context: Context,
entry: Arc<rule_graph::Entry>,
generator: Value,
) -> NodeFuture<Value> {
future::loop_fn(externs::eval("None").unwrap(), move |input| {
let context = context.clone();
let entry = entry.clone();
future::result(externs::generator_send(&generator, &input)).and_then(move |response| {
match response {
externs::GeneratorResponse::Get(get) => Self::gen_get(&context, entry, vec![get])
.map(|vs| future::Loop::Continue(vs.into_iter().next().unwrap()))
.to_boxed(),
externs::GeneratorResponse::GetMulti(gets) => Self::gen_get(&context, entry, gets)
.map(|vs| future::Loop::Continue(externs::store_tuple(&vs)))
.to_boxed(),
externs::GeneratorResponse::Break(val) => future::ok(future::Loop::Break(val)).to_boxed(),
}
})
}).to_boxed()
}
}
impl Node for Task {
type Output = Value;
fn run(self, context: Context) -> NodeFuture<Value> {
let deps = future::join_all(
self
.task
.clause
.iter()
.map(|selector| self.get(&context, selector.clone()))
.collect::<Vec<_>>(),
);
let func = self.task.func.clone();
let entry = self.entry.clone();
deps
.then(move |deps_result| match deps_result {
Ok(deps) => externs::call(&externs::val_for(&func.0), &deps),
Err(failure) => Err(failure),
})
.then(move |task_result| match task_result {
Ok(val) => {
if externs::satisfied_by(&context.core.types.generator, &val) {
Self::generate(context, entry, val)
} else {
ok(val)
}
}
Err(failure) => err(failure),
})
.to_boxed()
}
}
impl From<Task> for NodeKey {
fn from(n: Task) -> Self {
NodeKey::Task(n)
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum NodeKey {
DigestFile(DigestFile),
ExecuteProcess(ExecuteProcess),
ReadLink(ReadLink),
Scandir(Scandir),
Select(Select),
Snapshot(Snapshot),
Task(Task),
}
impl NodeKey {
pub fn format(&self) -> String {
fn keystr(key: &Key) -> String {
externs::key_to_str(&key)
}
fn typstr(tc: &TypeConstraint) -> String {
externs::key_to_str(&tc.0)
}
match self {
&NodeKey::DigestFile(ref s) => format!("DigestFile({:?})", s.0),
&NodeKey::ExecuteProcess(ref s) => format!("ExecuteProcess({:?}", s.0),
&NodeKey::ReadLink(ref s) => format!("ReadLink({:?})", s.0),
&NodeKey::Scandir(ref s) => format!("Scandir({:?})", s.0),
&NodeKey::Select(ref s) => format!(
"Select({}, {})",
keystr(&s.subject),
typstr(&s.selector.product)
),
&NodeKey::Task(ref s) => format!(
"Task({}, {}, {})",
externs::project_str(&externs::val_for(&s.task.func.0), "__name__"),
keystr(&s.subject),
typstr(&s.product)
),
&NodeKey::Snapshot(ref s) => format!("Snapshot({})", keystr(&s.0)),
}
}