diff --git a/pkg/vcs/github.go b/pkg/vcs/github.go index b850e8a..8b36fbe 100644 --- a/pkg/vcs/github.go +++ b/pkg/vcs/github.go @@ -339,8 +339,18 @@ func (g *GitHubClient) SetScoreLabels(ctx context.Context, pr *PR, scores []Scor for _, sc := range scores { name := GitHubScoreLabel(sc.Name, sc.Value) add = append(add, name) - if _, err := g.r.do(ctx, "POST", base+"/labels", map[string]string{"name": name, "color": sc.Color}, nil); err != nil && statusOf(err) != http.StatusUnprocessableEntity { - return fmt.Errorf("create label %s: %w", name, err) + if _, err := g.r.do(ctx, "POST", base+"/labels", map[string]string{"name": name, "color": sc.Color}, nil); err != nil { + if statusOf(err) != http.StatusUnprocessableEntity { + return fmt.Errorf("create label %s: %w", name, err) + } + // It exists: give it the band colour (best effort). + var l struct { + Color string `json:"color"` + } + lp := base + "/labels/" + url.PathEscape(name) + if _, err := g.r.do(ctx, "GET", lp, nil, &l); err == nil && !sameColor(l.Color, sc.Color) { + _, _ = g.r.do(ctx, "PATCH", lp, map[string]string{"color": sc.Color}, nil) + } } } _, err := g.r.do(ctx, "POST", fmt.Sprintf("%s/issues/%d/labels", base, pr.Number), map[string][]string{"labels": add}, nil) diff --git a/pkg/vcs/gitlab.go b/pkg/vcs/gitlab.go index b5715f0..52c6c4b 100644 --- a/pkg/vcs/gitlab.go +++ b/pkg/vcs/gitlab.go @@ -314,12 +314,15 @@ func (g *GitLabClient) SetScoreLabels(ctx context.Context, pr *PR, scores []Scor for _, sc := range scores { name := GitLabScoreLabel(sc.Name, sc.Value) add = append(add, name) - // Create once with the band colour; an existing label is fine. + // Create it with the band colour; an existing one gets that colour + // too, so a label made earlier (by hand, another tool) isn't left + // in some other colour. _, err := g.r.do(ctx, "POST", fmt.Sprintf("/projects/%s/labels", proj(pr.Repo)), map[string]string{"name": name, "color": "#" + sc.Color}, nil) if err != nil { if s := statusOf(err); s != http.StatusConflict && s != http.StatusBadRequest { return fmt.Errorf("create label %s: %w", name, err) } + g.recolorLabel(ctx, pr.Repo, name, sc.Color) } } body := map[string]string{"add_labels": strings.Join(add, ",")} @@ -330,6 +333,21 @@ func (g *GitLabClient) SetScoreLabels(ctx context.Context, pr *PR, scores []Scor return err } +// recolorLabel gives an existing project label the colour (hex, no #). +// Best effort: a group label can't be changed from the project, and a +// failure leaves the label as it was. +func (g *GitLabClient) recolorLabel(ctx context.Context, repo, name, color string) { + path := fmt.Sprintf("/projects/%s/labels/%s", proj(repo), url.PathEscape(name)) + var l struct { + Color string `json:"color"` + IsProjectLabel *bool `json:"is_project_label"` + } + if _, err := g.r.do(ctx, "GET", path, nil, &l); err != nil || sameColor(l.Color, color) || (l.IsProjectLabel != nil && !*l.IsProjectLabel) { + return + } + _, _ = g.r.do(ctx, "PUT", path, map[string]string{"color": "#" + color}, nil) +} + func (g *GitLabClient) UpdatePR(ctx context.Context, pr *PR, title, description *string) error { body := map[string]string{} if title != nil { diff --git a/pkg/vcs/labels_test.go b/pkg/vcs/labels_test.go index 773d9a0..3debb73 100644 --- a/pkg/vcs/labels_test.go +++ b/pkg/vcs/labels_test.go @@ -17,11 +17,17 @@ func TestGitLabScoreLabels(t *testing.T) { var mu sync.Mutex var created []map[string]string var put map[string]string + var recolored []string srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { mu.Lock() defer mu.Unlock() body, _ := io.ReadAll(r.Body) switch { + case r.Method == "GET" && r.URL.EscapedPath() == "/api/v4/projects/g%2Fp/labels/Security%20Score::100": + _, _ = io.WriteString(w, `{"name":"Security Score::100","color":"#6699cc","is_project_label":true}`) // made earlier, not green + case r.Method == "PUT" && strings.Contains(r.URL.Path, "/labels/"): + recolored = append(recolored, r.URL.Path+" "+string(body)) + _, _ = io.WriteString(w, `{}`) case r.Method == "GET" && strings.HasSuffix(r.URL.Path, "/merge_requests/7"): _, _ = io.WriteString(w, `{"labels":["bug","Quality Score::60","Security Score::100","Maintainability Score::90"]}`) case r.Method == "POST" && strings.HasSuffix(r.URL.Path, "/labels"): @@ -55,17 +61,30 @@ func TestGitLabScoreLabels(t *testing.T) { if len(created) != 3 || created[2]["color"] != "#fb8c00" { t.Errorf("created = %v", created) } + if len(recolored) != 1 || !strings.Contains(recolored[0], "Security Score::100") || !strings.Contains(recolored[0], `"#2da44e"`) { + t.Errorf("an existing label in another colour gets the band colour: %v", recolored) + } } func TestGitHubScoreLabels(t *testing.T) { var mu sync.Mutex var deleted []string var added []string + var patched []string srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { mu.Lock() defer mu.Unlock() body, _ := io.ReadAll(r.Body) switch { + case r.Method == "GET" && strings.HasPrefix(r.URL.Path, "/repos/o/r/labels/"): + color := "2DA44E" // already green (case aside) + if strings.HasSuffix(r.URL.Path, "Maintainability Score: 70") { + color = "ededed" + } + _, _ = io.WriteString(w, `{"color":"`+color+`"}`) + case r.Method == "PATCH" && strings.HasPrefix(r.URL.Path, "/repos/o/r/labels/"): + patched = append(patched, r.URL.Path+" "+string(body)) + _, _ = io.WriteString(w, `{}`) case r.Method == "GET" && r.URL.Path == "/repos/o/r/issues/7/labels": _, _ = io.WriteString(w, `[{"name":"bug"},{"name":"Quality Score: 60"},{"name":"Security Score: 100"}]`) case r.Method == "DELETE": @@ -93,6 +112,9 @@ func TestGitHubScoreLabels(t *testing.T) { if strings.Join(added, "|") != "Quality Score: 85|Security Score: 100|Maintainability Score: 70" { t.Errorf("added = %v", added) } + if len(patched) != 1 || !strings.Contains(patched[0], "Maintainability Score: 70") || !strings.Contains(patched[0], `"fb8c00"`) { + t.Errorf("only the label in another colour is recoloured: %v", patched) + } } func TestCommitStatus(t *testing.T) { diff --git a/pkg/vcs/vcs.go b/pkg/vcs/vcs.go index ac97cc6..02130a9 100644 --- a/pkg/vcs/vcs.go +++ b/pkg/vcs/vcs.go @@ -181,6 +181,11 @@ type ScoreLabel struct { // GitLabScoreLabel and GitHubScoreLabel name the labels. GitLab's "::" makes // them scoped labels (one value per key). +// sameColor compares hex colours, ignoring case and a leading #. +func sameColor(a, b string) bool { + return strings.EqualFold(strings.TrimPrefix(a, "#"), strings.TrimPrefix(b, "#")) +} + func GitLabScoreLabel(name string, v int) string { return fmt.Sprintf("%s Score::%d", name, v) } func GitHubScoreLabel(name string, v int) string { return fmt.Sprintf("%s Score: %d", name, v) }