From 3be729302724d1749785d42cf1f0500cd2ae51f6 Mon Sep 17 00:00:00 2001 From: Marek Czernek Date: Sun, 2 Aug 2020 15:55:29 +0200 Subject: [PATCH] enhancement: Improve error handling --- Makefile | 4 ++++ main/main.go | 27 ++++++++++++++++++--------- 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/Makefile b/Makefile index d80fdff..6a5d1f4 100644 --- a/Makefile +++ b/Makefile @@ -19,5 +19,9 @@ build-all: GOOS=linux GOARCH=$(GOARCH) $(GOBUILD) -o bin/$(BINARY_NAME)_linux -v $(GOPKG) GOOS=darwin GOARCH=$(GOARCH) $(GOBUILD) -o bin/$(BINARY_NAME)_darwin -v $(GOPKG) +.PHONY: clean +clean: + -rm bin/* + .PHONY: all all: build diff --git a/main/main.go b/main/main.go index d4db485..3e945c9 100644 --- a/main/main.go +++ b/main/main.go @@ -18,35 +18,34 @@ var removed int = 0 func main() { parseCmdFlags() cfg, err := GetConfig(configPath) - if err != nil { - fmt.Printf("Could not parse configuration yaml: %v\n", err) - os.Exit(1) - } + handleError(err, "[ERR] Could not parse configuration yaml\n", true) client := getGithubClient(cfg) var wg sync.WaitGroup - issues, _, _ := client.Issues.ListByRepo(context.Background(), cfg.Repo.Owner, cfg.Repo.Name, nil) + issues, _, err := client.Issues.ListByRepo(context.Background(), cfg.Repo.Owner, cfg.Repo.Name, nil) + handleError(err, "[ERR] Could not connect to GitHub API, check API token?\n", true) + wg.Add(len(issues)) for _, issue := range issues { go deleteIssueReactions(&wg, client, cfg, *issue.Number) } wg.Wait() - fmt.Printf("Successfully removed %d issue reactions from repo %v\n", removed, cfg.Repo) + fmt.Printf("Removed %d issue reactions from repo %v\n", removed, cfg.Repo) } func deleteIssueReactions(wg *sync.WaitGroup, client *github.Client, cfg *Config, issueNumber int) { defer wg.Done() ctx := context.Background() - reactions, _, _ := client.Reactions.ListIssueReactions(ctx, cfg.Repo.Owner, cfg.Repo.Name, issueNumber, nil) + reactions, _, err := client.Reactions.ListIssueReactions(ctx, cfg.Repo.Owner, cfg.Repo.Name, issueNumber, nil) + handleError(err, fmt.Sprintf("[WARN] Could not list reactions for issue %d", issueNumber), false) for _, reaction := range reactions { if *reaction.User.Login == cfg.Auth.Login { _, err := client.Reactions.DeleteIssueReaction(ctx, cfg.Repo.Owner, cfg.Repo.Name, issueNumber, *reaction.ID) if err != nil { - fmt.Println("[ERR] Could not delete reaction ", reaction) - fmt.Println(err) + fmt.Fprintf(os.Stderr, "[WARN] Could not delete reaction %v\nerror:\n%v", reaction, err) } else { removed++ } @@ -72,3 +71,13 @@ func getGithubClient(cfg *Config) *github.Client { tc := oauth2.NewClient(ctx, ts) return github.NewClient(tc) } + +func handleError(err error, msg string, fatal bool) { + if err != nil { + fmt.Fprintf(os.Stderr, msg) + fmt.Fprintf(os.Stderr, "%v\n", err) + if fatal { + os.Exit(1) + } + } +}