Skip to content

Commit 84629f7

Browse files
brianmcgeeBrian McGee
authored and
Brian McGee
committed
feat: support fail on change (#16)
Closes #8 Signed-off-by: Brian McGee <[email protected]> Reviewed-on: https://git.numtide.com/numtide/treefmt/pulls/16 Reviewed-by: Jonas Chevalier <[email protected]> Co-authored-by: Brian McGee <[email protected]> Co-committed-by: Brian McGee <[email protected]>
1 parent aebbcfd commit 84629f7

File tree

3 files changed

+28
-0
lines changed

3 files changed

+28
-0
lines changed

internal/cli/cli.go

+1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ type Options struct {
1010
AllowMissingFormatter bool `default:"false" help:"Do not exit with error if a configured formatter is missing"`
1111
ClearCache bool `short:"c" help:"Reset the evaluation cache. Use in case the cache is not precise enough"`
1212
ConfigFile string `type:"existingfile" default:"./treefmt.toml"`
13+
FailOnChange bool `help:"Exit with error if any changes were made. Useful for CI"`
1314
Formatters []string `help:"Specify formatters to apply. Defaults to all formatters"`
1415
TreeRoot string `type:"existingdir" default:"."`
1516
Verbosity int `name:"verbose" short:"v" type:"counter" default:"0" env:"LOG_LEVEL" help:"Set the verbosity of logs e.g. -vv"`

internal/cli/format.go

+6
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ import (
1818

1919
type Format struct{}
2020

21+
var ErrFailOnChange = errors.New("unexpected changes detected, --fail-on-change is enabled")
22+
2123
func (f *Format) Run() error {
2224
start := time.Now()
2325

@@ -155,6 +157,10 @@ func (f *Format) Run() error {
155157
}
156158
changes += count
157159

160+
if Cli.FailOnChange && changes != 0 {
161+
return ErrFailOnChange
162+
}
163+
158164
fmt.Printf("%v files changed in %v", changes, time.Now().Sub(start))
159165
return nil
160166
})

internal/cli/format_test.go

+21
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,27 @@ func TestCache(t *testing.T) {
179179
as.Contains(string(out), "0 files changed")
180180
}
181181

182+
func TestFailOnChange(t *testing.T) {
183+
as := require.New(t)
184+
185+
tempDir := test.TempExamples(t)
186+
configPath := tempDir + "/echo.toml"
187+
188+
// test without any excludes
189+
config := format.Config{
190+
Formatters: map[string]*format.Formatter{
191+
"echo": {
192+
Command: "echo",
193+
Includes: []string{"*"},
194+
},
195+
},
196+
}
197+
198+
test.WriteConfig(t, configPath, config)
199+
_, err := cmd(t, "--fail-on-change", "--config-file", configPath, "--tree-root", tempDir)
200+
as.ErrorIs(err, ErrFailOnChange)
201+
}
202+
182203
func TestBustCacheOnFormatterChange(t *testing.T) {
183204
as := require.New(t)
184205

0 commit comments

Comments
 (0)