From 3304f6c463637a84d543c8f98168cbdeb3ac6f01 Mon Sep 17 00:00:00 2001 From: Ayooluwa Isaiah Date: Wed, 2 Oct 2024 00:36:50 +0100 Subject: [PATCH] fix linting errors --- app/app.go | 17 ++++---- app/app_test/app_test.go | 15 +++++-- app/app_test/app_unix_test.go | 11 +++-- app/help.go | 2 +- f2.go | 6 +-- find/csv.go | 1 + find/find.go | 5 ++- find/find_internal_test.go | 4 +- find/find_test/find_csv_test.go | 4 +- find/find_test/find_test.go | 2 +- find/find_test/find_unix_test.go | 6 +-- internal/apperr/apperr.go | 4 +- internal/config/config.go | 43 ++++++++++--------- internal/config/errors.go | 4 -- internal/file/file.go | 7 +-- internal/sortfiles/sortfiles.go | 4 ++ .../sortfiles_test/sortfiles_test.go | 2 +- internal/testutil/testutil.go | 25 ++++++----- rename/backup.go | 11 +---- rename/rename.go | 1 + rename/rename_test/rename_test.go | 5 +-- replace/replace.go | 7 ++- replace/replace_test/variables_test.go | 2 +- replace/variables.go | 4 +- report/report.go | 12 +++++- report/report_test/report_test.go | 2 + validate/validate.go | 10 ++--- validate/validate_internal_test.go | 2 +- .../validate_test/validate_windows_test.go | 2 +- 29 files changed, 122 insertions(+), 98 deletions(-) diff --git a/app/app.go b/app/app.go index 53bef7f..eb3e840 100644 --- a/app/app.go +++ b/app/app.go @@ -9,11 +9,12 @@ import ( "os" "strings" - "github.com/ayoisaiah/f2/internal/config" - "github.com/ayoisaiah/f2/internal/osutil" "github.com/pterm/pterm" "github.com/urfave/cli/v2" slogctx "github.com/veqryn/slog-context" + + "github.com/ayoisaiah/f2/internal/config" + "github.com/ayoisaiah/f2/internal/osutil" ) const ( @@ -45,20 +46,20 @@ var supportedDefaultOpts = []string{ flagVerbose.Name, } -// isInputFromPipe detects if input is being piped to F2 +// isInputFromPipe detects if input is being piped to F2. func isInputFromPipe() bool { fileInfo, _ := os.Stdin.Stat() return fileInfo.Mode()&os.ModeCharDevice == 0 } -// isOutputToPipe detects if F2's output is being piped to another command +// isOutputToPipe detects if F2's output is being piped to another command. func isOutputToPipe() bool { fileInfo, _ := os.Stdout.Stat() - return !((fileInfo.Mode() & os.ModeCharDevice) == os.ModeCharDevice) + return ((fileInfo.Mode() & os.ModeCharDevice) != os.ModeCharDevice) } -// initLogger sets up defaults for the global logger +// initLogger sets up defaults for the global logger. func initLogger() { opts := &slog.HandlerOptions{ Level: slog.LevelError, @@ -77,7 +78,7 @@ func initLogger() { slog.SetDefault(l) } -// handlePipeInput processes input from a pipe and appends it to os.Args +// handlePipeInput processes input from a pipe and appends it to os.Args. func handlePipeInput(reader io.Reader) error { if !isInputFromPipe() { return nil @@ -97,7 +98,7 @@ func handlePipeInput(reader io.Reader) error { } // loadDefaultOpts creates a CLI context with default options (F2_DEFAULT_OPTS) -// from the environment. Returns `nil` if default options do not exist +// from the environment. Returns `nil` if default options do not exist. func loadDefaultOpts() (*cli.Context, error) { var defaultCtx *cli.Context diff --git a/app/app_test/app_test.go b/app/app_test/app_test.go index cd9d94a..2ed46a5 100644 --- a/app/app_test/app_test.go +++ b/app/app_test/app_test.go @@ -5,10 +5,11 @@ import ( "os" "testing" + "github.com/urfave/cli/v2" + "github.com/ayoisaiah/f2/app" "github.com/ayoisaiah/f2/internal/config" "github.com/ayoisaiah/f2/internal/testutil" - "github.com/urfave/cli/v2" ) func TestShortHelp(t *testing.T) { @@ -94,16 +95,18 @@ func TestVersion(t *testing.T) { func TestDefaultEnv(t *testing.T) { cases := []struct { + Assert func(t *testing.T, ctx *cli.Context) Name string - Args []string DefaultOpts string - Assert func(t *testing.T, ctx *cli.Context) + Args []string }{ { Name: "enable hidden files", Args: []string{"f2_test", "--find", "jpeg"}, DefaultOpts: "--hidden", Assert: func(t *testing.T, ctx *cli.Context) { + t.Helper() + if !ctx.Bool("hidden") { t.Fatal("expected --hidden default option to be true") } @@ -114,6 +117,8 @@ func TestDefaultEnv(t *testing.T) { Args: []string{"f2_test", "--find", "jpeg"}, DefaultOpts: "--fix-conflicts-pattern _%03d", Assert: func(t *testing.T, ctx *cli.Context) { + t.Helper() + if got := ctx.String("fix-conflicts-pattern"); got != "_%03d" { t.Fatalf( "expected --fix-conflicts-pattern to default option to be _%%03d, but got: %s", @@ -133,6 +138,8 @@ func TestDefaultEnv(t *testing.T) { }, DefaultOpts: "--fix-conflicts-pattern _%03d", Assert: func(t *testing.T, ctx *cli.Context) { + t.Helper() + if got := ctx.String("fix-conflicts-pattern"); got != "_%02d" { t.Fatalf( "expected --fix-conflicts-pattern to default option to be _%%02d, but got: %s", @@ -141,7 +148,7 @@ func TestDefaultEnv(t *testing.T) { } }, }, - // TODO: Should repeatable options be overriden? + // TODO: Should repeatable options be overridden? // { // Name: "exclude node_modules and git", // Args: []string{ diff --git a/app/app_test/app_unix_test.go b/app/app_test/app_unix_test.go index 60ce72b..eb41941 100644 --- a/app/app_test/app_unix_test.go +++ b/app/app_test/app_unix_test.go @@ -8,11 +8,14 @@ import ( "os/exec" "testing" - "github.com/ayoisaiah/f2/app" "github.com/stretchr/testify/assert" + + "github.com/ayoisaiah/f2/app" ) func simulatePipe(t *testing.T, name string, arg ...string) *exec.Cmd { + t.Helper() + r, w, err := os.Pipe() if err != nil { t.Fatal(err) @@ -23,9 +26,11 @@ func simulatePipe(t *testing.T, name string, arg ...string) *exec.Cmd { cmd.Stdout = w oldStdin := os.Stdin + t.Cleanup(func() { os.Stdin = oldStdin }) + os.Stdin = r if err := cmd.Run(); err != nil { @@ -37,7 +42,7 @@ func simulatePipe(t *testing.T, name string, arg ...string) *exec.Cmd { return cmd } -// TODO: Write equivalent for Windows +// TODO: Write equivalent for Windows. func TestPipingInputFromFind(t *testing.T) { cases := []struct { name string @@ -75,7 +80,7 @@ func TestPipingInputFromFind(t *testing.T) { t.Run(tc.name, func(t *testing.T) { simulatePipe(t, "find", tc.findArgs...) - app.Get(os.Stdin, os.Stdout) + _, _ = app.Get(os.Stdin, os.Stdout) got := os.Args[len(os.Args)-len(tc.expected):] diff --git a/app/help.go b/app/help.go index 2dfe0e0..908cef4 100644 --- a/app/help.go +++ b/app/help.go @@ -357,7 +357,7 @@ func envHelp() string { ) } -func ShortHelp(app *cli.App) string { +func ShortHelp(_ *cli.App) string { return fmt.Sprintf( `The batch renaming tool you'll actually enjoy using. diff --git a/f2.go b/f2.go index c8a74ce..050a0d6 100644 --- a/f2.go +++ b/f2.go @@ -19,8 +19,8 @@ var errConflictDetected = &apperr.Error{ Message: "resolve conflicts manually or use -F/--fix-conflicts", } -// execute initiates a new renaming operation based on the provided CLI context -func execute(ctx *cli.Context) error { +// execute initiates a new renaming operation based on the provided CLI context. +func execute(_ *cli.Context) error { appConfig := config.Get() changes, err := find.Find(appConfig) @@ -65,7 +65,7 @@ func execute(ctx *cli.Context) error { return err } -// New creates a new CLI application for f2 +// New creates a new CLI application for f2. func New(reader io.Reader, writer io.Writer) (*cli.App, error) { renamer, err := app.Get(reader, writer) if err != nil { diff --git a/find/csv.go b/find/csv.go index 569d04c..cadd4e5 100644 --- a/find/csv.go +++ b/find/csv.go @@ -73,6 +73,7 @@ func handleCSV(conf *config.Config) (file.Changes, error) { continue } + return nil, statErr } diff --git a/find/find.go b/find/find.go index 84db6a6..4831767 100644 --- a/find/find.go +++ b/find/find.go @@ -9,6 +9,7 @@ import ( "strings" "github.com/adrg/xdg" + "github.com/ayoisaiah/f2/internal/config" "github.com/ayoisaiah/f2/internal/file" "github.com/ayoisaiah/f2/internal/pathutil" @@ -230,7 +231,7 @@ func loadFromBackup(conf *config.Config) (file.Changes, error) { filepath.Join("f2", "backups", conf.BackupFilename), ) if err != nil { - // The file does not exist, but it's not an error in this context + //nolint:nilerr // The file does not exist, but it's not an error in this context return nil, nil } @@ -241,7 +242,7 @@ func loadFromBackup(conf *config.Config) (file.Changes, error) { var changes file.Changes - if err = json.Unmarshal(fileBytes, &changes); err != nil { + if err := json.Unmarshal(fileBytes, &changes); err != nil { return nil, err } diff --git a/find/find_internal_test.go b/find/find_internal_test.go index 87ddebc..ae09a90 100644 --- a/find/find_internal_test.go +++ b/find/find_internal_test.go @@ -55,9 +55,9 @@ func TestIsMaxDepth(t *testing.T) { t.Run(tc.Name, func(t *testing.T) { // Ensure os-specifc separators are used - rootPath, currentPath := filepath.Join( + rootPath, currentPath := filepath.FromSlash( tc.RootPath, - ), filepath.Join( + ), filepath.FromSlash( tc.CurrentPath, ) diff --git a/find/find_test/find_csv_test.go b/find/find_test/find_csv_test.go index 0b4ff45..c559aec 100644 --- a/find/find_test/find_csv_test.go +++ b/find/find_test/find_csv_test.go @@ -18,7 +18,9 @@ var csvCases = []testutil.TestCase{ } // TestFindCSV tests file matching with CSV files. -// TODO: Test --csv +// TODO: Test --csv. func TestFindCSV(t *testing.T) { + _ = csvCases + t.Skip("not implemented") } diff --git a/find/find_test/find_test.go b/find/find_test/find_test.go index 4902224..236dd90 100644 --- a/find/find_test/find_test.go +++ b/find/find_test/find_test.go @@ -278,7 +278,7 @@ func TestFind(t *testing.T) { findTest(t, testCases) } -// TODO: Test reverting from a backup file +// TODO: Test reverting from a backup file. func TestLoadFromBackup(t *testing.T) { t.Skip("not implemented") } diff --git a/find/find_test/find_unix_test.go b/find/find_test/find_unix_test.go index 59a97b7..b3c382a 100644 --- a/find/find_test/find_unix_test.go +++ b/find/find_test/find_unix_test.go @@ -9,11 +9,7 @@ import ( "github.com/ayoisaiah/f2/internal/testutil" ) -func setHidden(path string) error { - return nil -} - -func setupWindowsHidden(t *testing.T, testDir string) (teardown func()) { +func setupWindowsHidden(_ *testing.T, _ string) (teardown func()) { return func() {} } diff --git a/internal/apperr/apperr.go b/internal/apperr/apperr.go index 1906328..7b87b69 100644 --- a/internal/apperr/apperr.go +++ b/internal/apperr/apperr.go @@ -3,9 +3,9 @@ package apperr import "fmt" type Error struct { - Cause error // The underlying error if any - Message string + Cause error Context any + Message string } func (e *Error) Error() string { diff --git a/internal/config/config.go b/internal/config/config.go index 7ed9a54..c7f01df 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -56,25 +56,25 @@ type Search struct { // Config represents the program configuration. type Config struct { Date time.Time `json:"date"` + BackupLocation io.Writer `json:"-"` ExcludeDirRegex *regexp.Regexp `json:"exclude_dir_regex"` ExcludeRegex *regexp.Regexp `json:"exclude_regex"` Search *Search `json:"search_regex"` FixConflictsPatternRegex *regexp.Regexp `json:"fix_conflicts_pattern_regex"` - Sort Sort `json:"sort"` Replacement string `json:"replacement"` WorkingDir string `json:"working_dir"` FixConflictsPattern string `json:"fix_conflicts_pattern"` CSVFilename string `json:"csv_filename"` + BackupFilename string `json:"backup_filename"` ExiftoolOpts ExiftoolOpts `json:"exiftool_opts"` - ReplacementSlice []string `json:"replacement_slice"` - FilesAndDirPaths []string `json:"files_and_dir_paths"` + PairOrder []string `json:"pair_order"` FindSlice []string `json:"find_slice"` - MaxDepth int `json:"max_depth"` - StartNumber int `json:"start_number"` + FilesAndDirPaths []string `json:"files_and_dir_paths"` + ReplacementSlice []string `json:"replacement_slice"` ReplaceLimit int `json:"replace_limit"` - AllowOverwrites bool `json:"allow_overwrites"` - ReverseSort bool `json:"reverse_sort"` - OnlyDir bool `json:"only_dir"` + StartNumber int `json:"start_number"` + MaxDepth int `json:"max_depth"` + Sort Sort `json:"sort"` Revert bool `json:"revert"` IncludeDir bool `json:"include_dir"` IgnoreExt bool `json:"ignore_ext"` @@ -90,12 +90,12 @@ type Config struct { Debug bool `json:"debug"` Recursive bool `json:"recursive"` ResetIndexPerDir bool `json:"reset_index_per_dir"` - SortPerDir bool `json:"sort_per_dir"` + OnlyDir bool `json:"only_dir"` PipeOutput bool `json:"is_output_to_pipe"` - BackupLocation io.Writer `json:"-"` - BackupFilename string `json:"backup_filename"` + ReverseSort bool `json:"reverse_sort"` + AllowOverwrites bool `json:"allow_overwrites"` Pair bool `json:"pair"` - PairOrder []string `json:"pair_order"` + SortPerDir bool `json:"sort_per_dir"` } // SetFindStringRegex compiles a regular expression for the @@ -185,6 +185,7 @@ func (c *Config) setDefaultOpts(ctx *cli.Context) error { c.Recursive = ctx.Bool("recursive") c.OnlyDir = ctx.Bool("only-dir") c.StringLiteralMode = ctx.Bool("string-mode") + //nolint:gosec // acceptable use c.MaxDepth = int(ctx.Uint("max-depth")) c.Verbose = ctx.Bool("verbose") c.AllowOverwrites = ctx.Bool("allow-overwrites") @@ -270,7 +271,7 @@ func (c *Config) setDefaultOpts(ctx *cli.Context) error { } // generateBackupFilename generates a unique filename for storing backup data -// based on the MD5 hash of the working directory path +// based on the MD5 hash of the working directory path. func generateBackupFilename(workingDir string) string { h := md5.New() h.Write([]byte(workingDir)) @@ -295,27 +296,27 @@ func Get() *Config { // configureOutput configures the output behavior of the application based // on environment variables and piping status. All output is suppressed in -// quiet mode -func (conf *Config) configureOutput() { +// quiet mode. +func (c *Config) configureOutput() { // Disable coloured output if NO_COLOR is set if _, exists := os.LookupEnv(EnvNoColor); exists { - conf.NoColor = true + c.NoColor = true } // Disable coloured output if F2_NO_COLOR is set if _, exists := os.LookupEnv(EnvF2NoColor); exists { - conf.NoColor = true + c.NoColor = true } - if conf.PipeOutput { - conf.NoColor = true + if c.PipeOutput { + c.NoColor = true } - if conf.NoColor { + if c.NoColor { pterm.DisableStyling() } - if conf.Quiet { + if c.Quiet { pterm.DisableOutput() } } diff --git a/internal/config/errors.go b/internal/config/errors.go index 0164d56..31df202 100644 --- a/internal/config/errors.go +++ b/internal/config/errors.go @@ -7,10 +7,6 @@ var ( Message: "requires one of: -f, -r, --csv, or -u. Run f2 --help for usage", } - errInvalidSimpleModeArgs = &apperr.Error{ - Message: "at least one argument must be specified in simple mode", - } - errParsingFixConflictsPattern = &apperr.Error{ Message: "the provided --fix-conflicts-pattern '%s' is invalid", } diff --git a/internal/file/file.go b/internal/file/file.go index 5d29e74..5d17fbf 100644 --- a/internal/file/file.go +++ b/internal/file/file.go @@ -6,10 +6,11 @@ import ( "path/filepath" "strings" - "github.com/ayoisaiah/f2/internal/config" - "github.com/ayoisaiah/f2/internal/status" "github.com/olekukonko/tablewriter" "github.com/pterm/pterm" + + "github.com/ayoisaiah/f2/internal/config" + "github.com/ayoisaiah/f2/internal/status" ) // Change represents a single renaming change. @@ -32,7 +33,7 @@ type Change struct { WillOverwrite bool `json:"-"` } -// AutoFixTarget sets the new target name +// AutoFixTarget sets the new target name. func (c *Change) AutoFixTarget(newTarget string) { c.Target = newTarget c.TargetPath = filepath.Join(c.BaseDir, c.Target) diff --git a/internal/sortfiles/sortfiles.go b/internal/sortfiles/sortfiles.go index e694d8e..8443a4f 100644 --- a/internal/sortfiles/sortfiles.go +++ b/internal/sortfiles/sortfiles.go @@ -36,8 +36,10 @@ func Pairs(changes file.Changes, pairOrder []string) { // Compare extensions based on pairOrder aExt, bExt := filepath.Ext(a.Source), filepath.Ext(b.Source) + for _, v := range pairOrder { v = "." + v + switch { case strings.EqualFold(aExt, v): return -1 @@ -106,6 +108,7 @@ func ByTime( aTime, bTime := sourceA.ModTime(), sourceB.ModTime() + //nolint:exhaustive // considering time sorts alone switch sortName { case config.SortMtime: case config.SortBtime: @@ -200,6 +203,7 @@ func Changes( EnforceHierarchicalOrder(changes) } + //nolint:exhaustive // default sort not needed switch sortName { case config.SortNatural: Natural(changes, reverseSort) diff --git a/internal/sortfiles/sortfiles_test/sortfiles_test.go b/internal/sortfiles/sortfiles_test/sortfiles_test.go index 2368f4d..4d38c6d 100644 --- a/internal/sortfiles/sortfiles_test/sortfiles_test.go +++ b/internal/sortfiles/sortfiles_test/sortfiles_test.go @@ -14,10 +14,10 @@ import ( type sortTestCase struct { Name string - TimeSort config.Sort Unsorted []string Sorted []string Order []string + TimeSort config.Sort ReverseSort bool SortPerDir bool Revert bool diff --git a/internal/testutil/testutil.go b/internal/testutil/testutil.go index 11b873d..4375770 100644 --- a/internal/testutil/testutil.go +++ b/internal/testutil/testutil.go @@ -22,22 +22,22 @@ import ( // TestCase represents a unique test case. type TestCase struct { Error error `json:"error"` - ConflictDetected bool `json:"conflict_detected"` + SetEnv map[string]string `json:"env"` SetupFunc func(t *testing.T, testDir string) (teardown func()) `json:"-"` + StdoutGoldenFile string `json:"stdout_golden_file"` DefaultOpts string `json:"default_opts"` Name string `json:"name"` + StderrGoldenFile string `json:"stderr_golden_file"` SnapShot struct { Stdout []byte Stderr []byte } `json:"-"` - StdoutGoldenFile string `json:"stdout_golden_file"` - StderrGoldenFile string `json:"stderr_golden_file"` - Args []string `json:"args"` - PathArgs []string `json:"path_args"` - Changes file.Changes `json:"changes"` - Want []string `json:"want"` - SetEnv map[string]string `json:"env"` - PipeOutput bool `json:"pipe_output"` + Args []string `json:"args"` + PathArgs []string `json:"path_args"` + Changes file.Changes `json:"changes"` + Want []string `json:"want"` + ConflictDetected bool `json:"conflict_detected"` + PipeOutput bool `json:"pipe_output"` } // SetupFileSystem creates all required files and folders for @@ -95,7 +95,9 @@ func SetupFileSystem( } // CompareChanges compares the expected file changes to the ones received. -func CompareChanges(t *testing.T, want file.Changes, got file.Changes) { +func CompareChanges(t *testing.T, want, got file.Changes) { + t.Helper() + assert.Equal(t, want, got) } @@ -223,7 +225,8 @@ func GetConfig(t *testing.T, tc *TestCase, testDir string) *config.Config { // Reset pterm to default state pterm.EnableStyling() // Re-initialize config with pipe output value set per test - config.Init(ctx, tc.PipeOutput) + _, _ = config.Init(ctx, tc.PipeOutput) + return nil } diff --git a/rename/backup.go b/rename/backup.go index 85073f9..71f4f49 100644 --- a/rename/backup.go +++ b/rename/backup.go @@ -7,6 +7,7 @@ import ( "path/filepath" "github.com/adrg/xdg" + "github.com/ayoisaiah/f2/internal/file" ) @@ -29,7 +30,7 @@ func createBackupFile(fileName string) (io.Writer, error) { // backupChanges records the details of a renaming operation to the specified // writer so that it may be reverted if necessary. If a writer is not specified -// it records the changes to the filesystem +// it records the changes to the filesystem. func backupChanges( changes file.Changes, fileName string, @@ -44,14 +45,6 @@ func backupChanges( } } - successfulChanges := make(file.Changes, 0, len(changes)) - - for _, change := range changes { - if change.Error == nil { - successfulChanges = append(successfulChanges, change) - } - } - err = changes.RenderJSON(w) if err != nil { return err diff --git a/rename/rename.go b/rename/rename.go index c88b40b..de7395c 100644 --- a/rename/rename.go +++ b/rename/rename.go @@ -11,6 +11,7 @@ import ( "time" "github.com/adrg/xdg" + "github.com/ayoisaiah/f2/internal/apperr" "github.com/ayoisaiah/f2/internal/config" "github.com/ayoisaiah/f2/internal/file" diff --git a/rename/rename_test/rename_test.go b/rename/rename_test/rename_test.go index 01b9d13..4c7a81d 100644 --- a/rename/rename_test/rename_test.go +++ b/rename/rename_test/rename_test.go @@ -29,8 +29,8 @@ func renameTest(t *testing.T, cases []testutil.TestCase) { } t.Cleanup(func() { - os.RemoveAll(baseDirPath) - os.Chdir(workingDir) + _ = os.RemoveAll(baseDirPath) + _ = os.Chdir(workingDir) }) err = os.Chdir(baseDirPath) @@ -153,7 +153,6 @@ func postRename(t *testing.T, cases []testutil.TestCase) { testutil.CompareGoldenFile(t, &tc) }) - } } diff --git a/replace/replace.go b/replace/replace.go index d301c9e..a98390b 100644 --- a/replace/replace.go +++ b/replace/replace.go @@ -633,7 +633,7 @@ func replaceString(conf *config.Config, originalName string) string { } // applyReplacements applies the configured replacement patterns to the source -// filename +// filename. func applyReplacement( conf *config.Config, vars *variables, @@ -666,7 +666,7 @@ func applyReplacement( return nil } -func isPair(prev *file.Change, curr *file.Change) bool { +func isPair(prev, curr *file.Change) bool { return pathutil.StripExtension( prev.SourcePath, ) == pathutil.StripExtension( @@ -705,11 +705,13 @@ func replaceMatches( change.TargetPath = filepath.Join(change.BaseDir, change.Target) change.Status = status.OK pairs++ + continue } } change.Position = i - pairs + err := applyReplacement(conf, &vars, change) if err != nil { return nil, err @@ -774,6 +776,7 @@ func Replace( ch := changes[i] conf.Replacement = ch.Target + vars, err := extractVariables(conf.Replacement) if err != nil { return nil, err diff --git a/replace/replace_test/variables_test.go b/replace/replace_test/variables_test.go index 81aff53..b131f6c 100644 --- a/replace/replace_test/variables_test.go +++ b/replace/replace_test/variables_test.go @@ -19,7 +19,7 @@ func getCurrentDate() string { return fmt.Sprintf("%d-%02d-%02d", year, month, day) } -func createDateFile(t *testing.T, testDir string) func() { +func createDateFile(t *testing.T, _ string) func() { t.Helper() dateFilePath := filepath.Join("testdata", "date.txt") diff --git a/replace/variables.go b/replace/variables.go index 50021aa..4c74632 100644 --- a/replace/variables.go +++ b/replace/variables.go @@ -644,7 +644,7 @@ func replaceExifToolVars( func replaceIndex( target string, changeIndex int, // position of change in the entire renaming operation - indexing indexVars, + indexing *indexVars, ) string { for i := range indexing.matches { current := indexing.matches[i] @@ -1082,7 +1082,7 @@ func replaceVariables( vars.index.matches = numVar.matches } - change.Target = replaceIndex(change.Target, changeIndex, vars.index) + change.Target = replaceIndex(change.Target, changeIndex, &vars.index) } return nil diff --git a/report/report.go b/report/report.go index e24b6ba..4db925e 100644 --- a/report/report.go +++ b/report/report.go @@ -63,14 +63,21 @@ func NoMatches(conf *config.Config) { pterm.Fprintln(config.Stderr, pterm.Sprint(msg)) } -// Report prints a report of the renaming changes to be made +// Report prints a report of the renaming changes to be made. func Report( conf *config.Config, fileChanges file.Changes, conflictDetected bool, ) { if conf.JSON { - fileChanges.RenderJSON(config.Stdout) + err := fileChanges.RenderJSON(config.Stdout) + if err != nil { + pterm.Fprintln( + config.Stderr, + pterm.Sprintf("%s %v", pterm.Red("error:"), err), + ) + } + return } @@ -95,6 +102,7 @@ func Report( // always printed to stderr. func PrintResults(conf *config.Config, fileChanges file.Changes, err error) { if err != nil { + //nolint:errorlint // checking if err matches custom interface renameErr, ok := err.(*apperr.Error) if ok { errIndices, ok := renameErr.Context.([]int) diff --git a/report/report_test/report_test.go b/report/report_test/report_test.go index 8f6beda..25fcea5 100644 --- a/report/report_test/report_test.go +++ b/report/report_test/report_test.go @@ -99,6 +99,7 @@ func reportTest(t *testing.T, cases []testutil.TestCase) { conf := testutil.GetConfig(t, &tc, ".") var stdout bytes.Buffer + var stderr bytes.Buffer config.Stdout = &stdout @@ -264,6 +265,7 @@ func TestExitWithErr(t *testing.T) { cmd.Env = append(os.Environ(), "BE_CRASHER=1") err := cmd.Run() + //nolint:errorlint // checking if err matches exit error if e, ok := err.(*exec.ExitError); ok && !e.Success() { return } diff --git a/validate/validate.go b/validate/validate.go index 70049b4..c523b52 100644 --- a/validate/validate.go +++ b/validate/validate.go @@ -18,11 +18,11 @@ import ( ) type validationCtx struct { - autoFix bool - allowOverwrites bool - changeIndex int change *file.Change seenPaths map[string]int + changeIndex int + autoFix bool + allowOverwrites bool } func (ctx validationCtx) updateSeenPaths() { @@ -84,7 +84,7 @@ func newTarget(change *file.Change) string { // checkSourceNotFoundConflict reports if the source file is missing in an // undo operation. It is automatically fixed by changing the status so that -// the file is skipped when renaming +// the file is skipped when renaming. func checkSourceNotFoundConflict( ctx validationCtx, ) (conflictDetected bool) { @@ -175,7 +175,7 @@ func checkPathExistsConflict( // checkTargetFileChangingConflict ensures that renaming a file to a target that // is changing later is detected to prevent data loss. It is automatically fixed -// by swapping the items around so that any renaming targets do not change later +// by swapping the items around so that any renaming targets do not change later. func checkTargetFileChangingConflict( ctx validationCtx, ) (conflictDetected bool) { diff --git a/validate/validate_internal_test.go b/validate/validate_internal_test.go index 9606b86..5355294 100644 --- a/validate/validate_internal_test.go +++ b/validate/validate_internal_test.go @@ -2,7 +2,7 @@ package validate import "testing" -// TODO: Test newTarget() function +// TODO: Test newTarget() function. func TestNewTarget(t *testing.T) { t.Skip("not implemented") } diff --git a/validate/validate_test/validate_windows_test.go b/validate/validate_test/validate_windows_test.go index f2afe4b..045f376 100644 --- a/validate/validate_test/validate_windows_test.go +++ b/validate/validate_test/validate_windows_test.go @@ -58,7 +58,7 @@ func TestValidateWindows(t *testing.T) { Source: "atomic-habits.pdf", Target: "<>:?etc.pdf", BaseDir: "ebooks", - Status: status.InvalidCharacters, + Status: status.ForbiddenCharacters, }, }, },