diff --git a/cmd/fix.go b/cmd/fix.go index 9d85b1f3..e935464d 100644 --- a/cmd/fix.go +++ b/cmd/fix.go @@ -49,6 +49,7 @@ type fixCommandParams struct { timeout time.Duration dryRun bool verbose bool + force bool } func (p *fixCommandParams) getConfigFile() string { @@ -146,6 +147,9 @@ The linter rules with automatic fixes available are currently: fixCommand.Flags().BoolVarP(¶ms.verbose, "verbose", "", false, "show the full changes applied in the console") + fixCommand.Flags().BoolVarP(¶ms.force, "force", "", false, + "allow fixing of files that have uncommitted changes in git or when git is not being used") + addPprofFlag(fixCommand.Flags()) RootCommand.AddCommand(fixCommand) @@ -314,14 +318,18 @@ func fix(args []string, params *fixCommandParams) error { return fmt.Errorf("failed to fix: %w", err) } + gitRepo, err := git.FindGitRepo(args...) + if err != nil { + return fmt.Errorf("failed to establish git repo: %w", err) + } + + if gitRepo == "" && !params.force { + return errors.New("no git repo found to support undo, use --force to override") + } + // if the fixer is being run in a git repo, we must not fix files that have // been changed. - if !params.dryRun { - gitRepo, err := git.FindGitRepo(args...) - if err != nil { - return fmt.Errorf("failed to establish git repo: %w", err) - } - + if !params.dryRun && !params.force { changedFiles := make(map[string]struct{}) if gitRepo != "" { diff --git a/e2e/cli_test.go b/e2e/cli_test.go index a14050f5..47ef262f 100644 --- a/e2e/cli_test.go +++ b/e2e/cli_test.go @@ -822,7 +822,8 @@ test_allow { mustWriteToFile(t, filepath.Join(td, file), string(content)) } - err := regal(&stdout, &stderr)("fix", filepath.Join(td, "foo"), filepath.Join(td, "bar")) + // --force is required to make the changes when there is no git repo + err := regal(&stdout, &stderr)("fix", "--force", filepath.Join(td, "foo"), filepath.Join(td, "bar")) // 0 exit status is expected as all violations should have been fixed expectExitCode(t, err, 0, &stdout, &stderr)