diff --git a/client/github/github_labels.go b/client/github/github_labels.go new file mode 100644 index 0000000..7c449e4 --- /dev/null +++ b/client/github/github_labels.go @@ -0,0 +1,22 @@ +package github + +import ( + "context" + "github.com/google/go-github/v67/github" + "propromo/utils" +) + +func ListGitHubLabels(repo utils.GitRepo) ([]*github.Label, error) { + ctx := context.Background() + + labels, _, err := client.Issues.ListLabels(ctx, repo.Owner, repo.Repository, nil) + return labels, err +} + +func CreateGitHubLabel(token string, repo utils.GitRepo, label *github.Label) (*github.Label, error) { + ctx := context.Background() + client := github.NewClient(nil).WithAuthToken(token) + + label, _, err := client.Issues.CreateLabel(ctx, repo.Owner, repo.Repository, label) + return label, err +} diff --git a/cmd/github/sync.go b/cmd/github/sync.go index b03c61c..64937ef 100644 --- a/cmd/github/sync.go +++ b/cmd/github/sync.go @@ -16,6 +16,7 @@ var targets []string func init() { syncCmd.AddCommand(milestonesCmd) + syncCmd.AddCommand(labelsCmd) } func getToken() string { diff --git a/cmd/github/sync_labels.go b/cmd/github/sync_labels.go new file mode 100644 index 0000000..cfe1599 --- /dev/null +++ b/cmd/github/sync_labels.go @@ -0,0 +1,54 @@ +package cmd + +import ( + "errors" + "fmt" + githubmodel "github.com/google/go-github/v67/github" + "github.com/spf13/cobra" + "propromo/client/github" + "propromo/cmdutils" + "propromo/utils" +) + +var labelsCmd = &cobra.Command{ + Use: "labels", + Short: "Sync labels from one repo to others", + Run: func(command *cobra.Command, args []string) { + fmt.Println("Syncing from", source, "to", targets) + + sourceRepo, err := utils.ParseGitRepo(source) + cobra.CheckErr(err) + + labels, err := github.ListGitHubLabels(sourceRepo) + cobra.CheckErr(err) + + repos := make([]utils.GitRepo, len(targets)) + for i, target := range targets { + repo, err := utils.ParseGitRepo(target) + cobra.CheckErr(err) + repos[i] = repo + } + + token := getToken() + for _, repo := range repos { + for _, label := range labels { + _, err := github.CreateGitHubLabel(token, repo, &githubmodel.Label{ + Name: label.Name, + Description: label.Description, + Color: label.Color, + }) + + var ghErr *githubmodel.ErrorResponse + if errors.As(err, &ghErr) && len(ghErr.Errors) == 1 && ghErr.Errors[0].Code == "already_exists" { + cmdutils.Logger.Info("Label already exists!", "repo", repo.String(), "label", *label.Name) + continue + } + cmdutils.Logger.Info("Label successfully created", "repo", repo.String(), "label", *label.Name) + } + } + }, +} + +func init() { + syncFlags(labelsCmd) +}