Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions find_replace.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,17 @@ func main() {
// clean success, 1 if argument parsing failed or any traversal error was
// recorded. Output documented in the README (Renaming/Rewriting lines) still
// goes to log.Default(); usage and aggregated error summaries go to stderr.

func validateFindReplace(find, replace string) error {
if find == "" {
return fmt.Errorf("FIND must not be empty")
}
if find == replace {
return fmt.Errorf("FIND and REPLACE must be different")
}
return nil
}

func run(args []string, stderr io.Writer) int {
// Remove date/time from logging output.
log.SetFlags(0)
Expand All @@ -82,6 +93,11 @@ func run(args []string, stderr io.Writer) int {
return 1
}

if err := validateFindReplace(args[1], args[2]); err != nil {
fmt.Fprintln(stderr, err)
return 1
}

fr := findReplace{find: args[1], replace: args[2]}

// Recursively explore the hierarchy depth first, rewrite files as needed,
Expand Down
24 changes: 24 additions & 0 deletions find_replace_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package main
import (
"bytes"
"errors"
"io"
"io/fs"
"os"
"os/exec"
Expand Down Expand Up @@ -660,6 +661,29 @@ func withWorkingDir(t *testing.T, dir string) {
t.Cleanup(func() { _ = os.Chdir(prev) })
}


Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Run gofmt on the added test file

The repo instructions require gofmt -l . to print nothing, but gofmt -l find_replace_test.go reports this file because of this extra blank line before the new test. Please run gofmt so the required formatting check passes.

Useful? React with 👍 / 👎.

func TestValidateFindReplace(t *testing.T) {
cases := []struct {
find, replace string
wantErr bool
}{
{"", "b", true},
{"a", "a", true},
{"a", "b", false},
}
for _, tc := range cases {
if err := validateFindReplace(tc.find, tc.replace); (err != nil) != tc.wantErr {
t.Fatalf("validateFindReplace(%q,%q) err=%v; wantErr=%v", tc.find, tc.replace, err, tc.wantErr)
}
}
}

func TestRunRejectsEmptyFind(t *testing.T) {
if code := run([]string{"find-replace", "", "b"}, io.Discard); code == 0 {
t.Fatal("expected non-zero exit for empty FIND")
}
}

func CloneRepoToTestDir(b *testing.B, repoUrl string) *File {
b.Helper()
d := newTestDir(b, "", "*")
Expand Down