Skip to content

Commit

Permalink
Add more test coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
prymitive committed Mar 18, 2022
1 parent a98e6ec commit 71d5eb3
Show file tree
Hide file tree
Showing 8 changed files with 115 additions and 74 deletions.
50 changes: 19 additions & 31 deletions cmd/pint/ci.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,31 +25,18 @@ var ciCmd = &cli.Command{
Action: actionCI,
}

func actionCI(c *cli.Context) (err error) {
err = initLogger(c.String(logLevelFlag), c.Bool(noColorFlag))
func actionCI(c *cli.Context) error {
meta, err := actionSetup(c)
if err != nil {
return fmt.Errorf("failed to set log level: %w", err)
}

workers := c.Int(workersFlag)
if workers < 1 {
return fmt.Errorf("--%s flag must be > 0", workersFlag)
}

cfg, err := config.Load(c.Path(configFlag), c.IsSet(configFlag))
if err != nil {
return fmt.Errorf("failed to load config file %q: %w", c.Path(configFlag), err)
}
if c.Bool(offlineFlag) {
cfg.DisableOnlineChecks()
return err
}

includeRe := []*regexp.Regexp{}
for _, pattern := range cfg.CI.Include {
for _, pattern := range meta.cfg.CI.Include {
includeRe = append(includeRe, regexp.MustCompile("^"+pattern+"$"))
}

baseBranch := strings.Split(cfg.CI.BaseBranch, "/")[len(strings.Split(cfg.CI.BaseBranch, "/"))-1]
baseBranch := strings.Split(meta.cfg.CI.BaseBranch, "/")[len(strings.Split(meta.cfg.CI.BaseBranch, "/"))-1]
currentBranch, err := git.CurrentBranch(git.RunGit)
if err != nil {
return fmt.Errorf("failed to get the name of current branch")
Expand All @@ -60,38 +47,39 @@ func actionCI(c *cli.Context) (err error) {
return nil
}

finder := discovery.NewGitBranchFinder(git.RunGit, includeRe, cfg.CI.BaseBranch, cfg.CI.MaxCommits)
finder := discovery.NewGitBranchFinder(git.RunGit, includeRe, meta.cfg.CI.BaseBranch, meta.cfg.CI.MaxCommits)
entries, err := finder.Find()
if err != nil {
return err
}

ctx := context.WithValue(context.Background(), config.CommandKey, config.CICommand)
summary := checkRules(ctx, workers, cfg, entries)
summary := checkRules(ctx, meta.workers, meta.cfg, entries)

reps := []reporter.Reporter{
reporter.NewConsoleReporter(os.Stderr),
}

if cfg.Repository != nil && cfg.Repository.BitBucket != nil {
if meta.cfg.Repository != nil && meta.cfg.Repository.BitBucket != nil {
token, ok := os.LookupEnv("BITBUCKET_AUTH_TOKEN")
if !ok {
return fmt.Errorf("BITBUCKET_AUTH_TOKEN env variable is required when reporting to BitBucket")
}

timeout, _ := time.ParseDuration(cfg.Repository.BitBucket.Timeout)
timeout, _ := time.ParseDuration(meta.cfg.Repository.BitBucket.Timeout)
br := reporter.NewBitBucketReporter(
cfg.Repository.BitBucket.URI,
version,
meta.cfg.Repository.BitBucket.URI,
timeout,
token,
cfg.Repository.BitBucket.Project,
cfg.Repository.BitBucket.Repository,
meta.cfg.Repository.BitBucket.Project,
meta.cfg.Repository.BitBucket.Repository,
git.RunGit,
)
reps = append(reps, br)
}

if cfg.Repository != nil && cfg.Repository.GitHub != nil {
if meta.cfg.Repository != nil && meta.cfg.Repository.GitHub != nil {
token, ok := os.LookupEnv("GITHUB_AUTH_TOKEN")
if !ok {
return fmt.Errorf("GITHUB_AUTH_TOKEN env variable is required when reporting to GitHub")
Expand All @@ -107,14 +95,14 @@ func actionCI(c *cli.Context) (err error) {
return fmt.Errorf("got not a valid number via GITHUB_PULL_REQUEST_NUMBER: %w", err)
}

timeout, _ := time.ParseDuration(cfg.Repository.GitHub.Timeout)
timeout, _ := time.ParseDuration(meta.cfg.Repository.GitHub.Timeout)
gr := reporter.NewGithubReporter(
cfg.Repository.GitHub.BaseURI,
cfg.Repository.GitHub.UploadURI,
meta.cfg.Repository.GitHub.BaseURI,
meta.cfg.Repository.GitHub.UploadURI,
timeout,
token,
cfg.Repository.GitHub.Owner,
cfg.Repository.GitHub.Repo,
meta.cfg.Repository.GitHub.Owner,
meta.cfg.Repository.GitHub.Repo,
prNum,
git.RunGit,
)
Expand Down
22 changes: 4 additions & 18 deletions cmd/pint/lint.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,39 +20,25 @@ var lintCmd = &cli.Command{
Action: actionLint,
}

func actionLint(c *cli.Context) (err error) {
err = initLogger(c.String(logLevelFlag), c.Bool(noColorFlag))
func actionLint(c *cli.Context) error {
meta, err := actionSetup(c)
if err != nil {
return fmt.Errorf("failed to set log level: %w", err)
}

workers := c.Int(workersFlag)
if workers < 1 {
return fmt.Errorf("--%s flag must be > 0", workersFlag)
return err
}

paths := c.Args().Slice()
if len(paths) == 0 {
return fmt.Errorf("at least one file or directory required")
}

cfg, err := config.Load(c.Path(configFlag), c.IsSet(configFlag))
if err != nil {
return fmt.Errorf("failed to load config file %q: %w", c.Path(configFlag), err)
}
cfg.SetDisabledChecks(c.StringSlice(disabledFlag))
if c.Bool(offlineFlag) {
cfg.DisableOnlineChecks()
}

finder := discovery.NewGlobFinder(paths...)
entries, err := finder.Find()
if err != nil {
return err
}

ctx := context.WithValue(context.Background(), config.CommandKey, config.LintCommand)
summary := checkRules(ctx, workers, cfg, entries)
summary := checkRules(ctx, meta.workers, meta.cfg, entries)

r := reporter.NewConsoleReporter(os.Stderr)
err = r.Submit(summary)
Expand Down
31 changes: 31 additions & 0 deletions cmd/pint/main.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
package main

import (
"fmt"
"os"

"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/urfave/cli/v2"

"github.com/cloudflare/pint/internal/config"
)

const (
Expand Down Expand Up @@ -74,6 +77,34 @@ func newApp() *cli.App {
}
}

type actionMeta struct {
cfg config.Config
workers int
}

func actionSetup(c *cli.Context) (meta actionMeta, err error) {
err = initLogger(c.String(logLevelFlag), c.Bool(noColorFlag))
if err != nil {
return meta, fmt.Errorf("failed to set log level: %w", err)
}

meta.workers = c.Int(workersFlag)
if meta.workers < 1 {
return meta, fmt.Errorf("--%s flag must be > 0", workersFlag)
}

meta.cfg, err = config.Load(c.Path(configFlag), c.IsSet(configFlag))
if err != nil {
return meta, fmt.Errorf("failed to load config file %q: %w", c.Path(configFlag), err)
}
meta.cfg.SetDisabledChecks(c.StringSlice(disabledFlag))
if c.Bool(offlineFlag) {
meta.cfg.DisableOnlineChecks()
}

return meta, nil
}

func main() {
app := newApp()
err := app.Run(os.Args)
Expand Down
6 changes: 6 additions & 0 deletions cmd/pint/tests/0064_watch_no_path.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
pint.error --no-color watch --listen=:6064
! stdout .
cmp stderr stderr.txt

-- stderr.txt --
level=fatal msg="Fatal error" error="at least one file or directory required"
41 changes: 41 additions & 0 deletions cmd/pint/tests/0065_ci_include.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
mkdir testrepo
cd testrepo
exec git init --initial-branch=main .

cp ../src/.pint.hcl .
env GIT_AUTHOR_NAME=pint
env GIT_AUTHOR_EMAIL=pint@example.com
env GIT_COMMITTER_NAME=pint
env GIT_COMMITTER_EMAIL=pint@example.com
exec git add .
exec git commit -am 'import rules and config'

exec git checkout -b v1
cp ../src/a.yml a.yml
exec git add a.yml
exec git commit -am 'v1'

exec git checkout -b v2
cp ../src/b.yml b.yml
exec git add b.yml
exec git commit -am 'v2'

pint.ok -l debug --no-color ci
! stdout .
stderr 'level=debug msg="Got branch information" base=main current=v2'
stderr 'level=debug msg="Found commit to scan" commit=.*'
stderr 'level=debug msg="Found commit to scan" commit=.*'
stderr 'level=debug msg="Git file change" allowed=false commit=.* path=a.yml'
stderr 'level=debug msg="Git file change" allowed=false commit=.* path=b.yml'

-- src/a.yml --
- record: rule1
expr: sum(foo) bi()
-- src/b.yml --
- record: rule1
expr: sum(foo) bi()
-- src/.pint.hcl --
ci {
baseBranch = "main"
include = ["xxx"]
}
24 changes: 5 additions & 19 deletions cmd/pint/watch.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,15 +73,10 @@ var watchCmd = &cli.Command{
},
}

func actionWatch(c *cli.Context) (err error) {
err = initLogger(c.String(logLevelFlag), c.Bool(noColorFlag))
func actionWatch(c *cli.Context) error {
meta, err := actionSetup(c)
if err != nil {
return fmt.Errorf("failed to set log level: %w", err)
}

workers := c.Int(workersFlag)
if workers < 1 {
return fmt.Errorf("--%s flag must be > 0", workersFlag)
return err
}

paths := c.Args().Slice()
Expand All @@ -94,15 +89,6 @@ func actionWatch(c *cli.Context) (err error) {
return fmt.Errorf("invalid %s value: %w", minSeverityFlag, err)
}

cfg, err := config.Load(c.Path(configFlag), c.IsSet(configFlag))
if err != nil {
return fmt.Errorf("failed to load config file %q: %w", c.Path(configFlag), err)
}
cfg.SetDisabledChecks(c.StringSlice(disabledFlag))
if c.Bool(offlineFlag) {
cfg.DisableOnlineChecks()
}

pidfile := c.String(pidfileFlag)
if pidfile != "" {
pid := os.Getpid()
Expand All @@ -121,7 +107,7 @@ func actionWatch(c *cli.Context) (err error) {
}

// start HTTP server for metrics
collector := newProblemCollector(cfg, paths, minSeverity, c.Int(maxProblemsFlag))
collector := newProblemCollector(meta.cfg, paths, minSeverity, c.Int(maxProblemsFlag))
// register all metrics
prometheus.MustRegister(collector)
prometheus.MustRegister(checkDuration)
Expand Down Expand Up @@ -156,7 +142,7 @@ func actionWatch(c *cli.Context) (err error) {
// start timer to run every $interval
interval := c.Duration(intervalFlag)
ack := make(chan bool, 1)
stop := startTimer(mainCtx, cfg, workers, interval, ack, collector)
stop := startTimer(mainCtx, meta.cfg, meta.workers, interval, ack, collector)

quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
Expand Down
6 changes: 4 additions & 2 deletions internal/reporter/bitbucket.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,9 @@ type BitBucketAnnotations struct {
Annotations []BitBucketAnnotation `json:"annotations"`
}

func NewBitBucketReporter(uri string, timeout time.Duration, token, project, repo string, gitCmd git.CommandRunner) BitBucketReporter {
func NewBitBucketReporter(version, uri string, timeout time.Duration, token, project, repo string, gitCmd git.CommandRunner) BitBucketReporter {
return BitBucketReporter{
version: version,
uri: uri,
timeout: timeout,
authToken: token,
Expand All @@ -46,6 +47,7 @@ func NewBitBucketReporter(uri string, timeout time.Duration, token, project, rep
// BitBucketReporter send linter results to BitBucket using
// https://docs.atlassian.com/bitbucket-server/rest/7.8.0/bitbucket-code-insights-rest.html
type BitBucketReporter struct {
version string
uri string
timeout time.Duration
authToken string
Expand Down Expand Up @@ -176,7 +178,7 @@ func (r BitBucketReporter) createReport(commit string, isPassing bool) error {
result = "FAIL"
}
payload, _ := json.Marshal(BitBucketReport{
Title: "Pint - Prometheus rules linter",
Title: fmt.Sprintf("Pint - Prometheus rules linter (version: %s)", r.version),
Result: result,
})

Expand Down
9 changes: 5 additions & 4 deletions internal/reporter/bitbucket_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ func TestBitBucketReporter(t *testing.T) {
},
},
report: reporter.BitBucketReport{
Title: "Pint - Prometheus rules linter",
Title: "Pint - Prometheus rules linter (version: v0.0.0)",
Result: "FAIL",
},
annotations: reporter.BitBucketAnnotations{
Expand Down Expand Up @@ -337,7 +337,7 @@ func TestBitBucketReporter(t *testing.T) {
},
},
report: reporter.BitBucketReport{
Title: "Pint - Prometheus rules linter",
Title: "Pint - Prometheus rules linter (version: v0.0.0)",
Result: "FAIL",
},
annotations: reporter.BitBucketAnnotations{
Expand Down Expand Up @@ -373,7 +373,7 @@ func TestBitBucketReporter(t *testing.T) {
},
summary: reporter.Summary{},
report: reporter.BitBucketReport{
Title: "Pint - Prometheus rules linter",
Title: "Pint - Prometheus rules linter (version: v0.0.0)",
Result: "PASS",
},
errorHandler: func(err error) error {
Expand Down Expand Up @@ -455,7 +455,7 @@ func TestBitBucketReporter(t *testing.T) {
},
},
report: reporter.BitBucketReport{
Title: "Pint - Prometheus rules linter",
Title: "Pint - Prometheus rules linter (version: v0.0.0)",
Result: "PASS",
},
annotations: reporter.BitBucketAnnotations{
Expand Down Expand Up @@ -516,6 +516,7 @@ func TestBitBucketReporter(t *testing.T) {
defer srv.Close()

r := reporter.NewBitBucketReporter(
"v0.0.0",
srv.URL,
time.Second,
"token",
Expand Down

0 comments on commit 71d5eb3

Please sign in to comment.