Skip to content

Commit

Permalink
refactor + update tests
Browse files Browse the repository at this point in the history
  • Loading branch information
ayoisaiah committed Aug 24, 2024
1 parent 7b73f9f commit 1dcf7ac
Show file tree
Hide file tree
Showing 35 changed files with 679 additions and 646 deletions.
16 changes: 6 additions & 10 deletions app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ var supportedDefaultOpts = []string{
flagIgnoreCase.Name,
flagIgnoreExt.Name,
flagIncludeDir.Name,
flagInteractive.Name,
flagJSON.Name,
flagMaxDepth.Name,
flagNoColor.Usage,
Expand Down Expand Up @@ -99,12 +98,6 @@ func initPrinter() {
if isOutputToPipe() {
pterm.DisableStyling()
}

pterm.Error.MessageStyle = pterm.NewStyle(pterm.FgRed)
pterm.Error.Prefix = pterm.Prefix{
Text: "ERROR",
Style: pterm.NewStyle(pterm.BgRed, pterm.FgBlack),
}
}

// handlePipeInput processes input from a pipe and appends it to os.Args
Expand Down Expand Up @@ -180,17 +173,22 @@ func Get(reader io.Reader, writer io.Writer) (*cli.App, error) {
app.Before = func(ctx *cli.Context) (err error) {
// print short help and exit if no arguments or flags are present
if ctx.NumFlags() == 0 && !ctx.Args().Present() {
pterm.Fprintln(writer, ShortHelp(ctx.App))
pterm.Fprintln(config.Stderr, ShortHelp(ctx.App))
os.Exit(int(osutil.ExitOK))
}

config.Stdout = ctx.App.Writer
config.Stdin = ctx.App.Reader

defer (func() {
appConfig, initErr := config.Init(ctx)
if initErr != nil && err == nil {
err = initErr
return
}

appConfig.IsOutputToPipe = isOutputToPipe()

slog.Info("configuration loaded", slog.Any("app_config", appConfig))
})()

Expand Down Expand Up @@ -269,11 +267,9 @@ offers several options for fine-grained control over the renaming process.`,
flagIncludeDir,
flagIgnoreCase,
flagIgnoreExt,
flagInteractive,
flagJSON,
flagMaxDepth,
flagNoColor,
flagPrint,
flagOnlyDir,
flagQuiet,
flagRecursive,
Expand Down
9 changes: 8 additions & 1 deletion app/app_test/app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"testing"

"github.com/ayoisaiah/f2/app"
"github.com/ayoisaiah/f2/internal/config"
"github.com/ayoisaiah/f2/internal/testutil"
"github.com/pterm/pterm"
"github.com/urfave/cli/v2"
Expand All @@ -19,7 +20,13 @@ func TestShortHelp(t *testing.T) {

var buf bytes.Buffer

renamer, err := app.Get(os.Stdin, &buf)
config.Stderr = &buf

t.Cleanup(func() {
config.Stderr = os.Stderr
})

renamer, err := app.Get(os.Stdin, os.Stdin)
if err != nil {
t.Fatal(err)
}
Expand Down
12 changes: 3 additions & 9 deletions app/app_test/testdata/help.golden
Original file line number Diff line number Diff line change
Expand Up @@ -118,10 +118,6 @@ OPTIONS
-e, --ignore-ext
Ignores the file extension when searching for matches.

--interactive
Prompts for confirmation before executing the renaming operation after a
dry-run.

--json
Produces JSON output, except for error messages which are sent to the
standard error.
Expand All @@ -132,15 +128,13 @@ OPTIONS
--no-color
Disables colored output.

--print
Prints all renamed paths after successful renaming.

-D, --only-dir
Renames only directories, not files (implies -d/--include-dir).

--quiet
Suppresses all output to the standard output, except for errors which are
sent to the standard error.
Don't print anything to stdout. If no matches are found, f2 will exit with
an error code instead of the normal success code without this flag.
Errors will continue to be written to stderr.

-R, --recursive
Recursively traverses directories when searching for matches.
Expand Down
21 changes: 3 additions & 18 deletions app/flag.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,14 +157,6 @@ var (
Ignores the file extension when searching for matches.`,
}

flagInteractive = &cli.BoolFlag{
Name: "interactive",
Aliases: []string{"n"},
Usage: `
Prompts for confirmation before executing the renaming operation after a
dry-run.`,
}

// TODO: JSON output should also be used for errors?
flagJSON = &cli.BoolFlag{
Name: "json",
Expand All @@ -188,14 +180,6 @@ var (
Disables colored output.`,
}

// TODO: Remove print option. Instead use CLI pipe to detect when renamed paths
// should be printed
flagPrint = &cli.BoolFlag{
Name: "print",
Usage: `
Prints all renamed paths after successful renaming.`,
}

flagOnlyDir = &cli.BoolFlag{
Name: "only-dir",
Aliases: []string{"D"},
Expand All @@ -207,8 +191,9 @@ var (
Name: "quiet",
Aliases: []string{"q"},
Usage: `
Suppresses all output to the standard output, except for errors which are
sent to the standard error.`,
Don't print anything to stdout. If no matches are found, f2 will exit with
an error code instead of the normal success code without this flag.
Errors will continue to be written to stderr.`,
}

flagRecursive = &cli.BoolFlag{
Expand Down
18 changes: 0 additions & 18 deletions app/help.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,12 +118,6 @@ func helpText(app *cli.App) string {
flagIgnoreExt.GetUsage(),
)

flagInteractiveHelp := fmt.Sprintf(
`%s %s`,
pterm.Green("--", flagInteractive.Name),
flagInteractive.GetUsage(),
)

flagJSONHelp := fmt.Sprintf(
`%s %s`,
pterm.Green("--", flagJSON.Name),
Expand All @@ -143,12 +137,6 @@ func helpText(app *cli.App) string {
flagNoColor.GetUsage(),
)

flagPrintHelp := fmt.Sprintf(
`%s %s`,
pterm.Green("--", flagPrint.Name),
flagPrint.GetUsage(),
)

flagOnlyDirHelp := fmt.Sprintf(
`%s, %s %s`,
pterm.Green("-", flagOnlyDir.Aliases[0]),
Expand Down Expand Up @@ -299,10 +287,6 @@ Project repository: https://github.com/ayoisaiah/f2
%s
%s
%s
%s
%s
Expand Down Expand Up @@ -336,11 +320,9 @@ Project repository: https://github.com/ayoisaiah/f2
flagIncludeDirHelp,
flagIgnoreCaseHelp,
flagIgnoreExtHelp,
flagInteractiveHelp,
flagJSONHelp,
flagMaxDepthHelp,
flagNoColorHelp,
flagPrintHelp,
flagOnlyDirHelp,
flagQuietHelp,
flagRecursiveHelp,
Expand Down
61 changes: 17 additions & 44 deletions f2.go
Original file line number Diff line number Diff line change
@@ -1,95 +1,68 @@
package f2

import (
"errors"
"fmt"
"io"
"log/slog"
"os"

"github.com/urfave/cli/v2"

"github.com/ayoisaiah/f2/app"
"github.com/ayoisaiah/f2/find"
"github.com/ayoisaiah/f2/internal/apperr"
"github.com/ayoisaiah/f2/internal/config"
"github.com/ayoisaiah/f2/rename"
"github.com/ayoisaiah/f2/replace"
"github.com/ayoisaiah/f2/report"
"github.com/ayoisaiah/f2/validate"
)

var errConflictDetected = errors.New(
"resolve conflicts before proceeding or use -F/--fix-conflicts to auto-fix",
)
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 {
appConfig := config.Get()

report.Stdout = ctx.App.Writer
report.Stderr = os.Stderr

if appConfig.Revert {
return rename.Undo(appConfig)
}

findMatches, err := find.Find(appConfig)
changes, err := find.Find(appConfig)
if err != nil {
return err
}

if len(findMatches) == 0 {
slog.Info("find matches completed: no matches found")
report.NoMatches(appConfig.JSON)
if len(changes) == 0 {
report.NoMatches(appConfig)

return nil
}

slog.Info(
fmt.Sprintf(
"find matches completed: found %d matches",
len(findMatches),
),
slog.Any("find_matches", findMatches),
slog.Int("num_matches", len(findMatches)),
)

changes, err := replace.Replace(appConfig, findMatches)
if err != nil {
return err
if !appConfig.Revert {
changes, err = replace.Replace(appConfig, changes)
if err != nil {
return err
}
}

slog.Info("bulk renaming completed", slog.Any("changes", changes))

hasConflicts := validate.Validate(
changes,
appConfig.AutoFixConflicts,
appConfig.AllowOverwrites,
)

if hasConflicts {
report.NonInteractive(changes, hasConflicts)
report.Report(appConfig, changes, hasConflicts)

return errConflictDetected
}

if !appConfig.Exec {
report.Report(appConfig, changes)
report.Report(appConfig, changes, hasConflicts)
return nil
}

err = rename.Rename(appConfig, changes)
if err != nil {
return err
}
err = rename.Rename(changes)

if appConfig.Print {
for i := range changes {
fmt.Println(changes[i].RelTargetPath)
}
}
rename.PostRename(appConfig, changes)

return nil
return err
}

// New creates a new CLI application for f2
Expand Down
4 changes: 2 additions & 2 deletions find/csv.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,10 @@ func readCSVFile(pathToCSV string) ([][]string, error) {

// handleCSV reads the provided CSV file, and finds all the valid candidates
// for renaming.
func handleCSV(conf *config.Config) ([]*file.Change, error) {
func handleCSV(conf *config.Config) (file.Changes, error) {
processed := make(map[string]bool)

var changes []*file.Change
var changes file.Changes

records, err := readCSVFile(conf.CSVFilename)
if err != nil {
Expand Down
Loading

0 comments on commit 1dcf7ac

Please sign in to comment.