-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathsess.rs
More file actions
1740 lines (1620 loc) · 64.6 KB
/
sess.rs
File metadata and controls
1740 lines (1620 loc) · 64.6 KB
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 (c) 2017-2018 ETH Zurich
// Fabian Schuiki <fschuiki@iis.ee.ethz.ch>
//! A command line session.
#![deny(missing_docs)]
use std;
use std::fmt;
use std::io::Write;
use std::iter::FromIterator;
use std::mem::swap;
use std::path::{Path, PathBuf};
use std::sync::atomic::AtomicUsize;
use std::sync::{Arc, Mutex};
use std::time::SystemTime;
#[cfg(unix)]
use std::fs::canonicalize;
#[cfg(windows)]
use dunce::canonicalize;
use crate::futures::{FutureExt, TryFutureExt};
use async_recursion::async_recursion;
use futures::future::{self, join_all};
use indexmap::{IndexMap, IndexSet};
use semver::Version;
use typed_arena::Arena;
use crate::cli::read_manifest;
use crate::config::Validate;
use crate::config::{self, Config, Manifest};
use crate::error::*;
// use crate::future_throttle::FutureThrottle;
use crate::git::Git;
use crate::src::SourceFile::Group;
use crate::src::SourceGroup;
use crate::target::TargetSpec;
use crate::util::try_modification_time;
/// A session on the command line.
///
/// Contains all the information that is iteratively being gathered and
/// generated as a command on the command line is executed.
pub struct Session<'ctx> {
/// The path of the package within which the tool was executed.
pub root: &'ctx Path,
/// The manifest of the root package.
pub manifest: &'ctx Manifest,
/// The tool configuration.
pub config: &'ctx Config,
/// The arenas into which we allocate various things that need to live as
/// long as the session.
arenas: &'ctx SessionArenas,
/// The manifest modification time.
pub manifest_mtime: Option<SystemTime>,
/// Some statistics about the session.
stats: SessionStatistics,
/// The dependency table.
deps: Mutex<DependencyTable<'ctx>>,
/// The internalized paths.
paths: Mutex<IndexSet<&'ctx Path>>,
/// The internalized strings.
strings: Mutex<IndexSet<&'ctx str>>,
/// The package name table.
names: Mutex<IndexMap<String, DependencyRef>>,
/// The dependency graph.
graph: Mutex<Arc<IndexMap<DependencyRef, IndexSet<DependencyRef>>>>,
/// The topologically sorted list of packages.
pkgs: Mutex<Arc<Vec<Vec<DependencyRef>>>>,
/// The source file manifest.
sources: Mutex<Option<SourceGroup<'ctx>>>,
/// The plugins declared by packages.
plugins: Mutex<Option<&'ctx Plugins>>,
/// The session cache.
pub cache: SessionCache<'ctx>,
// /// A throttle for futures performing git network operations.
// git_throttle: FutureThrottle,
/// A toggle to disable remote fetches & clones
pub local_only: bool,
}
impl<'sess, 'ctx: 'sess> Session<'ctx> {
/// Create a new session.
pub fn new(
root: &'ctx Path,
manifest: &'ctx Manifest,
config: &'ctx Config,
arenas: &'ctx SessionArenas,
local_only: bool,
force_fetch: bool,
) -> Session<'ctx> {
Session {
root,
manifest,
config,
arenas,
manifest_mtime: {
if force_fetch {
Some(SystemTime::now())
} else {
try_modification_time(root.join("Bender.yml"))
}
},
stats: Default::default(),
deps: Mutex::new(DependencyTable::new()),
paths: Mutex::new(IndexSet::new()),
strings: Mutex::new(IndexSet::new()),
names: Mutex::new(IndexMap::new()),
graph: Mutex::new(Arc::new(IndexMap::new())),
pkgs: Mutex::new(Arc::new(Vec::new())),
sources: Mutex::new(None),
plugins: Mutex::new(None),
cache: Default::default(),
// git_throttle: FutureThrottle::new(8),
local_only,
}
}
/// Load a dependency stated in a manifest for further inspection.
///
/// This internalizes the dependency and returns a lightweight reference to
/// it. This reference may then be used to further inspect the dependency
/// and perform resolution.
pub fn load_dependency(
&self,
name: &str,
cfg: &config::Dependency,
manifest: &config::Manifest,
) -> DependencyRef {
debugln!(
"sess: load dependency `{}` as {:?} for package `{}`",
name,
cfg,
manifest.package.name
);
let src = DependencySource::from(cfg);
self.deps
.lock()
.unwrap()
.add(self.intern_dependency_entry(DependencyEntry {
name: name.into(),
source: src,
revision: None,
version: None,
}))
}
/// Load a lock file.
///
/// This internalizes the dependency sources, i.e. assigns `DependencyRef`
/// objects to them, and generates a nametable.
pub fn load_locked(&self, locked: &config::Locked) -> Result<()> {
let mut deps = self.deps.lock().unwrap();
let mut names = IndexMap::new();
let mut graph_names = IndexMap::new();
for (name, pkg) in &locked.packages {
let src = match pkg.source {
config::LockedSource::Path(ref path) => DependencySource::Path(path.clone()),
config::LockedSource::Git(ref url) => DependencySource::Git(url.clone()),
config::LockedSource::Registry(ref _ver) => DependencySource::Registry,
};
let id = deps.add(
self.intern_dependency_entry(DependencyEntry {
name: name.clone(),
source: src,
revision: pkg.revision.clone(),
version: pkg
.version
.as_ref()
.map(|s| semver::Version::parse(s).unwrap()),
}),
);
graph_names.insert(id, &pkg.dependencies);
names.insert(name.clone(), id);
}
drop(deps);
// Translate the name-based graph into an ID-based graph.
let graph: IndexMap<DependencyRef, IndexSet<DependencyRef>> = graph_names
.into_iter()
.map(|(k, v)| {
(
k,
v.iter()
.map(|name| match names.get(name) {
Some(id) => Ok(*id),
None => Err(Error::new(format!(
"Failed to match dependency {}, please run `bender update`!",
name
))),
})
.collect::<Result<_>>(),
)
})
.map(|(k, v)| match v {
Ok(v) => Ok((k, v)),
Err(e) => Err(e),
})
.collect::<Result<_>>()?;
// Determine the topological ordering of the packages.
let pkgs = {
// Assign a rank to each package. A package's rank will be strictly
// smaller than the rank of all its dependencies. This yields a
// topological ordering.
let mut ranks: IndexMap<DependencyRef, usize> =
graph.keys().map(|&id| (id, 0)).collect();
let mut pending = IndexSet::new();
for name in self.manifest.dependencies.keys() {
if !(names.contains_key(name)) {
return Err(Error::new(format!(
"`Bender.yml` contains dependency `{}` but `Bender.lock` does not.\n\
\tYou may need to run `bender update`.",
name
)));
}
}
pending.extend(self.manifest.dependencies.keys().map(|name| names[name]));
let mut cyclic = false;
while !pending.is_empty() {
let mut current_pending = IndexSet::new();
swap(&mut pending, &mut current_pending);
for id in current_pending {
let min_dep_rank = ranks[&id] + 1;
for &dep_id in &graph[&id] {
if ranks[&dep_id] <= min_dep_rank {
ranks.insert(dep_id, min_dep_rank);
pending.insert(dep_id);
}
}
// Limit rank to two times graph length, which is sufficient except if there is
// a cyclic dependency
if ranks[&id] > 2 * graph.len() {
cyclic = true;
}
}
if cyclic {
let mut pend_str = vec![];
for element in pending.iter() {
pend_str.push(self.dependency_name(*element));
}
return Err(Error::new(format!(
"a cyclical dependency was discovered, likely relates to one of {:?}.\n\
\tPlease ensure no dependency loops.",
pend_str
)));
}
}
debugln!("sess: topological ranks {:#?}", ranks);
// Group together packages with the same rank, to build the final
// ordering.
let num_ranks = ranks.values().map(|v| v + 1).max().unwrap_or(0);
let pkgs: Vec<Vec<DependencyRef>> = (0..num_ranks)
.rev()
.map(|rank| {
let mut v: Vec<_> = ranks
.iter()
.filter_map(|(&k, &v)| if v == rank { Some(k) } else { None })
.collect();
v.sort_by(|&a, &b| self.dependency_name(a).cmp(self.dependency_name(b)));
v
})
.collect();
pkgs
};
debugln!("sess: names {:?}", names);
debugln!("sess: graph {:?}", graph);
debugln!("sess: pkgs {:?}", pkgs);
*self.names.lock().unwrap() = names;
*self.graph.lock().unwrap() = Arc::new(graph);
*self.pkgs.lock().unwrap() = Arc::new(pkgs);
Ok(())
}
/// Obtain information on a dependency.
pub fn dependency(&self, dep: DependencyRef) -> &'ctx DependencyEntry {
// TODO: Don't make any clones! Use an arena instead.
self.deps.lock().unwrap().list[dep.0]
}
/// Determine the name of a dependency.
pub fn dependency_name(&self, dep: DependencyRef) -> &'ctx str {
self.intern_string(self.deps.lock().unwrap().list[dep.0].name.as_str())
}
/// Determine the source of a dependency.
pub fn dependency_source(&self, dep: DependencyRef) -> DependencySource {
// TODO: Don't make any clones! Use an arena instead.
self.deps.lock().unwrap().list[dep.0].source.clone()
}
/// Resolve a dependency name to a reference.
///
/// Returns an error if the dependency does not exist.
pub fn dependency_with_name(&self, name: &str) -> Result<DependencyRef> {
let result = self.names.lock().unwrap().get(name).copied();
match result {
Some(id) => Ok(id),
None => Err(Error::new(format!(
"Dependency `{}` does not exist. Did you forget to add it to the manifest?",
name
))),
}
}
/// Internalize a path.
///
/// This allocates the path in the arena and returns a reference to it whose
/// lifetime is bound to the arena rather than this `Session`. Useful to
/// obtain a lightweight pointer to a path that is guaranteed to outlive the
/// `Session`.
pub fn intern_path<T>(&self, path: T) -> &'ctx Path
where
T: Into<PathBuf> + AsRef<Path>,
{
let mut paths = self.paths.lock().unwrap();
if let Some(&p) = paths.get(path.as_ref()) {
p
} else {
let p = self.arenas.path.alloc(path.into());
paths.insert(p);
p
}
}
/// Internalize a string.
///
/// This allocates the string in the arena and returns a reference to it
/// whose lifetime is bound to the arena rather than this `Session`. Useful
/// to obtain a lightweight pointer to a string that is guaranteed to
/// outlive the `Session`.
pub fn intern_string<T>(&self, string: T) -> &'ctx str
where
T: Into<String> + AsRef<str>,
{
let mut strings = self.strings.lock().unwrap();
if let Some(&s) = strings.get(string.as_ref()) {
s
} else {
let s = self.arenas.string.alloc(string.into());
strings.insert(s);
s
}
}
/// Internalize a manifest.
///
/// This allocates the manifest in the arena and returns a reference to it
/// whose lifetime is bound to the arena rather than this `Session`. Useful
/// to obtain a lightweight pointer to a manifest that is guaranteed to
/// outlive the `Session`.
pub fn intern_manifest<T>(&self, manifest: T) -> &'ctx Manifest
where
T: Into<Manifest>,
{
self.arenas.manifest.alloc(manifest.into())
}
/// Internalize a dependency entry.
pub fn intern_dependency_entry(&self, entry: DependencyEntry) -> &'ctx DependencyEntry {
self.arenas.dependency_entry.alloc(entry)
}
/// Access the package dependency graph.
pub fn graph(&self) -> Arc<IndexMap<DependencyRef, IndexSet<DependencyRef>>> {
self.graph.lock().unwrap().clone()
}
/// Access the topological sorting of the packages.
pub fn packages(&self) -> Arc<Vec<Vec<DependencyRef>>> {
self.pkgs.lock().unwrap().clone()
}
/// Load the sources in a manifest into a source group.
pub fn load_sources(
&self,
sources: &'ctx config::Sources,
package: Option<&'ctx str>,
dependencies: IndexSet<String>,
dependency_export_includes: IndexMap<String, IndexSet<&'ctx Path>>,
version: Option<Version>,
) -> SourceGroup<'ctx> {
let include_dirs: IndexSet<&Path> =
IndexSet::from_iter(sources.include_dirs.iter().map(|d| self.intern_path(d)));
let defines = sources
.defines
.iter()
.map(|(k, v)| {
(
self.intern_string(k),
v.as_ref().map(|v| self.intern_string(v)),
)
})
.collect();
let files = sources
.files
.iter()
.map(|file| match *file {
config::SourceFile::File(ref path) => (path as &Path).into(),
config::SourceFile::Group(ref group) => self
.load_sources(
group.as_ref(),
None,
dependencies.clone(),
dependency_export_includes.clone(),
version.clone(),
)
.into(),
})
.collect();
SourceGroup {
package,
independent: false,
target: sources.target.clone(),
include_dirs: include_dirs.clone(),
export_incdirs: dependency_export_includes.clone(),
defines,
files,
dependencies,
version,
}
}
}
/// An event loop to perform IO within a session.
///
/// This struct wraps a `Session` and keeps an additional event loop. Using the
/// various functions provided, IO can be scheduled on this event loop. The
/// futures may then be driven to completion using the `run()` function.
pub struct SessionIo<'sess, 'ctx: 'sess> {
/// The underlying session.
pub sess: &'sess Session<'ctx>,
git_versions: Mutex<IndexMap<PathBuf, GitVersions<'ctx>>>,
}
impl<'io, 'sess: 'io, 'ctx: 'sess> SessionIo<'sess, 'ctx> {
/// Create a new session wrapper.
pub fn new(sess: &'sess Session<'ctx>) -> SessionIo<'sess, 'ctx> {
SessionIo {
sess,
git_versions: Mutex::new(IndexMap::new()),
}
}
/// Determine the available versions for a dependency.
pub async fn dependency_versions(
&'io self,
dep_id: DependencyRef,
force_fetch: bool,
) -> Result<DependencyVersions<'ctx>> {
self.sess.stats.num_calls_dependency_versions.increment();
let dep = self.sess.dependency(dep_id);
match dep.source {
DependencySource::Registry => {
unimplemented!("determine available versions of registry dependency");
}
DependencySource::Path(_) => Ok(DependencyVersions::Path),
DependencySource::Git(ref url) => {
let db = self.git_database(&dep.name, url, force_fetch, None).await?;
self.git_versions_func(db)
.await
.map(DependencyVersions::Git)
}
}
}
/// Access the git database for a dependency.
///
/// If the database does not exist, it is created. If the database has not
/// been updated recently, the remote is fetched.
async fn git_database(
&'io self,
name: &str,
url: &str,
force_fetch: bool,
fetch_ref: Option<&str>,
) -> Result<Git<'ctx>> {
// TODO: Make the assembled future shared and keep it in a lookup table.
// Then use that table to return the future if it already exists.
// This ensures that the gitdb is setup only once, and makes the
// whole process faster for later calls.
self.sess.stats.num_calls_git_database.increment();
// Determine the name of the database as the given name and the first
// 8 bytes (16 hex characters) of the URL's BLAKE2 hash.
use blake2::{Blake2b512, Digest};
let hash = &format!("{:016x}", Blake2b512::digest(url.as_bytes()))[..16];
let db_name = format!("{}-{}", name, hash);
// Determine the location of the git database and create it if its does
// not yet exist.
let db_dir = self
.sess
.config
.database
.join("git")
.join("db")
.join(db_name);
let db_dir = self.sess.intern_path(db_dir);
match std::fs::create_dir_all(db_dir) {
Ok(_) => (),
Err(cause) => {
return Err(Error::chain(
format!("Failed to create git database directory {:?}.", db_dir),
cause,
))
}
};
let git = Git::new(db_dir, &self.sess.config.git);
let name2 = String::from(name);
let url = String::from(url);
let url2 = url.clone();
let url3 = url.clone();
// Either initialize the repository or update it if needed.
if !db_dir.join("config").exists() {
if self.sess.local_only {
return Err(Error::new(
"Bender --local argument set, unable to initialize git dependency. \n\
\tPlease update without --local, or provide a path to the missing dependency.",
));
}
// Initialize.
self.sess.stats.num_database_init.increment();
// TODO MICHAERO: May need throttle
future::lazy(|_| {
stageln!("Cloning", "{} ({})", name2, url2);
Ok(())
})
.and_then(|_| git.spawn_with(|c| c.arg("init").arg("--bare")))
.and_then(|_| git.spawn_with(|c| c.arg("remote").arg("add").arg("origin").arg(url)))
.and_then(|_| git.fetch("origin"))
.and_then(|_| async {
if let Some(reference) = fetch_ref {
git.fetch_ref("origin", reference).await
} else {
Ok(())
}
})
.await
.map_err(move |cause| {
if url3.contains("git@") {
warnln!("Please ensure your public ssh key is added to the git server.");
}
warnln!("Please ensure the url is correct and you have access to the repository.");
Error::chain(
format!("Failed to initialize git database in {:?}.", db_dir),
cause,
)
})
.map(move |_| git)
} else {
// Update if the manifest has been modified since the last fetch.
let db_mtime = try_modification_time(db_dir.join("FETCH_HEAD"));
if (self.sess.manifest_mtime < db_mtime && !force_fetch) || self.sess.local_only {
debugln!("sess: skipping fetch of {:?}", db_dir);
return Ok(git);
}
self.sess.stats.num_database_fetch.increment();
// TODO MICHAERO: May need throttle
future::lazy(|_| {
stageln!("Fetching", "{} ({})", name2, url2);
Ok(())
})
.and_then(|_| git.fetch("origin"))
.and_then(|_| async {
if let Some(reference) = fetch_ref {
git.fetch_ref("origin", reference).await
} else {
Ok(())
}
})
.await
.map_err(move |cause| {
if url3.contains("git@") {
warnln!("Please ensure your public ssh key is added to the git server.");
}
warnln!("Please ensure the url is correct and you have access to the repository.");
Error::chain(
format!("Failed to update git database in {:?}.", db_dir),
cause,
)
})
.map(move |_| git)
}
}
/// Determine the list of versions available for a git dependency.
pub async fn git_versions_func(&'io self, git: Git<'ctx>) -> Result<GitVersions<'ctx>> {
let versions_tmp = self.git_versions.lock().unwrap().clone();
match versions_tmp.get(&git.path.to_path_buf()) {
Some(result) => {
debugln!("sess: git_versions from stored");
Ok(GitVersions {
versions: result.versions.clone(),
refs: result.refs.clone(),
revs: result.revs.clone(),
})
}
None => {
debugln!("sess: git_versions get new");
let dep_refs = git.list_refs().await;
let dep_revs = git.list_revs().await;
let dep_refs_and_revs = dep_refs.and_then(|refs| -> Result<_> {
if refs.is_empty() {
Ok((refs, vec![]))
} else {
dep_revs.map(move |revs| (refs, revs))
}
});
dep_refs_and_revs.and_then(move |(refs, revs)| {
let refs: Vec<_> = refs
.into_iter()
.map(|(a, b)| (self.sess.intern_string(a), self.sess.intern_string(b)))
.collect();
let revs: Vec<_> = revs
.into_iter()
.map(|s| self.sess.intern_string(s))
.collect();
debugln!("sess: refs {:?}", refs);
let (tags, branches) = {
// Create a lookup table for the revisions. This will be used to
// only accept refs that point to actual revisions.
let rev_ids: IndexSet<&str> = revs.iter().copied().collect();
// Split the refs into tags and branches, discard
// everything else.
let mut tags = IndexMap::<&'ctx str, &'ctx str>::new();
let mut branches = IndexMap::<&'ctx str, &'ctx str>::new();
let tag_pfx = "refs/tags/";
let branch_pfx = "refs/remotes/origin/";
for (hash, rf) in refs {
if !rev_ids.contains(hash) {
continue;
}
if let Some(stripped) = rf.strip_prefix(tag_pfx) {
tags.insert(stripped, hash);
} else if let Some(stripped) = rf.strip_prefix(branch_pfx) {
branches.insert(stripped, hash);
}
}
(tags, branches)
};
// Extract the tags that look like semantic versions.
let mut versions: Vec<(semver::Version, &'ctx str)> = tags
.iter()
.filter_map(|(tag, &hash)| {
if let Some(stripped) = tag.strip_prefix('v') {
match semver::Version::parse(stripped) {
Ok(v) => Some((v, hash)),
Err(_) => None,
}
} else {
None
}
})
.collect();
versions.sort_by(|a, b| b.cmp(a));
// Merge tags and branches.
let refs: IndexMap<&str, &str> =
branches.into_iter().chain(tags.into_iter()).collect();
let mut git_versions = self.git_versions.lock().unwrap().clone();
let git_path = git.path;
git_versions.insert(
git_path.to_path_buf(),
GitVersions {
versions: versions.clone(),
refs: refs.clone(),
revs: revs.clone(),
},
);
*self.git_versions.lock().unwrap() = git_versions.clone();
Ok(GitVersions {
versions,
refs,
revs,
})
})
}
}
}
/// Get the path of a dependency
pub fn get_package_path(&'io self, dep_id: DependencyRef) -> PathBuf {
let dep = self.sess.dependency(dep_id);
// Determine the name of the checkout as the given name and the first
// 8 bytes (16 hex characters) of a BLAKE2 hash of the source and the
// root package name. This ensures that for every dependency and
// root package we have at most one checkout. (If multiple versions of
// the same package have access to the same dependency collection, this
// may need to be updated.)
let hash = {
use blake2::{Blake2b512, Digest};
let mut hasher = Blake2b512::new();
match dep.source {
DependencySource::Registry => unimplemented!(),
DependencySource::Git(ref url) => hasher.update(url.as_bytes()),
DependencySource::Path(ref path) => {
// Determine and canonicalize the dependency path, and
// immediately return it.
let path = self.sess.root.join(path);
let path = match canonicalize(&path) {
Ok(p) => p,
Err(_) => path,
};
return path;
}
}
hasher.update(format!("{:?}", self.sess.manifest.package.name).as_bytes());
&format!("{:016x}", hasher.finalize())[..16]
};
let checkout_name = format!("{}-{}", dep.name, hash);
// Determine the location of the git checkout. If the workspace has an
// explicit checkout directory, use that and do not append any hash to
// the dependency name.
match self.sess.manifest.workspace.checkout_dir {
Some(ref cd) => cd.join(&dep.name),
None => self
.sess
.config
.database
.join("git")
.join("checkouts")
.join(checkout_name),
}
}
/// Ensure that a dependency is checked out and obtain its path.
pub async fn checkout(&'io self, dep_id: DependencyRef) -> Result<&'ctx Path> {
// Check if the checkout is already in the cache.
if let Some(&cached) = self.sess.cache.checkout.lock().unwrap().get(&dep_id) {
return Ok(cached);
}
self.sess.stats.num_calls_checkout.increment();
let dep = self.sess.dependency(dep_id);
match dep.source {
DependencySource::Registry => unimplemented!(),
DependencySource::Git(..) => {}
DependencySource::Path(..) => {
let path = self
.sess
.intern_path(self.get_package_path(dep_id).as_path());
return Ok(path);
}
}
let checkout_dir = self.sess.intern_path(self.get_package_path(dep_id));
match dep.source {
DependencySource::Path(..) => unreachable!(),
DependencySource::Registry => unimplemented!(),
DependencySource::Git(ref url) => self
.checkout_git(
self.sess.intern_string(&dep.name),
checkout_dir,
self.sess.intern_string(url),
self.sess.intern_string(dep.revision.as_ref().unwrap()),
)
.await
.and_then(move |path| {
self.sess
.cache
.checkout
.lock()
.unwrap()
.insert(dep_id, path);
Ok(path)
}),
}
}
/// Ensure that a proper git checkout exists.
///
/// If the directory is not a proper git repository, it is deleted and
/// re-created from scratch.
async fn checkout_git(
&'io self,
name: &'ctx str,
path: &'ctx Path,
url: &'ctx str,
revision: &'ctx str,
) -> Result<&'ctx Path> {
// First check if we have to get rid of the current checkout. This is
// the case if it either does not exist or the checked out revision does
// not match what we expect.
future::lazy(|_| Ok(path.exists()))
.and_then(|exists| async move {
if exists {
// Never scrap checkouts the user asked for explicitly in
// the workspace configuration.
if self.sess.manifest.workspace.checkout_dir.is_some() {
return Ok(false);
}
// Scrap checkouts with the wrong tag.
Git::new(path, &self.sess.config.git)
.current_checkout()
.then(|current| async {
Ok(match current {
Ok(Some(current)) => {
debugln!(
"checkout_git: currently `{}` (want `{}`)",
current,
revision
);
current != revision
}
_ => true,
})
})
.await
} else {
// Don't do anything if there is no checkout.
Ok(false)
}
})
.and_then(|clear| async move {
if clear {
debugln!("checkout_git: clear checkout {:?}", path);
std::fs::remove_dir_all(path).map_err(|cause| {
Error::chain(
format!("Failed to remove checkout directory {:?}.", path),
cause,
)
})
} else {
Ok(())
}
})
.await?;
// Perform the checkout if necessary.
// TODO MICHAERO: May need proper chaining to previous future using and_then
if !path.exists() {
stageln!("Checkout", "{} ({})", name, url);
// First generate a tag to be cloned in the database. This is
// necessary since `git clone` does not accept commits, but only
// branches or tags for shallow clones.
let tag_name_0 = format!("bender-tmp-{}", revision);
let tag_name_1 = tag_name_0.clone();
let git = self.git_database(name, url, false, Some(revision)).await?;
git.spawn_with(move |c| c.arg("tag").arg(tag_name_0).arg(revision).arg("--force"))
.map_err(move |cause| {
warnln!("Please ensure the commits are available on the remote or run bender update");
Error::chain(format!("Failed to checkout commit {} for {} given in Bender.lock.\n", revision, name),
cause,
)
})
.await?;
git.spawn_with(move |c| {
c.arg("clone")
.arg(git.path)
.arg(path)
.arg("--recursive")
.arg("--branch")
.arg(tag_name_1)
})
.await?;
}
Ok(path)
}
/// Checkout only git dependency's path sub-dependency Bender.yml files
#[async_recursion(?Send)]
async fn sub_dependency_fixing(
&'io self,
dep_iter_mut: &mut IndexMap<String, config::Dependency>,
top_package_name: String,
reference_path: &Path,
dep_base_path: &Path,
db: Git<'ctx>,
used_git_rev: &str,
) -> Result<()> {
for dep in (dep_iter_mut).iter_mut() {
if let (_, config::Dependency::Path(ref path)) = dep {
if !path.starts_with("/") {
warnln!("Path dependencies ({:?}) in git dependencies ({:?}) currently not fully supported. Your mileage may vary.", dep.0, top_package_name);
let sub_entries = db
.list_files(
used_git_rev,
Some(
reference_path
.strip_prefix(dep_base_path)
.unwrap()
.join(path)
.join("Bender.yml"),
),
)
.await?;
let sub_data = match sub_entries.into_iter().next() {
None => Ok(None),
Some(sub_entry) => db.cat_file(sub_entry.hash).await.map(Some),
}?;
let sub_dep_path = reference_path.join(path).clone();
let tmp_path = self.sess.root.join(".bender").join("tmp");
if let Some(full_sub_data) = sub_data.clone() {
if !tmp_path.exists() {
std::fs::create_dir_all(tmp_path.clone())?;
}
let mut sub_file = std::fs::OpenOptions::new()
.write(true)
.truncate(true)
.create(true)
.open(tmp_path.join(format!("{}_manifest.yml", dep.0)))?;
writeln!(&mut sub_file, "{}", full_sub_data)?;
sub_file.flush()?;
}
*dep.1 = config::Dependency::Path(sub_dep_path.clone());
// Further dependencies
let _manifest: Result<_> = match sub_data {
Some(data) => {
let partial: config::PartialManifest = serde_yaml::from_str(&data)
.map_err(|cause| {
Error::chain(
format!(
"Syntax error in manifest of dependency `{}` at \
revision `{}`.",
dep.0, used_git_rev
),
cause,
)
})?;
let mut full = partial.validate().map_err(|cause| {
Error::chain(
format!(
"Error in manifest of dependency `{}` at revision \
`{}`.",
dep.0, used_git_rev
),
cause,
)
})?;
self.sub_dependency_fixing(
&mut full.dependencies,
full.package.name.clone(),
&sub_dep_path,
dep_base_path,
db,
used_git_rev,
)
.await?;
Ok(())
}
None => Ok(()),
};
}
}
}
Ok(())
}
/// Load the manifest for a specific version of a dependency.
///
/// Loads and returns the manifest for a dependency at a specific version.
/// Returns `None` if the dependency has no manifest.
pub async fn dependency_manifest_version(
&'io self,
dep_id: DependencyRef,
version: DependencyVersion<'ctx>,
) -> Result<Option<&'ctx Manifest>> {
// Check if the manifest is already in the cache.
let cache_key = (dep_id, version);
if let Some(&cached) = self
.sess
.cache
.dependency_manifest_version
.lock()
.unwrap()
.get(&cache_key)
{
return Ok(cached);
}
self.sess