Skip to content

Commit

Permalink
Merge pull request #168 from k1LoW/summary
Browse files Browse the repository at this point in the history
Support for adding code metrics report to GitHub Actions Job Summaries
  • Loading branch information
k1LoW authored Sep 17, 2022
2 parents f3d1a15 + b9585f8 commit 022f790
Show file tree
Hide file tree
Showing 13 changed files with 191 additions and 40 deletions.
6 changes: 6 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
linters:
fast: false
enable:
- gosec
- misspell
linters-settings:
staticcheck:
go: 1.16
misspell:
locale: US
ignore-words: []
issues:
exclude:
- SA3000
2 changes: 2 additions & 0 deletions .octocov.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ push:
if: is_default_branch
comment:
if: is_pull_request
summary:
if: is_pull_request
report:
if: is_default_branch
datastores:
Expand Down
5 changes: 1 addition & 4 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ BUILD_LDFLAGS = -X $(PKG).commit=$(COMMIT) -X $(PKG).date=$(DATE)

default: test

ci: depsdev test test_no_coverage sec
ci: depsdev test test_no_coverage

test:
go test ./... -coverprofile=coverage.out -covermode=count
Expand All @@ -28,9 +28,6 @@ test_no_coverage: build
test_collect_metrics: build
./octocov --config testdata/octocov_parallel_tests.yml

sec:
gosec ./...

lint:
golangci-lint run ./...

Expand Down
41 changes: 28 additions & 13 deletions cmd/comment.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
"github.com/k1LoW/octocov/report"
)

func commentReport(ctx context.Context, c *config.Config, r, rPrev *report.Report) error {
func commentReport(ctx context.Context, c *config.Config, content, key string) error {
repo, err := gh.Parse(c.Repository)
if err != nil {
return err
Expand All @@ -24,9 +24,34 @@ func commentReport(ctx context.Context, c *config.Config, r, rPrev *report.Repor
if err != nil {
return err
}
if c.Comment.DeletePrevious {
if err := g.PutCommentWithDeletion(ctx, repo.Owner, repo.Repo, n, content, key); err != nil {
return err
}
} else {
if err := g.PutComment(ctx, repo.Owner, repo.Repo, n, content, key); err != nil {
return err
}
}
return nil
}

func createReportContent(ctx context.Context, c *config.Config, r, rPrev *report.Report) (string, error) {
repo, err := gh.Parse(c.Repository)
if err != nil {
return "", err
}
g, err := gh.New()
if err != nil {
return "", err
}
n, err := g.DetectCurrentPullRequestNumber(ctx, repo.Owner, repo.Repo)
if err != nil {
return "", err
}
files, err := g.GetPullRequestFiles(ctx, repo.Owner, repo.Repo, n)
if err != nil {
return err
return "", err
}
footer := "Reported by [octocov](https://github.com/k1LoW/octocov)"
if c.Comment.HideFooterLink {
Expand Down Expand Up @@ -66,17 +91,7 @@ func commentReport(ctx context.Context, c *config.Config, r, rPrev *report.Repor
footer,
)

if c.Comment.DeletePrevious {
if err := g.PutCommentWithDeletion(ctx, repo.Owner, repo.Repo, n, strings.Join(comment, "\n"), r.Key()); err != nil {
return err
}
} else {
if err := g.PutComment(ctx, repo.Owner, repo.Repo, n, strings.Join(comment, "\n"), r.Key()); err != nil {
return err
}
}

return nil
return strings.Join(comment, "\n"), nil
}

func capitalize(w string) string {
Expand Down
31 changes: 30 additions & 1 deletion cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -340,7 +340,36 @@ var rootCmd = &cobra.Command{
if err := c.DiffConfigReady(); err != nil {
cmd.PrintErrf("Skip comparing reports: %v\n", err)
}
if err := commentReport(ctx, c, r, rPrev); err != nil {
content, err := createReportContent(ctx, c, r, rPrev)
if err != nil {
return err
}
if err := commentReport(ctx, c, content, r.Key()); err != nil {
return err
}
return nil
}(); err != nil {
cmd.PrintErrf("Skip commenting the report to pull request: %v\n", err)
}
}

// Add report to job summaries
if err := c.SummaryConfigReady(); err != nil {
cmd.PrintErrf("Skip adding report to job summaries: %v\n", err)
} else {
if err := func() error {
cmd.PrintErrln("Adding report...")
if rPrev == nil {
cmd.PrintErrln("Skip comparing reports: previous report not found")
}
if err := c.DiffConfigReady(); err != nil {
cmd.PrintErrf("Skip comparing reports: %v\n", err)
}
content, err := createReportContent(ctx, c, r, rPrev)
if err != nil {
return err
}
if err := addReportContentToSummary(content); err != nil {
return err
}
return nil
Expand Down
25 changes: 25 additions & 0 deletions cmd/summary.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package cmd

import (
"fmt"
"os"
"path/filepath"
)

func addReportContentToSummary(content string) error {
p := os.Getenv("GITHUB_STEP_SUMMARY")
if _, err := os.Stat(p); err != nil {
return err
}
f, err := os.OpenFile(filepath.Clean(p), os.O_RDWR|os.O_CREATE|os.O_APPEND, os.ModePerm)
if err != nil {
return err
}
defer func() {
_ = f.Close()
}()
if _, err := fmt.Fprintln(f, content); err != nil {
return err
}
return nil
}
5 changes: 5 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ type Config struct {
Central *ConfigCentral `yaml:"central,omitempty"`
Push *ConfigPush `yaml:"push,omitempty"`
Comment *ConfigComment `yaml:"comment,omitempty"`
Summary *ConfigSummary `yaml:"summary,omitempty"`
Diff *ConfigDiff `yaml:"diff,omitempty"`
GitRoot string `yaml:"-"`
// working directory
Expand Down Expand Up @@ -110,6 +111,10 @@ type ConfigComment struct {
If string `yaml:"if,omitempty"`
}

type ConfigSummary struct {
If string `yaml:"if,omitempty"`
}

type ConfigDiff struct {
Path string `yaml:"path,omitempty"`
Datastores []string `yaml:"datastores,omitempty"`
Expand Down
36 changes: 36 additions & 0 deletions config/ready.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"os"

"github.com/k1LoW/octocov/gh"
)
Expand Down Expand Up @@ -87,6 +88,41 @@ func (c *Config) CommentConfigReady() error {
return nil
}

func (c *Config) SummaryConfigReady() error {
if c.Summary == nil {
return errors.New("summary: is not set")
}
if c.Repository == "" {
return fmt.Errorf("env %s is not set", "GITHUB_REPOSITORY")
}
if os.Getenv("GITHUB_STEP_SUMMARY") == "" {
return fmt.Errorf("env %s is not set", "GITHUB_STEP_SUMMARY")
}
ctx := context.Background()
repo, err := gh.Parse(c.Repository)
if err != nil {
return err
}
if c.gh == nil {
g, err := gh.New()
if err != nil {
return err
}
c.gh = g
}
if _, err := c.gh.DetectCurrentPullRequestNumber(ctx, repo.Owner, repo.Repo); err != nil {
return err
}
ok, err := c.CheckIf(c.Summary.If)
if err != nil {
return err
}
if !ok {
return fmt.Errorf("the condition in the `if` section is not met (%s)", c.Summary.If)
}
return nil
}

func (c *Config) CoverageBadgeConfigReady() error {
if err := c.CoverageConfigReady(); err != nil {
return err
Expand Down
2 changes: 2 additions & 0 deletions config/yaml.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ func (c *Config) UnmarshalYAML(data []byte) error {
Central *ConfigCentral `yaml:"central,omitempty"`
Push interface{} `yaml:"push,omitempty"`
Comment interface{} `yaml:"comment,omitempty"`
Summary *ConfigSummary `yaml:"summary,omitempty"`
Diff *ConfigDiff `yaml:"diff,omitempty"`
}{}
err := yaml.Unmarshal(data, &s)
Expand All @@ -32,6 +33,7 @@ func (c *Config) UnmarshalYAML(data []byte) error {
c.TestExecutionTime = s.TestExecutionTime
c.Report = s.Report
c.Central = s.Central
c.Summary = s.Summary
c.Diff = s.Diff

switch v := s.Comment.(type) {
Expand Down
14 changes: 9 additions & 5 deletions report/diff_report.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ func (d *DiffReport) Out(w io.Writer) {
r := tablewriter.Colors{tablewriter.Bold, tablewriter.FgRedColor}
b := tablewriter.Colors{tablewriter.Bold}

d.renderTable(table, g, r, b, true)
d.renderTable(table, g, r, b, true, false)

table.Render()
}
Expand All @@ -69,7 +69,7 @@ func (d *DiffReport) Table() string {
table.SetBorders(tablewriter.Border{Left: true, Top: false, Right: true, Bottom: false})
table.SetCenterSeparator("|")
table.SetColumnAlignment([]int{tablewriter.ALIGN_LEFT, tablewriter.ALIGN_RIGHT, tablewriter.ALIGN_RIGHT, tablewriter.ALIGN_RIGHT})
d.renderTable(table, tablewriter.Colors{}, tablewriter.Colors{}, tablewriter.Colors{}, false)
d.renderTable(table, tablewriter.Colors{}, tablewriter.Colors{}, tablewriter.Colors{}, false, true)
table.Render()

out = append(out, strings.Replace(strings.Replace(buf.String(), "---|", "--:|", 4), "--:|", "---|", 1))
Expand All @@ -80,7 +80,7 @@ func (d *DiffReport) Table() string {
table2.SetBorders(tablewriter.Border{Left: true, Top: false, Right: true, Bottom: false})
table2.SetCenterSeparator("|")
table2.SetColumnAlignment([]int{tablewriter.ALIGN_LEFT, tablewriter.ALIGN_RIGHT, tablewriter.ALIGN_RIGHT, tablewriter.ALIGN_RIGHT})
d.renderTable(table2, tablewriter.Colors{}, tablewriter.Colors{}, tablewriter.Colors{}, true)
d.renderTable(table2, tablewriter.Colors{}, tablewriter.Colors{}, tablewriter.Colors{}, true, false)
table2.Render()

t2 := leftSepRe.ReplaceAllString(buf2.String(), " |")
Expand Down Expand Up @@ -125,8 +125,12 @@ func (d *DiffReport) Table() string {
return strings.Join(out, "\n")
}

func (d *DiffReport) renderTable(table *tablewriter.Table, g, r, b tablewriter.Colors, detail bool) {
table.SetHeader([]string{"", makeHeadTitle(d.RefA, d.CommitA, d.ReportA.covPaths), makeHeadTitle(d.RefB, d.CommitB, d.ReportB.covPaths), "+/-"})
func (d *DiffReport) renderTable(table *tablewriter.Table, g, r, b tablewriter.Colors, detail bool, withLink bool) {
if withLink {
table.SetHeader([]string{"", makeHeadTitleWithLink(d.RefA, d.CommitA, d.ReportA.covPaths), makeHeadTitleWithLink(d.RefB, d.CommitB, d.ReportB.covPaths), "+/-"})
} else {
table.SetHeader([]string{"", makeHeadTitle(d.RefA, d.CommitA, d.ReportA.covPaths), makeHeadTitle(d.RefB, d.CommitB, d.ReportB.covPaths), "+/-"})
}
if d.Coverage != nil {
{
dd := d.Coverage.Diff
Expand Down
12 changes: 7 additions & 5 deletions report/diff_report_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ func TestDiff(t *testing.T) {
}

func TestDiffTable(t *testing.T) {
t.Setenv("GITHUB_SERVER_URL", "https://github.com")
t.Setenv("GITHUB_REPOSITORY", "k1LoW/octocov")
a := &Report{}
if err := a.Load(filepath.Join(testdataDir(t), "reports", "k1LoW", "tbls", "report2.json")); err != nil {
t.Fatal(err)
Expand All @@ -38,11 +40,11 @@ func TestDiffTable(t *testing.T) {
}

got := a.Compare(b).Table()
want := `| | master (896d3c5) | master (5d1e926) | +/- |
|-------------------------|-----------------:|-----------------:|-------:|
| **Coverage** | 68.5% | 38.8% | -29.7% |
| **Code to Test Ratio** | 1:0.5 | 1:0.0 | -0.5 |
| **Test Execution Time** | 4m40s | - | -4m40s |
want := `| | [master](https://github.com/k1LoW/octocov/tree/master) ([896d3c5](https://github.com/k1LoW/octocov/commit/896d3c59e6595e582eedbc7d7a05b4922ea88064)) | [master](https://github.com/k1LoW/octocov/tree/master) ([5d1e926](https://github.com/k1LoW/octocov/commit/5d1e926b41be6660d138ba73846c29e42784b473)) | +/- |
|-------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------:|-----------------------------------------------------------------------------------------------------------------------------------------------------:|-------:|
| **Coverage** | 68.5% | 38.8% | -29.7% |
| **Code to Test Ratio** | 1:0.5 | 1:0.0 | -0.5 |
| **Test Execution Time** | 4m40s | - | -4m40s |
` + "\n<details>\n\n<summary>Details</summary>\n\n``` diff\n" + ` | | master (896d3c5) | master (5d1e926) | +/- |
|---------------------|------------------|------------------|---------|
- | Coverage | 68.5% | 38.8% | -29.7% |
Expand Down
25 changes: 25 additions & 0 deletions report/report.go
Original file line number Diff line number Diff line change
Expand Up @@ -448,6 +448,31 @@ func makeHeadTitle(ref, commit string, covPaths []string) string {
return fmt.Sprintf("%s (%s)", ref, commit)
}

func makeHeadTitleWithLink(ref, commit string, covPaths []string) string {
var (
refLink string
commitLink string
)
repoURL := fmt.Sprintf("%s/%s", os.Getenv("GITHUB_SERVER_URL"), os.Getenv("GITHUB_REPOSITORY"))
switch {
case strings.HasPrefix(ref, "refs/heads/"):
branch := strings.TrimPrefix(ref, "refs/heads/")
refLink = fmt.Sprintf("[%s](%s/tree/%s)", branch, repoURL, branch)
case strings.HasPrefix(ref, "refs/pull/"):
n := strings.TrimPrefix(strings.TrimSuffix(strings.TrimSuffix(ref, "/head"), "/merge"), "refs/pull/")
refLink = fmt.Sprintf("[#%s](%s/pull/%s)", n, repoURL, n)
}
if len(commit) > 7 {
commitLink = fmt.Sprintf("[%s](%s/commit/%s)", commit[:7], repoURL, commit)
} else {
commitLink = "-"
}
if ref == "" {
return strings.Join(covPaths, ", ")
}
return fmt.Sprintf("%s (%s)", refLink, commitLink)
}

type timePoint struct {
t time.Time
c int
Expand Down
27 changes: 15 additions & 12 deletions report/report_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"testing"
"time"

"github.com/google/go-cmp/cmp"
"github.com/k1LoW/octocov/gh"
"github.com/k1LoW/octocov/pkg/coverage"
"github.com/k1LoW/octocov/pkg/ratio"
Expand Down Expand Up @@ -194,18 +195,20 @@ func TestOut(t *testing.T) {
},
}
for _, tt := range tests {
r := &Report{}
if err := r.Load(tt.path); err != nil {
t.Fatal(err)
}
buf := new(bytes.Buffer)
if err := r.Out(buf); err != nil {
t.Fatal(err)
}
got := buf.String()
if got != tt.want {
t.Errorf("got\n%v\n%#v\nwant\n%v\n%#v", got, got, tt.want, tt.want)
}
t.Run(tt.path, func(t *testing.T) {
r := &Report{}
if err := r.Load(tt.path); err != nil {
t.Fatal(err)
}
buf := new(bytes.Buffer)
if err := r.Out(buf); err != nil {
t.Fatal(err)
}
got := buf.String()
if diff := cmp.Diff(got, tt.want, nil); diff != "" {
t.Errorf("%s", diff)
}
})
}
}

Expand Down

0 comments on commit 022f790

Please sign in to comment.