Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
257 changes: 257 additions & 0 deletions internal/plan.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,257 @@
package internal

import (
"context"
"fmt"
"sort"
"strings"
)

// maxListed caps the names listed per change in a message, so it stays one readable line.
const maxListed = 10

// State is what the plugin read from the repository: only what the enabled remediations need.
type State struct {
Repo *repository
Collaborators []user // with Remediations.DirectCollaborators
Invitations []invitation // with Remediations.DirectCollaborators.Invitations
}

// Plan is the changes the enabled remediations need, kept in refs as last_plan.
type Plan struct {
Mode string `json:"mode"`
Repository string `json:"repository"`
// RemoveCollaborators are the direct collaborators to remove, sorted case-insensitively.
RemoveCollaborators []string `json:"remove_collaborators,omitempty"`
// CancelInvitations are the pending invitations to delete.
CancelInvitations []PlannedInvitation `json:"cancel_invitations,omitempty"`
// WebCommitSignoff is the value to set, when it differs.
WebCommitSignoff string `json:"web_commit_signoff,omitempty"`
// Kept are the direct collaborators left in place because Keep lists them (or they own
// the repository).
Kept []string `json:"kept,omitempty"`
}

// PlannedInvitation is an invitation to cancel.
type PlannedInvitation struct {
ID int64 `json:"id"`
Login string `json:"login"` // the invitee, or the email, or "#<id>"
}

// Empty reports whether nothing needs to change.
func (p *Plan) Empty() bool {
return len(p.RemoveCollaborators) == 0 && len(p.CancelInvitations) == 0 && p.WebCommitSignoff == ""
}

// read reads the state the enabled remediations need. The repository is always read: it
// checks access first, and gives its owner and settings page.
func read(ctx context.Context, c *githubClient, r Repo, p *Params) (*State, error) {
repo, err := c.getRepository(ctx, r)
if err != nil {
return nil, err
}
st := &State{Repo: repo}
dc := p.Remediations.DirectCollaborators
if dc.Enabled {
if st.Collaborators, err = c.listDirectCollaborators(ctx, r); err != nil {
return nil, err
}
if dc.Invitations {
if st.Invitations, err = c.listInvitations(ctx, r); err != nil {
return nil, err
}
}
}
return st, nil
}

// ComputePlan returns the changes that make st match the parameters. The repository's
// owner is never removed (GitHub refuses it, so it would fail every run).
func ComputePlan(r Repo, p *Params, keep *KeepList, st *State) *Plan {
plan := &Plan{Mode: p.Mode, Repository: r.FullName()}
if st.Repo != nil && st.Repo.FullName != "" {
plan.Repository = st.Repo.FullName
}
owner := ""
if st.Repo != nil {
owner = strings.ToLower(st.Repo.Owner.Login)
}
dc := p.Remediations.DirectCollaborators
if dc.Enabled {
for _, u := range st.Collaborators {
if keep.Has(u.Login) || strings.ToLower(u.Login) == owner {
plan.Kept = append(plan.Kept, u.Login)
continue
}
plan.RemoveCollaborators = append(plan.RemoveCollaborators, u.Login)
}
sortFold(plan.RemoveCollaborators)
sortFold(plan.Kept)
if dc.Invitations {
for _, inv := range st.Invitations {
if login := inv.login(); login != "" && keep.Has(login) {
continue
}
plan.CancelInvitations = append(plan.CancelInvitations, PlannedInvitation{ID: inv.ID, Login: invitationLabel(inv)})
}
sort.SliceStable(plan.CancelInvitations, func(i, j int) bool {
a, b := strings.ToLower(plan.CancelInvitations[i].Login), strings.ToLower(plan.CancelInvitations[j].Login)
if a != b {
return a < b
}
return plan.CancelInvitations[i].ID < plan.CancelInvitations[j].ID
})
}
}
if ws := p.Remediations.WebCommitSignoff; ws.Enabled && st.Repo != nil {
want := ws.Value == SignoffRequired
if st.Repo.WebCommitSignoffRequired != want {
plan.WebCommitSignoff = ws.Value
}
}
return plan
}

func invitationLabel(inv invitation) string {
switch {
case inv.login() != "":
return inv.login()
case inv.Email != "":
return inv.Email
}
return fmt.Sprintf("#%d", inv.ID)
}

func sortFold(s []string) {
sort.SliceStable(s, func(i, j int) bool { return strings.ToLower(s[i]) < strings.ToLower(s[j]) })
}

// Done is what an apply changed, in the order it ran.
type Done struct {
RemovedCollaborators []string
CancelledInvitations []string
WebCommitSignoff string
}

func (d *Done) empty() bool {
return len(d.RemovedCollaborators) == 0 && len(d.CancelledInvitations) == 0 && d.WebCommitSignoff == ""
}

// execute makes the plan's changes: collaborators, then invitations, then signoff. It stops
// at the first error; what was done before it stays done and is returned.
func execute(ctx context.Context, c *githubClient, r Repo, plan *Plan) (*Done, error) {
done := &Done{}
for _, login := range plan.RemoveCollaborators {
if !loginRE.MatchString(login) {
return done, fmt.Errorf("refusing to remove %q: not a GitHub login", login)
}
if err := c.removeCollaborator(ctx, r, login); err != nil {
return done, err
}
done.RemovedCollaborators = append(done.RemovedCollaborators, login)
}
for _, inv := range plan.CancelInvitations {
if err := c.deleteInvitation(ctx, r, inv.ID); err != nil {
return done, err
}
done.CancelledInvitations = append(done.CancelledInvitations, inv.Login)
}
if plan.WebCommitSignoff != "" {
want := plan.WebCommitSignoff == SignoffRequired
repo, err := c.setWebCommitSignoff(ctx, r, want)
if err != nil {
return done, err
}
if repo.WebCommitSignoffRequired != want {
return done, fmt.Errorf("PATCH %s: GitHub kept web commit signoff %s (an organization policy may enforce it)",
repoPath(r), signoffWord(repo.WebCommitSignoffRequired))
}
done.WebCommitSignoff = plan.WebCommitSignoff
}
return done, nil
}

func signoffWord(required bool) string {
if required {
return SignoffRequired
}
return SignoffNotRequired
}

// Messages.

const msgCompliant = "compliant: nothing to change"

// dryRunMessage is "dry-run: would remove 3 direct collaborators (alice, bob, carol), cancel
// 1 invitation (dave), set web commit signoff to required".
func dryRunMessage(plan *Plan) string {
if plan.Empty() {
return msgCompliant
}
var parts []string
if n := len(plan.RemoveCollaborators); n > 0 {
parts = append(parts, fmt.Sprintf("remove %s (%s)", count(n, "direct collaborator"), names(plan.RemoveCollaborators)))
}
if n := len(plan.CancelInvitations); n > 0 {
parts = append(parts, fmt.Sprintf("cancel %s (%s)", count(n, "invitation"), names(invitationLogins(plan.CancelInvitations))))
}
if plan.WebCommitSignoff != "" {
parts = append(parts, "set web commit signoff to "+plan.WebCommitSignoff)
}
return "dry-run: would " + strings.Join(parts, ", ")
}

// doneText is "removed 2 direct collaborators (alice, bob), cancelled 1 invitation (dave),
// set web commit signoff to required".
func doneText(d *Done) string {
var parts []string
if n := len(d.RemovedCollaborators); n > 0 {
parts = append(parts, fmt.Sprintf("removed %s (%s)", count(n, "direct collaborator"), names(d.RemovedCollaborators)))
}
if n := len(d.CancelledInvitations); n > 0 {
parts = append(parts, fmt.Sprintf("cancelled %s (%s)", count(n, "invitation"), names(d.CancelledInvitations)))
}
if d.WebCommitSignoff != "" {
parts = append(parts, "set web commit signoff to "+d.WebCommitSignoff)
}
return strings.Join(parts, ", ")
}

// appliedMessage is "applied: <done>", or compliant when nothing needed changing.
func appliedMessage(d *Done) string {
if d.empty() {
return msgCompliant
}
return "applied: " + doneText(d)
}

// failedMessage is the error, then what was changed before it.
func failedMessage(err error, d *Done) string {
msg := err.Error()
if d != nil && !d.empty() {
msg += "; changed before the error: " + doneText(d)
}
return msg
}

func invitationLogins(invs []PlannedInvitation) []string {
out := make([]string, len(invs))
for i, inv := range invs {
out[i] = inv.Login
}
return out
}

func count(n int, noun string) string {
if n == 1 {
return "1 " + noun
}
return fmt.Sprintf("%d %ss", n, noun)
}

func names(list []string) string {
if len(list) <= maxListed {
return strings.Join(list, ", ")
}
return strings.Join(list[:maxListed], ", ") + fmt.Sprintf(" and %d more", len(list)-maxListed)
}
Loading
Loading