From 84629f7b9490e42fe89b763b72afa666d61c2f17 Mon Sep 17 00:00:00 2001 From: Brian McGee Date: Wed, 3 Jan 2024 13:10:54 +0000 Subject: [PATCH] feat: support fail on change (#16) Closes #8 Signed-off-by: Brian McGee Reviewed-on: https://git.numtide.com/numtide/treefmt/pulls/16 Reviewed-by: Jonas Chevalier Co-authored-by: Brian McGee Co-committed-by: Brian McGee --- internal/cli/cli.go | 1 + internal/cli/format.go | 6 ++++++ internal/cli/format_test.go | 21 +++++++++++++++++++++ 3 files changed, 28 insertions(+) diff --git a/internal/cli/cli.go b/internal/cli/cli.go index 4d70b71..9915ee0 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -10,6 +10,7 @@ type Options struct { AllowMissingFormatter bool `default:"false" help:"Do not exit with error if a configured formatter is missing"` ClearCache bool `short:"c" help:"Reset the evaluation cache. Use in case the cache is not precise enough"` ConfigFile string `type:"existingfile" default:"./treefmt.toml"` + FailOnChange bool `help:"Exit with error if any changes were made. Useful for CI"` Formatters []string `help:"Specify formatters to apply. Defaults to all formatters"` TreeRoot string `type:"existingdir" default:"."` Verbosity int `name:"verbose" short:"v" type:"counter" default:"0" env:"LOG_LEVEL" help:"Set the verbosity of logs e.g. -vv"` diff --git a/internal/cli/format.go b/internal/cli/format.go index 298030a..9483a5b 100644 --- a/internal/cli/format.go +++ b/internal/cli/format.go @@ -18,6 +18,8 @@ import ( type Format struct{} +var ErrFailOnChange = errors.New("unexpected changes detected, --fail-on-change is enabled") + func (f *Format) Run() error { start := time.Now() @@ -155,6 +157,10 @@ func (f *Format) Run() error { } changes += count + if Cli.FailOnChange && changes != 0 { + return ErrFailOnChange + } + fmt.Printf("%v files changed in %v", changes, time.Now().Sub(start)) return nil }) diff --git a/internal/cli/format_test.go b/internal/cli/format_test.go index a172755..c487227 100644 --- a/internal/cli/format_test.go +++ b/internal/cli/format_test.go @@ -179,6 +179,27 @@ func TestCache(t *testing.T) { as.Contains(string(out), "0 files changed") } +func TestFailOnChange(t *testing.T) { + as := require.New(t) + + tempDir := test.TempExamples(t) + configPath := tempDir + "/echo.toml" + + // test without any excludes + config := format.Config{ + Formatters: map[string]*format.Formatter{ + "echo": { + Command: "echo", + Includes: []string{"*"}, + }, + }, + } + + test.WriteConfig(t, configPath, config) + _, err := cmd(t, "--fail-on-change", "--config-file", configPath, "--tree-root", tempDir) + as.ErrorIs(err, ErrFailOnChange) +} + func TestBustCacheOnFormatterChange(t *testing.T) { as := require.New(t)