Skip to content

Commit

Permalink
fix linting errors
Browse files Browse the repository at this point in the history
  • Loading branch information
ayoisaiah committed Oct 1, 2024
1 parent 4144cd3 commit 3304f6c
Show file tree
Hide file tree
Showing 29 changed files with 122 additions and 98 deletions.
17 changes: 9 additions & 8 deletions app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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,
Expand All @@ -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
Expand All @@ -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

Expand Down
15 changes: 11 additions & 4 deletions app/app_test/app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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")
}
Expand All @@ -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",
Expand All @@ -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",
Expand All @@ -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{
Expand Down
11 changes: 8 additions & 3 deletions app/app_test/app_unix_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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 {
Expand All @@ -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
Expand Down Expand Up @@ -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):]

Expand Down
2 changes: 1 addition & 1 deletion app/help.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
6 changes: 3 additions & 3 deletions f2.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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 {
Expand Down
1 change: 1 addition & 0 deletions find/csv.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ func handleCSV(conf *config.Config) (file.Changes, error) {

continue
}

return nil, statErr
}

Expand Down
5 changes: 3 additions & 2 deletions find/find.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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
}

Expand All @@ -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
}

Expand Down
4 changes: 2 additions & 2 deletions find/find_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)

Expand Down
4 changes: 3 additions & 1 deletion find/find_test/find_csv_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
2 changes: 1 addition & 1 deletion find/find_test/find_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
6 changes: 1 addition & 5 deletions find/find_test/find_unix_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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() {}
}

Expand Down
4 changes: 2 additions & 2 deletions internal/apperr/apperr.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
43 changes: 22 additions & 21 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
Expand All @@ -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
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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))
Expand All @@ -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()
}
}
Expand Down
4 changes: 0 additions & 4 deletions internal/config/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
}
Expand Down
Loading

0 comments on commit 3304f6c

Please sign in to comment.