-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathtree.rs
1979 lines (1722 loc) · 62.1 KB
/
tree.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 (C) 2019 Josh Gao
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::iter::FromIterator;
use std::ops::Deref;
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use anyhow::{Context, Error};
use chrono::prelude::*;
use progpool::{ExecutionResult, ExecutionResults, Job, Pool};
use url::Url;
use walkdir::WalkDir;
use crate::util::*;
use crate::*;
use config::{ManifestConfig, RemoteConfig};
use depot::Depot;
use manifest::FileOperation;
pub struct Tree {
pub path: PathBuf,
pub config: TreeConfig,
}
#[derive(Copy, Clone, PartialEq)]
pub enum FetchType {
/// Fetch the manifest, then fetch everything.
Fetch,
/// Fetch everything but the manifest.
FetchExceptManifest,
/// Don't fetch anything, use only the local cache.
NoFetch,
}
#[derive(Clone, PartialEq, Eq)]
pub enum FetchTarget {
/// Fetch whatever each project has specified as its upstream revision.
Upstream,
/// Fetch specific revisions for the project.
Specific(HashSet<String>),
/// Fetch everything.
All,
}
impl FetchTarget {
fn empty() -> FetchTarget {
FetchTarget::Specific(HashSet::new())
}
fn reify<T: Into<String>>(&self, upstream_rev: T) -> FetchTarget {
match self {
FetchTarget::Upstream => {
let mut set = HashSet::new();
set.insert(upstream_rev.into());
FetchTarget::Specific(set)
}
x => x.clone(),
}
}
fn merge(&mut self, other: &FetchTarget) {
if *self == FetchTarget::Upstream || *other == FetchTarget::Upstream {
panic!("unreified FetchTarget");
}
if *self == FetchTarget::All || *other == FetchTarget::All {
*self = FetchTarget::All;
return;
}
match self {
FetchTarget::Specific(ref mut lhs) => match other {
FetchTarget::Specific(ref rhs) => {
*lhs = lhs.union(rhs).cloned().collect();
}
_ => unreachable!(),
},
_ => unreachable!(),
}
}
}
#[derive(Copy, Clone, PartialEq)]
pub enum CheckoutType {
Checkout,
RefsOnly,
NoCheckout,
}
#[derive(Clone, Debug)]
pub enum GroupFilter {
Include(String),
Exclude(String),
}
impl GroupFilter {
fn filter_project(filters: &[GroupFilter], project: &manifest::Project) -> bool {
let groups = project.groups.as_deref().unwrap_or(&[]);
let default = filters.is_empty()
|| filters.iter().any(|x| match x {
GroupFilter::Include(group) => group == "default",
GroupFilter::Exclude(_) => false,
});
let mut included = default && !groups.iter().any(|x| x == "notdefault");
let mut excluded = false;
for filter in filters {
match filter {
GroupFilter::Include(group) => {
if groups.contains(group) {
included = true;
}
}
GroupFilter::Exclude(group) => {
if groups.contains(group) {
excluded = true;
}
}
}
}
included && !excluded
}
}
// toml-rs can't serialize enums.
impl serde::Serialize for GroupFilter {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match self {
GroupFilter::Include(group) => serializer.serialize_str(group),
GroupFilter::Exclude(group) => serializer.serialize_str(&("-".to_string() + group)),
}
}
}
struct GroupFilterVisitor;
impl<'de> serde::de::Visitor<'de> for GroupFilterVisitor {
type Value = GroupFilter;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a group")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
if value.starts_with('-') {
let string = value[1..].to_string();
if string.is_empty() {
Err(E::custom("empty group name"))
} else {
Ok(GroupFilter::Exclude(string))
}
} else if value.is_empty() {
Err(E::custom("empty group name"))
} else {
Ok(GroupFilter::Include(value.to_string()))
}
}
}
impl<'de> serde::Deserialize<'de> for GroupFilter {
fn deserialize<D>(deserializer: D) -> Result<GroupFilter, D::Error>
where
D: serde::Deserializer<'de>,
{
deserializer.deserialize_str(GroupFilterVisitor)
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct TreeConfig {
pub remote: String,
pub branch: String,
pub manifest: String,
pub tags: Vec<String>,
pub projects: Vec<String>,
pub group_filters: Option<Vec<GroupFilter>>,
}
#[derive(Clone, Debug)]
pub struct ProjectInfo {
pub project_path: String,
pub project_name: String,
pub remote: String,
pub revision: String,
pub file_ops: Vec<manifest::FileOperation>,
pub manifest_project: bool,
}
#[derive(Debug, PartialEq)]
pub enum FileState {
New,
Modified,
Deleted,
Renamed,
TypeChange,
Unchanged,
}
impl FileState {
pub fn to_char(&self) -> char {
match self {
FileState::New => 'a',
FileState::Modified => 'm',
FileState::Deleted => 'd',
FileState::Renamed => 'r',
FileState::TypeChange => 'd',
FileState::Unchanged => '-',
}
}
}
#[derive(Debug)]
pub struct FileStatus {
pub filename: String,
pub index: FileState,
pub worktree: FileState,
}
#[derive(Debug)]
pub struct ProjectStatus {
pub name: String,
pub path: String,
pub branch: Option<String>,
pub commit: git2::Oid,
pub commit_summary: Option<String>,
pub files: Vec<FileStatus>,
pub ahead: usize,
pub behind: usize,
}
pub struct BranchInfo<'repo> {
pub name: String,
pub commit: git2::Commit<'repo>,
}
impl<'repo> BranchInfo<'repo> {
fn from_branch(branch: git2::Branch) -> Result<BranchInfo, Error> {
let name = branch
.name()
.context("could not determine branch name")?
.ok_or_else(|| format_err!("branch name is not valid UTF-8"))?;
let commit = branch
.get()
.peel_to_commit()
.context(format!("failed to get commit for {}", name))?;
Ok(BranchInfo {
name: name.to_string(),
commit,
})
}
fn from_ref(reference: git2::Reference) -> Result<BranchInfo, Error> {
ensure!(reference.is_branch(), "expected reference to refer to a branch");
BranchInfo::from_branch(git2::Branch::wrap(reference))
}
fn from_branch_name(
repo: &'repo git2::Repository,
branch_name: &str,
branch_type: git2::BranchType,
) -> Result<BranchInfo<'repo>, Error> {
BranchInfo::from_branch(repo.find_branch(branch_name, branch_type).context(format!(
"could not find {} branch {}",
match branch_type {
git2::BranchType::Local => "local",
git2::BranchType::Remote => "remote",
},
branch_name
))?)
}
fn name_without_remote(&self) -> &str {
let components: Vec<&str> = self.name.split('/').collect();
assert!(components.len() == 1 || components.len() == 2);
components.last().unwrap()
}
}
struct CommitSummary {
pub id: git2::Oid,
pub summary: String,
}
struct UploadSummary {
pub project_path: String,
pub src_branch: String,
pub dest_remote: String,
pub dest_branch: String,
pub commit_summaries: Vec<CommitSummary>,
}
fn confirm_upload(upload_summaries: Vec<&UploadSummary>, autosubmit: bool) -> Result<(), Error> {
let mut lines: Vec<String> = Vec::new();
for upload_summary in upload_summaries {
let is_aosp = upload_summary.dest_remote == "aosp";
lines.push(format!(
"{}: {} commit{} from branch {} to {}{}{}",
PROJECT_STYLE.apply_to(&upload_summary.project_path),
upload_summary.commit_summaries.len(),
if upload_summary.commit_summaries.len() == 1 {
""
} else {
"s"
},
BRANCH_STYLE.apply_to(&upload_summary.src_branch),
if is_aosp {
AOSP_REMOTE_STYLE.apply_to(&upload_summary.dest_remote)
} else {
NON_AOSP_REMOTE_STYLE.apply_to(&upload_summary.dest_remote)
},
SLASH_STYLE.apply_to("/"),
BRANCH_STYLE.apply_to(&upload_summary.dest_branch),
));
for commit_summary in &upload_summary.commit_summaries {
lines.push(format!(
" {:.10} {}",
console::style(commit_summary.id).cyan(),
commit_summary.summary
))
}
}
lines.push(format!(
"Continue with upload? {}[y/N]? ",
if autosubmit {
format!("({}) ", console::style("autosubmit enabled").red().bold())
} else {
"".into()
}
));
print!("{}", lines.join("\n"));
std::io::stdout().flush()?;
let line = util::read_line()?;
match line.as_str() {
"y" | "Y" => {
// Print an extra newline to separate gerrit's output from the confirmation prompt.
println!();
Ok(())
}
_ => Err(format_err!("upload aborted by user")),
}
}
fn summarize_upload(
project_path: &str,
repo: &git2::Repository,
src: &BranchInfo,
dest: &BranchInfo,
dest_remote: &str,
commits: &[git2::Oid],
) -> Result<UploadSummary, Error> {
let mut commit_summaries: Vec<CommitSummary> = Vec::new();
for commit_oid in commits {
let commit = repo
.find_commit(*commit_oid)
.context(format!("could not find commit matching {}", commit_oid))?;
commit_summaries.push(CommitSummary {
id: commit.id(),
summary: commit
.summary()
.ok_or_else(|| format_err!("commit message for {} is not valid UTF-8", commit.id()))?
.to_string(),
})
}
Ok(UploadSummary {
project_path: project_path.to_string(),
src_branch: src.name.to_string(),
dest_remote: dest_remote.to_string(),
dest_branch: dest.name_without_remote().to_string(),
commit_summaries,
})
}
impl Tree {
pub fn construct<T: Into<PathBuf>>(
depot: &Depot,
path: T,
manifest_config: &ManifestConfig,
remote_config: &RemoteConfig,
branch: &str,
file: &str,
group_filters: Vec<GroupFilter>,
fetch: bool,
) -> Result<Tree, Error> {
let tree_root = path.into();
// TODO: Add locking?
util::assert_empty_directory(&tree_root)?;
let pore_path = tree_root.join(".pore");
std::fs::create_dir_all(&pore_path).context(format!("failed to create directory {:?}", pore_path))?;
let manifest_path = pore_path.join("manifest");
let manifest_file = PathBuf::from("manifest").join(file);
create_symlink(manifest_file, pore_path.join("manifest.xml")).context("failed to create manifest symlink")?;
let manifest_project = &manifest_config.project;
if fetch {
depot.fetch_repo(
&remote_config,
manifest_project,
Some(&[branch.to_string()]),
false,
None,
)?;
}
depot.clone_repo(&remote_config, manifest_project, &branch, &manifest_path)?;
let tree_config = TreeConfig {
remote: remote_config.name.clone(),
branch: branch.into(),
manifest: manifest_config.project.clone(),
tags: Vec::new(),
projects: Vec::new(),
group_filters: Some(group_filters),
};
let tree = Tree {
path: tree_root,
config: tree_config,
};
tree.write_config()?;
Ok(tree)
}
pub fn from_path<T: Into<PathBuf>>(path: T) -> Result<Tree, Error> {
let path: PathBuf = path.into();
if path.join(".pore").exists() {
let config = Tree::read_config(&path)?;
Ok(Tree { path, config })
} else {
Err(format_err!("failed to find tree at {:?}", path))
}
}
pub fn find_from_path<T: Into<PathBuf>>(path: T) -> Result<Tree, Error> {
let original_path: PathBuf = path.into();
let mut path: PathBuf = original_path.clone();
while !path.join(".pore").exists() {
if let Some(parent) = path.parent() {
path = parent.to_path_buf();
} else {
bail!("failed to find tree enclosing {:?}", original_path);
}
}
Tree::from_path(path)
}
fn write_config(&self) -> Result<(), Error> {
let text = toml::to_string_pretty(&self.config).context("failed to serialize tree config")?;
Ok(std::fs::write(self.path.join(".pore").join("tree.toml"), text).context("failed to write tree config")?)
}
fn read_config<T: AsRef<Path>>(tree_root: T) -> Result<TreeConfig, Error> {
let tree_root: &Path = tree_root.as_ref();
let text =
std::fs::read_to_string(tree_root.join(".pore").join("tree.toml")).context("failed to read tree config")?;
Ok(toml::from_str(&text).context("failed to deserialize tree config")?)
}
pub fn read_manifest(&self) -> Result<Manifest, Error> {
let manifest_path = self.path.join(".pore").join("manifest");
let manifest_file = self.path.join(".pore").join("manifest.xml");
let manifest = Manifest::parse(&manifest_path, &manifest_file).context("failed to read manifest")?;
Ok(manifest)
}
pub fn collect_manifest_projects(
&self,
config: Arc<Config>,
manifest: &Manifest,
under: Option<Vec<PathBuf>>,
) -> Result<Vec<ProjectInfo>, Error> {
let default_revision = manifest
.default
.as_ref()
.and_then(|def| def.revision.clone())
.unwrap_or_else(|| self.config.branch.clone());
let group_filters = self.config.group_filters.as_deref().unwrap_or(&[]);
// The correctness of this seems dubious if the paths are accessed via symlinks or mount points,
// but repo doesn't handle this either.
let tree_root = std::fs::canonicalize(&self.path).context("failed to canonicalize tree path")?;
let mut paths = Vec::new();
for path in under.unwrap_or_default() {
let requested_path =
std::fs::canonicalize(&path).context(format!("failed to canonicalize requested path '{}'", path.display()))?;
paths.push(
pathdiff::diff_paths(&requested_path, &tree_root)
.ok_or_else(|| format_err!("failed to calculate path diff for {}", path.display()))?,
);
}
let filtered_projects = manifest
.projects
.iter()
.filter(|(_project_path, project)| GroupFilter::filter_project(&group_filters, &project))
.filter(|(project_path, _project)| {
paths.is_empty() || paths.iter().any(|path| Path::new(path).starts_with(project_path))
});
let mut projects = Vec::new();
for (project_path, project) in filtered_projects {
let (remote, remote_config) = manifest.resolve_project_remote(&config, &self.config, project)?;
let revision = project
.revision
.clone()
.or_else(|| remote_config.revision.clone())
.or_else(|| manifest.default.as_ref().and_then(|m| m.revision.clone()))
.unwrap_or_else(|| default_revision.clone());
projects.push(ProjectInfo {
project_path: project_path.to_str().expect("project path not UTF-8").into(),
project_name: project.name.clone(),
remote,
revision,
file_ops: project.file_operations.clone(),
manifest_project: false,
});
}
Ok(projects)
}
fn sync_repos(
&mut self,
pool: &mut Pool,
config: Arc<Config>,
projects: Vec<ProjectInfo>,
fetch_target: Option<FetchTarget>,
checkout: CheckoutType,
do_project_cleanup: bool,
detach: bool,
fetch_tags: bool,
ssh_masters: &mut HashMap<String, std::process::Child>,
no_lfs: bool,
) -> Result<i32, Error> {
let config = Arc::new(config.clone());
let projects: Vec<Arc<_>> = projects.into_iter().map(Arc::new).collect();
if let Some(target) = fetch_target {
let target: Arc<FetchTarget> = Arc::new(target);
let mut job = Job::with_name("fetching");
// The same underlying repository might be checked out into multiple directories.
#[derive(PartialEq, Eq, Hash)]
struct FetchProject {
remote: String,
project_name: String,
}
let mut fetch_projects = HashMap::<FetchProject, FetchTarget>::new();
let mut remote_names = HashSet::new();
for project in &projects {
let key = FetchProject {
remote: project.remote.clone(),
project_name: project.project_name.clone(),
};
let local_target = target.clone().reify(&project.revision);
fetch_projects
.entry(key)
.or_insert_with(|| FetchTarget::empty())
.merge(&local_target);
remote_names.insert(project.remote.clone());
}
// Spawn an ssh ControlMaster to eliminate ssh startup latency.
for remote_name in remote_names {
let remote = match config.find_remote(&remote_name) {
Ok(x) => x,
Err(_) => continue,
};
if let Ok(parsed) = Url::parse(&remote.url) {
if parsed.scheme() != "ssh" {
continue;
}
if let Some(host) = parsed.host_str() {
ssh_masters.entry(host.into()).or_insert_with(|| {
let mut cmd = std::process::Command::new("ssh");
cmd.arg("-M");
cmd.arg("-N");
cmd.arg("-o").arg(format!("ControlPath {}", ssh_mux_path()));
cmd.arg(host);
cmd.spawn().expect("failed to start ssh ControlMaster")
});
}
}
}
for (project, target) in &fetch_projects {
let config = Arc::clone(&config);
let project_name = project.project_name.clone();
let remote_name = project.remote.clone();
let target = target.clone();
job.add_task(project_name.clone(), move |_| -> Result<(), Error> {
let remote = config
.find_remote(&remote_name)
.context(format!("failed to find remote {}", remote_name))?;
let depot = config
.find_depot(&remote.depot)
.context(format!("failed to find depot for remote {}", remote_name))?;
let target_vec: Option<Vec<String>> = match target {
FetchTarget::Upstream => panic!("unreified FetchTarget"),
FetchTarget::Specific(targets) => Some(targets.iter().cloned().collect()),
FetchTarget::All => None,
};
let target = target_vec.as_deref();
depot
.fetch_repo(&remote, &project_name, target, fetch_tags, None)
.context(format!("failed to fetch for project {}", project_name,))?;
Ok(())
});
}
let result = pool.execute(job);
if !result.failed.is_empty() {
for failure in result.failed {
eprintln!("{}: {:?}", failure.name, failure.result);
}
bail!("failed to sync");
}
}
if checkout == CheckoutType::Checkout || checkout == CheckoutType::RefsOnly {
let mut job = Job::with_name("checkout");
let tree_root = Arc::new(self.path.clone());
let lfs_projects = Arc::new(dashmap::DashMap::<String, PathBuf>::with_capacity(10));
for project in &projects {
let config = Arc::clone(&config);
let project_info = Arc::clone(&project);
let project_path = self.path.join(&project.project_path);
let tree_root = Arc::clone(&tree_root);
let lfs_projects = Arc::clone(&lfs_projects);
job.add_task(project.project_path.clone(), move |_| {
let remote = config
.find_remote(&project_info.remote)
.context(format!("failed to find remote {}", project_info.remote))?;
let depot = config
.find_depot(&remote.depot)
.context(format!("failed to find depot for remote {}", project_info.remote))?;
let project_name = &project_info.project_name;
let revision = &project_info.revision;
if project_path.exists() {
depot
.update_remote_refs(&remote, &project_info.project_name, &project_path)
.context("failed to update remote refs")?;
}
if checkout == CheckoutType::Checkout {
if project_path.exists() {
let repo = git2::Repository::open(&project_path).context("failed to open repository".to_string())?;
// There's two things to be concerned about here:
// - HEAD might be attached to a branch
// - the repo might have uncommitted changes in the index or worktree
//
// If HEAD is attached to a branch, we choose to do nothing (for now), unless explicitly told to detach.
// At some point, we should probably try to perform the equivalent of `git pull --rebase`.
//
// If the repo has uncommitted changes, do a dry-run first, and give up if we have any conflicts.
let head_detached = repo.head_detached().context("failed to check if HEAD is detached")?;
let current_head = repo.head();
let current_head_oid = match current_head {
Ok(ref head) => Some(head.target().context("HEAD not a direct reference?")?),
Err(_) => None,
};
let new_head = util::parse_revision(&repo, &remote.name, &revision)
.context(format!(
"failed to find revision to sync to (wanted {}/{} in {:?})",
remote.name, revision, project_path
))?
.peel_to_commit()?;
if Some(new_head.id()) == current_head_oid {
// We're already at the top of tree.
} else {
if let Some(current_head_oid) = current_head_oid {
if detach {
repo
.set_head_detached(current_head_oid)
.context("failed to set HEAD detached")?;
} else {
// Check if the new head descends from the current one.
if !repo
.graph_descendant_of(new_head.id(), current_head_oid)
.context("graph descendent of failed")?
{
let (ahead, behind) = repo
.graph_ahead_behind(current_head_oid, new_head.id())
.context("graph ahead behind failed")?;
let head_name = if head_detached {
console::style("no branch".to_string()).red().to_string()
} else {
let head = current_head.unwrap();
let head_short = head.shorthand().context("branch name contains invalid UTF-8")?;
format!("branch {}", BRANCH_STYLE.apply_to(&head_short))
};
bail!("{} {}", head_name, util::ahead_behind(ahead, behind));
}
}
}
// Do a dry run first to look for dirty changes.
let probe = repo.checkout_tree(
new_head.as_object(),
Some(git2::build::CheckoutBuilder::new().dry_run()),
);
if let Err(err) = probe {
bail!(err);
}
repo
.checkout_tree(new_head.as_object(), None)
.context(format!("failed to checkout to {:?}", new_head))?;
repo
.reset(new_head.as_object(), git2::ResetType::Soft, None)
.context(format!("failed to move HEAD to {:?}", new_head))?;
}
} else {
depot.clone_repo(&remote, &project_name, &revision, &project_path)?;
}
if project_info.manifest_project {
// Some tools look at the upstream tracking branch of .repo/manifest to determine
// what manifest branch is being used.
let repo = git2::Repository::open(&project_path).context("failed to open repository".to_string())?;
let head = repo
.head()
.context("failed to get HEAD")?
.peel_to_commit()
.context("failed to peel HEAD to commit")?;
let mut branch = match repo.find_branch("default", git2::BranchType::Local) {
Ok(branch) => branch,
Err(_) => repo
.branch("default", &head, true)
.context("failed to create manifest default branch")?,
};
// TODO: repo uses origin as the upstream, regardless of what the remote is called.
branch
.set_upstream(Some(&format!("{}/{}", project_info.remote, project_info.revision)))
.context(format!(
"failed to set manifest branch upstream to {}/{}",
project_info.remote, project_info.revision
))?;
repo
.set_head("refs/heads/default")
.context("failed to set manifest HEAD")?;
}
// Set up symlinks to repo hooks.
let hooks_dir = project_path.join(".git").join("hooks");
let relpath = pathdiff::diff_paths(tree_root.as_ref(), &hooks_dir)
.ok_or_else(|| format_err!("failed to calculate path diff from hooks to tree root"))?
.join(".pore")
.join("hooks");
for filename in hooks::hooks().keys() {
let target = relpath.join(filename);
let symlink_path = hooks_dir.join(filename);
let _ = std::fs::remove_file(&symlink_path);
create_symlink(&target, &symlink_path)
.context(format!("failed to create symlink at {:?}", &symlink_path))?;
}
if !no_lfs && Path::exists(&project_path.join(".lfsconfig")) {
lfs_projects.insert(project_info.project_path.clone(), project_path);
}
}
Ok(())
});
}
let results = pool.execute(job);
for failure in &results.failed {
println!("{}", PROJECT_STYLE.apply_to(&failure.name));
println!("{}", console::style(format!(" {}", failure.result)).red());
}
// Perform linkfiles/copyfiles.
for project in &projects {
// src is the target of the link/the file that is copied, and is a relative path from the project.
// dst is the location of the link/copy that the rule creates, and is a relative path from the tree root.
for op in &project.file_ops {
let src_path = self.path.join(&project.project_path).join(&op.src());
let dst_path = self.path.join(&op.dst());
let base = dst_path
.parent()
.ok_or_else(|| format_err!("linkfile destination is the root?"))?;
if let Err(err) = std::fs::remove_file(&dst_path) {
if err.kind() != std::io::ErrorKind::NotFound {
bail!("failed to unlink file {:?}: {}", dst_path, err);
}
}
let _ = std::fs::create_dir_all(&base)
.map_err(|err| eprintln!("warning: failed to create directory {:?}: {}", &base, err));
match op {
FileOperation::LinkFile { .. } => {
// repo makes the symlinks as relative symlinks.
let target = pathdiff::diff_paths(&src_path, &base)
.ok_or_else(|| format_err!("failed to calculate path diff for {:?} -> {:?}", dst_path, src_path,))?;
let _ = create_symlink(target, &dst_path)
.map_err(|err| eprintln!("warning: failed to create symlink at {:?}: {}", dst_path, err));
}
FileOperation::CopyFile { .. } => {
let _ = std::fs::copy(&src_path, &dst_path).map_err(|err| {
eprintln!(
"warning: failed to copy file from {:?} to {:?}: {}",
src_path, dst_path, err
)
});
}
}
}
}
if do_project_cleanup {
let lost_found = self.path.join("lost+found");
std::fs::create_dir_all(&lost_found).context("failed to create lost+found directory")?;
let find_ignore = lost_found.join(".find-ignore");
std::fs::OpenOptions::new()
.write(true)
.create(true)
.open(find_ignore)
.context("failed to create lost+found/.find-ignore")?;
let previous: HashSet<String> = HashSet::from_iter(self.config.projects.iter().cloned());
self.config.projects = projects.iter().map(|p| p.project_path.clone()).collect();
let current: HashSet<String> = HashSet::from_iter(self.config.projects.iter().cloned());
// Since we're using rename to move projects, we need to handle parents before children
// (which will then fail because they've already been moved).
let mut diff: Vec<_> = previous.difference(¤t).collect();
diff.sort();
for ref project in diff {
let src_path = self.path.join(project);
let date = Utc::now().format("%Y%m%d-%H%M%S").to_string();
let dst_path = self.path.join("lost+found").join(&date).join(project);
println!("Moving deleted project {} to {:?}", project, dst_path);
let result = std::fs::create_dir_all(&dst_path)
.context("failed to create lost+found directory")
.and_then(|_| {
std::fs::rename(&src_path, &dst_path)
.context(format!("failed to move project from {:?} to {:?}", src_path, dst_path))
});
if let Err(e) = result {
eprintln!("warning: {}", e);
}
}
self.write_config().context("failed to write tree config")?;
}
if !lfs_projects.is_empty() {
let mut job = Job::with_name("lfs pull");
for project in lfs_projects.iter() {
let project_path = project.value().clone();
job.add_task(project.key(), move |_| -> Result<(), Error> {
macro_rules! run_git {
($args:expr, $msg:expr) => {
std::process::Command::new("git")
.args($args)
.current_dir(&project_path)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.expect($msg);
};
}
run_git!(["lfs", "install", "--local"], "Failed to install Git LFS");
run_git!(["lfs", "pull"], "Failed to pull Git LFS assets");
Ok(())
});
}
let results = pool.execute(job);
for failure in &results.failed {
println!("{}", PROJECT_STYLE.apply_to(&failure.name));
println!("{}", console::style(format!(" {}", failure.result)).red());
}
}
}
Ok(0)
}
fn write_hook(&self, directory: &Path, filename: &str, contents: &str) -> Result<(), Error> {
let path = self.path.join(directory);
std::fs::create_dir_all(&path).context(format!("failed to create directory: {:?}", path))?;
let file_path = path.join(filename);
let mut file = std::fs::File::create(&file_path).context(format!("failed to open file at {:?}", file_path))?;
file
.write_all(contents.as_bytes())
.context(format!("failed to write hook at {:?}", file_path))?;
// Currently no std APIs for dealing with file permissions on Windows.
// Not running this on Windows probably isn't an issue since everything
// should be executable unless the code was checked out to a directory
// that prohibits it.
#[cfg(unix)]
{
let mut permissions = file.metadata()?.permissions();
permissions.set_mode(0o700);
file.set_permissions(permissions)?;
}
Ok(())
}
pub fn update_hooks(&self) -> Result<(), Error> {
// Just always do this, since it's cheap.
let hooks_dir = PathBuf::new().join(".pore").join("hooks");
for (filename, contents) in hooks::hooks() {
self.write_hook(hooks_dir.as_path(), filename, contents)?;
}
Ok(())
}
pub fn ensure_repo_compat(&self) -> Result<(), Error> {
std::fs::create_dir_all(self.path.join(".repo")).context("failed to create dummy .repo dir")?;
// Create symlinks for manifests and manifest.xml.
create_symlink("../.pore/manifest", self.path.join(".repo").join("manifests"))?;
create_symlink("../.pore/manifest.xml", self.path.join(".repo").join("manifest.xml"))?;
// Write a script that forwards repo to pore.
let repo_bin_dir = PathBuf::new().join(".repo").join("repo");
self.write_hook(
repo_bin_dir.as_path(),
"repo",
"#!/bin/bash\nexec -a repo pore \"${@}\"\n",
)?;
// Also write a main.py to the directory so that a bare `repo` can use it.