-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathmod.rs
1282 lines (1168 loc) · 43.1 KB
/
mod.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
mod api;
#[cfg(test)]
mod tests;
use self::api::{BranchProtectionOp, TeamPrivacy, TeamRole};
use crate::github::api::{GithubRead, Login, PushAllowanceActor, RepoPermission, RepoSettings};
use log::debug;
use rust_team_data::v1::{Bot, BranchProtectionMode};
use std::collections::{HashMap, HashSet};
use std::fmt::{Display, Formatter, Write};
pub(crate) use self::api::{GitHubApiRead, GitHubWrite, HttpClient};
static DEFAULT_DESCRIPTION: &str = "Managed by the rust-lang/team repository.";
static DEFAULT_PRIVACY: TeamPrivacy = TeamPrivacy::Closed;
pub(crate) fn create_diff(
github: Box<dyn GithubRead>,
teams: Vec<rust_team_data::v1::Team>,
repos: Vec<rust_team_data::v1::Repo>,
) -> anyhow::Result<Diff> {
let github = SyncGitHub::new(github, teams, repos)?;
github.diff_all()
}
type OrgName = String;
type RepoName = String;
#[derive(Copy, Clone, Debug, PartialEq)]
enum GithubApp {
RenovateBot,
}
impl GithubApp {
fn from_id(app_id: u64) -> Option<Self> {
match app_id {
2740 => Some(GithubApp::RenovateBot),
_ => None,
}
}
}
impl Display for GithubApp {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
GithubApp::RenovateBot => f.write_str("RenovateBot"),
}
}
}
#[derive(Clone, Debug)]
struct OrgAppInstallation {
app: GithubApp,
installation_id: u64,
repositories: HashSet<RepoName>,
}
#[derive(Clone, Debug, PartialEq)]
struct AppInstallation {
app: GithubApp,
installation_id: u64,
}
struct SyncGitHub {
github: Box<dyn GithubRead>,
teams: Vec<rust_team_data::v1::Team>,
repos: Vec<rust_team_data::v1::Repo>,
usernames_cache: HashMap<u64, String>,
org_owners: HashMap<OrgName, HashSet<u64>>,
org_apps: HashMap<OrgName, Vec<OrgAppInstallation>>,
}
impl SyncGitHub {
pub(crate) fn new(
github: Box<dyn GithubRead>,
teams: Vec<rust_team_data::v1::Team>,
repos: Vec<rust_team_data::v1::Repo>,
) -> anyhow::Result<Self> {
debug!("caching mapping between user ids and usernames");
let users = teams
.iter()
.filter_map(|t| t.github.as_ref().map(|gh| &gh.teams))
.flatten()
.flat_map(|team| &team.members)
.copied()
.collect::<HashSet<_>>()
.into_iter()
.collect::<Vec<_>>();
let usernames_cache = github.usernames(&users)?;
debug!("caching organization owners");
let orgs = teams
.iter()
.filter_map(|t| t.github.as_ref())
.flat_map(|gh| &gh.teams)
.map(|gh_team| &gh_team.org)
.collect::<HashSet<_>>();
let mut org_owners = HashMap::new();
let mut org_apps = HashMap::new();
for org in &orgs {
org_owners.insert((*org).to_string(), github.org_owners(org)?);
let mut installations: Vec<OrgAppInstallation> = vec![];
for installation in github.org_app_installations(org)? {
if let Some(app) = GithubApp::from_id(installation.app_id) {
let mut repositories = HashSet::new();
for repo_installation in
github.app_installation_repos(installation.installation_id)?
{
repositories.insert(repo_installation.name);
}
installations.push(OrgAppInstallation {
app,
installation_id: installation.installation_id,
repositories,
});
}
}
org_apps.insert(org.to_string(), installations);
}
Ok(SyncGitHub {
github,
teams,
repos,
usernames_cache,
org_owners,
org_apps,
})
}
pub(crate) fn diff_all(&self) -> anyhow::Result<Diff> {
let team_diffs = self.diff_teams()?;
let repo_diffs = self.diff_repos()?;
Ok(Diff {
team_diffs,
repo_diffs,
})
}
fn diff_teams(&self) -> anyhow::Result<Vec<TeamDiff>> {
let mut diffs = Vec::new();
let mut unseen_github_teams = HashMap::new();
for team in &self.teams {
if let Some(gh) = &team.github {
for github_team in &gh.teams {
// Get existing teams we haven't seen yet
let unseen_github_teams = match unseen_github_teams.get_mut(&github_team.org) {
Some(ts) => ts,
None => {
let ts: HashMap<_, _> = self
.github
.org_teams(&github_team.org)?
.into_iter()
.collect();
unseen_github_teams
.entry(github_team.org.clone())
.or_insert(ts)
}
};
// Remove the current team from the collection of unseen GitHub teams
unseen_github_teams.remove(&github_team.name);
diffs.push(self.diff_team(github_team)?);
}
}
}
let delete_diffs = unseen_github_teams
.into_iter()
.filter(|(org, _)| matches!(org.as_str(), "rust-lang" | "rust-lang-nursery")) // Only delete unmanaged teams in `rust-lang` and `rust-lang-nursery` for now
.flat_map(|(org, remaining_github_teams)| {
remaining_github_teams
.into_iter()
.map(move |t| (org.clone(), t))
})
// Don't delete the special bot teams
.filter(|(_, (remaining_github_team, _))| {
!BOTS_TEAMS.contains(&remaining_github_team.as_str())
})
.map(|(org, (name, slug))| TeamDiff::Delete(DeleteTeamDiff { org, name, slug }));
diffs.extend(delete_diffs);
Ok(diffs)
}
fn diff_team(&self, github_team: &rust_team_data::v1::GitHubTeam) -> anyhow::Result<TeamDiff> {
// Ensure the team exists and is consistent
let team = match self.github.team(&github_team.org, &github_team.name)? {
Some(team) => team,
None => {
let members = github_team
.members
.iter()
.map(|member| {
let expected_role = self.expected_role(&github_team.org, *member);
(self.usernames_cache[member].clone(), expected_role)
})
.collect();
return Ok(TeamDiff::Create(CreateTeamDiff {
org: github_team.org.clone(),
name: github_team.name.clone(),
description: DEFAULT_DESCRIPTION.to_owned(),
privacy: DEFAULT_PRIVACY,
members,
}));
}
};
let mut name_diff = None;
if team.name != github_team.name {
name_diff = Some(github_team.name.clone())
}
let mut description_diff = None;
match &team.description {
Some(description) => {
if description != DEFAULT_DESCRIPTION {
description_diff = Some((description.clone(), DEFAULT_DESCRIPTION.to_owned()));
}
}
None => {
description_diff = Some((String::new(), DEFAULT_DESCRIPTION.to_owned()));
}
}
let mut privacy_diff = None;
if team.privacy != DEFAULT_PRIVACY {
privacy_diff = Some((team.privacy, DEFAULT_PRIVACY))
}
let mut member_diffs = Vec::new();
let mut current_members = self.github.team_memberships(&team)?;
let invites = self
.github
.team_membership_invitations(&github_team.org, &github_team.name)?;
// Ensure all expected members are in the team
for member in &github_team.members {
let expected_role = self.expected_role(&github_team.org, *member);
let username = &self.usernames_cache[member];
if let Some(member) = current_members.remove(member) {
if member.role != expected_role {
member_diffs.push((
username.clone(),
MemberDiff::ChangeRole((member.role, expected_role)),
));
} else {
member_diffs.push((username.clone(), MemberDiff::Noop));
}
} else {
// Check if the user has been invited already
if invites.contains(username) {
member_diffs.push((username.clone(), MemberDiff::Noop));
} else {
member_diffs.push((username.clone(), MemberDiff::Create(expected_role)));
}
}
}
// The previous cycle removed expected members from current_members, so it only contains
// members to delete now.
for member in current_members.values() {
member_diffs.push((member.username.clone(), MemberDiff::Delete));
}
Ok(TeamDiff::Edit(EditTeamDiff {
org: github_team.org.clone(),
name: team.name,
name_diff,
description_diff,
privacy_diff,
member_diffs,
}))
}
fn diff_repos(&self) -> anyhow::Result<Vec<RepoDiff>> {
let mut diffs = Vec::new();
for repo in &self.repos {
diffs.push(self.diff_repo(repo)?);
}
Ok(diffs)
}
fn diff_repo(&self, expected_repo: &rust_team_data::v1::Repo) -> anyhow::Result<RepoDiff> {
let actual_repo = match self.github.repo(&expected_repo.org, &expected_repo.name)? {
Some(r) => r,
None => {
let permissions = calculate_permission_diffs(
expected_repo,
Default::default(),
Default::default(),
)?;
let mut branch_protections = Vec::new();
for branch_protection in &expected_repo.branch_protections {
branch_protections.push((
branch_protection.pattern.clone(),
construct_branch_protection(expected_repo, branch_protection),
));
}
return Ok(RepoDiff::Create(CreateRepoDiff {
org: expected_repo.org.clone(),
name: expected_repo.name.clone(),
settings: RepoSettings {
description: Some(expected_repo.description.clone()),
homepage: expected_repo.homepage.clone(),
archived: false,
auto_merge_enabled: expected_repo.auto_merge_enabled,
},
permissions,
branch_protections,
app_installations: self.diff_app_installations(expected_repo, &[])?,
}));
}
};
let permission_diffs = self.diff_permissions(expected_repo)?;
let branch_protection_diffs = self.diff_branch_protections(&actual_repo, expected_repo)?;
let old_settings = RepoSettings {
description: actual_repo.description.clone(),
homepage: actual_repo.homepage.clone(),
archived: actual_repo.archived,
auto_merge_enabled: actual_repo.allow_auto_merge.unwrap_or(false),
};
let new_settings = RepoSettings {
description: Some(expected_repo.description.clone()),
homepage: expected_repo.homepage.clone(),
archived: expected_repo.archived,
auto_merge_enabled: expected_repo.auto_merge_enabled,
};
let existing_installations = self
.org_apps
.get(&expected_repo.org)
.map(|installations| {
installations
.iter()
.filter_map(|installation| {
// Only load installations from apps that we know about, to avoid removing
// unknown installations.
if installation.repositories.contains(&actual_repo.name) {
Some(AppInstallation {
app: installation.app,
installation_id: installation.installation_id,
})
} else {
None
}
})
.collect::<Vec<_>>()
})
.unwrap_or_default();
let app_installation_diffs =
self.diff_app_installations(expected_repo, &existing_installations)?;
Ok(RepoDiff::Update(UpdateRepoDiff {
org: expected_repo.org.clone(),
name: actual_repo.name,
repo_node_id: actual_repo.node_id,
repo_id: actual_repo.repo_id,
settings_diff: (old_settings, new_settings),
permission_diffs,
branch_protection_diffs,
app_installation_diffs,
}))
}
fn diff_permissions(
&self,
expected_repo: &rust_team_data::v1::Repo,
) -> anyhow::Result<Vec<RepoPermissionAssignmentDiff>> {
let actual_teams: HashMap<_, _> = self
.github
.repo_teams(&expected_repo.org, &expected_repo.name)?
.into_iter()
.map(|t| (t.name.clone(), t))
.collect();
let actual_collaborators: HashMap<_, _> = self
.github
.repo_collaborators(&expected_repo.org, &expected_repo.name)?
.into_iter()
.map(|u| (u.name.clone(), u))
.collect();
calculate_permission_diffs(expected_repo, actual_teams, actual_collaborators)
}
fn diff_branch_protections(
&self,
actual_repo: &api::Repo,
expected_repo: &rust_team_data::v1::Repo,
) -> anyhow::Result<Vec<BranchProtectionDiff>> {
let mut branch_protection_diffs = Vec::new();
let mut actual_protections = self
.github
.branch_protections(&actual_repo.org, &actual_repo.name)?;
for branch_protection in &expected_repo.branch_protections {
let actual_branch_protection = actual_protections.remove(&branch_protection.pattern);
let expected_branch_protection =
construct_branch_protection(expected_repo, branch_protection);
let operation = {
match actual_branch_protection {
Some((database_id, bp)) if bp != expected_branch_protection => {
BranchProtectionDiffOperation::Update(
database_id,
bp,
expected_branch_protection,
)
}
None => BranchProtectionDiffOperation::Create(expected_branch_protection),
// The branch protection doesn't need to change
Some(_) => continue,
}
};
branch_protection_diffs.push(BranchProtectionDiff {
pattern: branch_protection.pattern.clone(),
operation,
})
}
// `actual_branch_protections` now contains the branch protections that were not expected
// but are still on GitHub. We want to delete them.
branch_protection_diffs.extend(actual_protections.into_iter().map(|(name, (id, _))| {
BranchProtectionDiff {
pattern: name,
operation: BranchProtectionDiffOperation::Delete(id),
}
}));
Ok(branch_protection_diffs)
}
fn diff_app_installations(
&self,
expected_repo: &rust_team_data::v1::Repo,
existing_installations: &[AppInstallation],
) -> anyhow::Result<Vec<AppInstallationDiff>> {
let mut diff = vec![];
let mut found_apps = Vec::new();
// Find apps that should be enabled on the repository
for app in expected_repo.bots.iter().filter_map(|bot| match bot {
Bot::Renovate => Some(GithubApp::RenovateBot),
_ => None,
}) {
// Find installation ID of this app on GitHub
let gh_installation = self
.org_apps
.get(&expected_repo.org)
.and_then(|installations| {
installations
.iter()
.find(|installation| installation.app == app)
.map(|i| i.installation_id)
});
let Some(gh_installation) = gh_installation else {
log::warn!("Application {app} should be enabled for repository {}/{}, but it is not installed on GitHub", expected_repo.org, expected_repo.name);
continue;
};
let installation = AppInstallation {
app,
installation_id: gh_installation,
};
found_apps.push(installation.clone());
if !existing_installations.contains(&installation) {
diff.push(AppInstallationDiff::Add(installation));
}
}
for existing in existing_installations {
if !found_apps.contains(existing) {
diff.push(AppInstallationDiff::Remove(existing.clone()));
}
}
Ok(diff)
}
fn expected_role(&self, org: &str, user: u64) -> TeamRole {
if let Some(true) = self
.org_owners
.get(org)
.map(|owners| owners.contains(&user))
{
TeamRole::Maintainer
} else {
TeamRole::Member
}
}
}
fn calculate_permission_diffs(
expected_repo: &rust_team_data::v1::Repo,
mut actual_teams: HashMap<String, api::RepoTeam>,
mut actual_collaborators: HashMap<String, api::RepoUser>,
) -> anyhow::Result<Vec<RepoPermissionAssignmentDiff>> {
let mut permissions = Vec::new();
// Team permissions
for expected_team in &expected_repo.teams {
let permission = convert_permission(&expected_team.permission);
let actual_team = actual_teams.remove(&expected_team.name);
let collaborator = RepoCollaborator::Team(expected_team.name.clone());
let diff = match actual_team {
Some(t) if t.permission != permission => RepoPermissionAssignmentDiff {
collaborator,
diff: RepoPermissionDiff::Update(t.permission, permission),
},
// Team permission does not need to change
Some(_) => continue,
None => RepoPermissionAssignmentDiff {
collaborator,
diff: RepoPermissionDiff::Create(permission),
},
};
permissions.push(diff);
}
// Bot permissions
let bots = expected_repo.bots.iter().filter_map(|b| {
let bot_user_name = bot_user_name(b)?;
actual_teams.remove(bot_user_name);
Some((bot_user_name, RepoPermission::Write))
});
// Member permissions
let members = expected_repo
.members
.iter()
.map(|m| (m.name.as_str(), convert_permission(&m.permission)));
for (name, permission) in bots.chain(members) {
let actual_collaborator = actual_collaborators.remove(name);
let collaborator = RepoCollaborator::User(name.to_owned());
let diff = match actual_collaborator {
Some(t) if t.permission != permission => RepoPermissionAssignmentDiff {
collaborator,
diff: RepoPermissionDiff::Update(t.permission, permission),
},
// Collaborator permission does not need to change
Some(_) => continue,
None => RepoPermissionAssignmentDiff {
collaborator,
diff: RepoPermissionDiff::Create(permission),
},
};
permissions.push(diff);
}
// `actual_teams` now contains the teams that were not expected
// but are still on GitHub. We now remove them.
for (team, t) in actual_teams {
if t.name == "security" && expected_repo.org == "rust-lang" {
// Skip removing access permissions from security.
// If we're in this branch we know that the team repo doesn't mention this team at all,
// so this shouldn't remove intentionally granted non-read access. Security is granted
// read access to all repositories in the org by GitHub (via a "security manager"
// role), and we can't remove that access.
//
// (FIXME: If we find security with non-read access, *that* probably should get dropped
// to read access. But not worth doing in this commit, want to get us unblocked first).
continue;
}
permissions.push(RepoPermissionAssignmentDiff {
collaborator: RepoCollaborator::Team(team),
diff: RepoPermissionDiff::Delete(t.permission),
});
}
// `actual_collaborators` now contains the collaborators that were not expected
// but are still on GitHub. We now remove them.
for (collaborator, u) in actual_collaborators {
permissions.push(RepoPermissionAssignmentDiff {
collaborator: RepoCollaborator::User(collaborator),
diff: RepoPermissionDiff::Delete(u.permission),
});
}
Ok(permissions)
}
/// Returns `None` if the bot is not an actual bot user, but rather a GitHub app.
fn bot_user_name(bot: &Bot) -> Option<&str> {
match bot {
Bot::Bors => Some("bors"),
Bot::Highfive => Some("rust-highfive"),
Bot::RustTimer => Some("rust-timer"),
Bot::Rustbot => Some("rustbot"),
Bot::Rfcbot => Some("rfcbot"),
Bot::Renovate => None,
}
}
fn convert_permission(p: &rust_team_data::v1::RepoPermission) -> RepoPermission {
use rust_team_data::v1;
match *p {
v1::RepoPermission::Write => RepoPermission::Write,
v1::RepoPermission::Admin => RepoPermission::Admin,
v1::RepoPermission::Maintain => RepoPermission::Maintain,
v1::RepoPermission::Triage => RepoPermission::Triage,
}
}
fn construct_branch_protection(
expected_repo: &rust_team_data::v1::Repo,
branch_protection: &rust_team_data::v1::BranchProtection,
) -> api::BranchProtection {
let uses_bors = expected_repo.bots.contains(&Bot::Bors);
let required_approving_review_count: u8 = if uses_bors {
0
} else {
match branch_protection.mode {
BranchProtectionMode::PrRequired {
required_approvals, ..
} => required_approvals
.try_into()
.expect("Too large required approval count"),
BranchProtectionMode::PrNotRequired => 0,
}
};
let mut push_allowances: Vec<PushAllowanceActor> = branch_protection
.allowed_merge_teams
.iter()
.map(|team| {
api::PushAllowanceActor::Team(api::TeamPushAllowanceActor {
organization: Login {
login: expected_repo.org.clone(),
},
name: team.to_string(),
})
})
.collect();
if uses_bors {
push_allowances.push(PushAllowanceActor::User(api::UserPushAllowanceActor {
login: "bors".to_owned(),
}));
}
api::BranchProtection {
pattern: branch_protection.pattern.clone(),
is_admin_enforced: true,
dismisses_stale_reviews: branch_protection.dismiss_stale_review,
required_approving_review_count,
required_status_check_contexts: match &branch_protection.mode {
BranchProtectionMode::PrRequired { ci_checks, .. } => ci_checks.clone(),
BranchProtectionMode::PrNotRequired => {
vec![]
}
},
push_allowances,
requires_approving_reviews: matches!(
branch_protection.mode,
BranchProtectionMode::PrRequired { .. }
),
}
}
/// The special bot teams
const BOTS_TEAMS: &[&str] = &["bors", "highfive", "rfcbot", "bots"];
/// A diff between the team repo and the state on GitHub
pub(crate) struct Diff {
team_diffs: Vec<TeamDiff>,
repo_diffs: Vec<RepoDiff>,
}
impl Diff {
/// Apply the diff to GitHub
pub(crate) fn apply(self, sync: &GitHubWrite) -> anyhow::Result<()> {
for team_diff in self.team_diffs {
team_diff.apply(sync)?;
}
for repo_diff in self.repo_diffs {
repo_diff.apply(sync)?;
}
Ok(())
}
}
impl std::fmt::Display for Diff {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "💻 Team Diffs:")?;
for team_diff in &self.team_diffs {
write!(f, "{team_diff}")?;
}
writeln!(f, "💻 Repo Diffs:")?;
for repo_diff in &self.repo_diffs {
write!(f, "{repo_diff}")?;
}
Ok(())
}
}
enum RepoDiff {
Create(CreateRepoDiff),
Update(UpdateRepoDiff),
}
impl RepoDiff {
fn apply(&self, sync: &GitHubWrite) -> anyhow::Result<()> {
match self {
RepoDiff::Create(c) => c.apply(sync),
RepoDiff::Update(u) => u.apply(sync),
}
}
}
impl std::fmt::Display for RepoDiff {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Create(c) => write!(f, "{c}"),
Self::Update(u) => write!(f, "{u}"),
}
}
}
struct CreateRepoDiff {
org: String,
name: String,
settings: RepoSettings,
permissions: Vec<RepoPermissionAssignmentDiff>,
branch_protections: Vec<(String, api::BranchProtection)>,
app_installations: Vec<AppInstallationDiff>,
}
impl CreateRepoDiff {
fn apply(&self, sync: &GitHubWrite) -> anyhow::Result<()> {
let repo = sync.create_repo(&self.org, &self.name, &self.settings)?;
for permission in &self.permissions {
permission.apply(sync, &self.org, &self.name)?;
}
for (branch, protection) in &self.branch_protections {
BranchProtectionDiff {
pattern: branch.clone(),
operation: BranchProtectionDiffOperation::Create(protection.clone()),
}
.apply(sync, &self.org, &self.name, &repo.node_id)?;
}
for installation in &self.app_installations {
installation.apply(sync, repo.repo_id)?;
}
Ok(())
}
}
impl std::fmt::Display for CreateRepoDiff {
fn fmt(&self, mut f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let RepoSettings {
description,
homepage,
archived: _,
auto_merge_enabled,
} = &self.settings;
writeln!(f, "➕ Creating repo:")?;
writeln!(f, " Org: {}", self.org)?;
writeln!(f, " Name: {}", self.name)?;
writeln!(f, " Description: {:?}", description)?;
writeln!(f, " Homepage: {:?}", homepage)?;
writeln!(f, " Auto-merge: {}", auto_merge_enabled)?;
writeln!(f, " Permissions:")?;
for diff in &self.permissions {
write!(f, "{diff}")?;
}
writeln!(f, " Branch Protections:")?;
for (branch_name, branch_protection) in &self.branch_protections {
writeln!(&mut f, " {branch_name}")?;
log_branch_protection(branch_protection, None, &mut f)?;
}
writeln!(f, " App Installations:")?;
for diff in &self.app_installations {
write!(f, "{diff}")?;
}
Ok(())
}
}
struct UpdateRepoDiff {
org: String,
name: String,
repo_node_id: String,
repo_id: u64,
// old, new
settings_diff: (RepoSettings, RepoSettings),
permission_diffs: Vec<RepoPermissionAssignmentDiff>,
branch_protection_diffs: Vec<BranchProtectionDiff>,
app_installation_diffs: Vec<AppInstallationDiff>,
}
impl UpdateRepoDiff {
pub(crate) fn noop(&self) -> bool {
if !self.can_be_modified() {
return true;
}
self.settings_diff.0 == self.settings_diff.1
&& self.permission_diffs.is_empty()
&& self.branch_protection_diffs.is_empty()
&& self.app_installation_diffs.is_empty()
}
fn can_be_modified(&self) -> bool {
// Archived repositories cannot be modified
// If the repository should be archived, and we do not change its archival status,
// we should not change any other properties of the repo.
if self.settings_diff.1.archived && self.settings_diff.0.archived {
return false;
}
true
}
fn apply(&self, sync: &GitHubWrite) -> anyhow::Result<()> {
if !self.can_be_modified() {
return Ok(());
}
if self.settings_diff.0 != self.settings_diff.1 {
sync.edit_repo(&self.org, &self.name, &self.settings_diff.1)?;
}
for permission in &self.permission_diffs {
permission.apply(sync, &self.org, &self.name)?;
}
for branch_protection in &self.branch_protection_diffs {
branch_protection.apply(sync, &self.org, &self.name, &self.repo_node_id)?;
}
for app_installation in &self.app_installation_diffs {
app_installation.apply(sync, self.repo_id)?;
}
Ok(())
}
}
impl std::fmt::Display for UpdateRepoDiff {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.noop() {
return Ok(());
}
writeln!(f, "📝 Editing repo '{}/{}':", self.org, self.name)?;
let (settings_old, settings_new) = &self.settings_diff;
let RepoSettings {
description,
homepage,
archived,
auto_merge_enabled,
} = settings_old;
match (description, &settings_new.description) {
(None, Some(new)) => writeln!(f, " Set description: '{new}'")?,
(Some(old), None) => writeln!(f, " Remove description: '{old}'")?,
(Some(old), Some(new)) if old != new => {
writeln!(f, " New description: '{old}' => '{new}'")?
}
_ => {}
}
match (homepage, &settings_new.homepage) {
(None, Some(new)) => writeln!(f, " Set homepage: '{new}'")?,
(Some(old), None) => writeln!(f, " Remove homepage: '{old}'")?,
(Some(old), Some(new)) if old != new => {
writeln!(f, " New homepage: '{old}' => '{new}'")?
}
_ => {}
}
match (archived, &settings_new.archived) {
(false, true) => writeln!(f, " Archive")?,
(true, false) => writeln!(f, " Unarchive")?,
_ => {}
}
match (auto_merge_enabled, &settings_new.auto_merge_enabled) {
(false, true) => writeln!(f, " Enable auto-merge")?,
(true, false) => writeln!(f, " Disable auto-merge")?,
_ => {}
}
if !self.permission_diffs.is_empty() {
writeln!(f, " Permission Changes:")?;
}
for permission_diff in &self.permission_diffs {
write!(f, "{permission_diff}")?;
}
if !self.branch_protection_diffs.is_empty() {
writeln!(f, " Branch Protections:")?;
}
for branch_protection_diff in &self.branch_protection_diffs {
write!(f, "{branch_protection_diff}")?;
}
if !self.app_installation_diffs.is_empty() {
writeln!(f, " App installation changes:")?;
}
for diff in &self.app_installation_diffs {
write!(f, "{diff}")?;
}
Ok(())
}
}
struct RepoPermissionAssignmentDiff {
collaborator: RepoCollaborator,
diff: RepoPermissionDiff,
}
impl RepoPermissionAssignmentDiff {
fn apply(&self, sync: &GitHubWrite, org: &str, repo_name: &str) -> anyhow::Result<()> {
match &self.diff {
RepoPermissionDiff::Create(p) | RepoPermissionDiff::Update(_, p) => {
match &self.collaborator {
RepoCollaborator::Team(team_name) => {
sync.update_team_repo_permissions(org, repo_name, team_name, p)?
}
RepoCollaborator::User(user_name) => {
sync.update_user_repo_permissions(org, repo_name, user_name, p)?
}
}
}
RepoPermissionDiff::Delete(_) => match &self.collaborator {
RepoCollaborator::Team(team_name) => {
sync.remove_team_from_repo(org, repo_name, team_name)?
}
RepoCollaborator::User(user_name) => {
sync.remove_collaborator_from_repo(org, repo_name, user_name)?
}
},
}
Ok(())
}
}
impl std::fmt::Display for RepoPermissionAssignmentDiff {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let name = match &self.collaborator {
RepoCollaborator::Team(name) => format!("team '{name}'"),
RepoCollaborator::User(name) => format!("user '{name}'"),
};
match &self.diff {
RepoPermissionDiff::Create(p) => {
writeln!(f, " Giving {name} {p} permission")
}
RepoPermissionDiff::Update(old, new) => {
writeln!(f, " Changing {name}'s permission from {old} to {new}")
}
RepoPermissionDiff::Delete(p) => {
writeln!(f, " Removing {name}'s {p} permission ")
}
}
}
}
enum RepoPermissionDiff {
Create(RepoPermission),
Update(RepoPermission, RepoPermission),
Delete(RepoPermission),
}
#[derive(Clone)]
enum RepoCollaborator {
Team(String),
User(String),
}
struct BranchProtectionDiff {
pattern: String,
operation: BranchProtectionDiffOperation,
}
impl BranchProtectionDiff {
fn apply(
&self,
sync: &GitHubWrite,
org: &str,
repo_name: &str,
repo_id: &str,
) -> anyhow::Result<()> {
match &self.operation {
BranchProtectionDiffOperation::Create(bp) => {
sync.upsert_branch_protection(
BranchProtectionOp::CreateForRepo(repo_id.to_string()),
&self.pattern,
bp,
)?;
}
BranchProtectionDiffOperation::Update(id, _, bp) => {
sync.upsert_branch_protection(
BranchProtectionOp::UpdateBranchProtection(id.clone()),
&self.pattern,
bp,
)?;
}
BranchProtectionDiffOperation::Delete(id) => {
debug!(
"Deleting branch protection '{}' on '{}/{}' as \
the protection is not in the team repo",
self.pattern, org, repo_name
);
sync.delete_branch_protection(org, repo_name, id)?;
}
}
Ok(())