Skip to content

Commit

Permalink
refactor and update tests
Browse files Browse the repository at this point in the history
  • Loading branch information
ayoisaiah committed Oct 18, 2024
1 parent 861125a commit 6848a37
Show file tree
Hide file tree
Showing 16 changed files with 76 additions and 78 deletions.
16 changes: 6 additions & 10 deletions find/csv.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,17 +53,13 @@ func handleCSV(conf *config.Config) (file.Changes, error) {

source := strings.TrimSpace(record[0])

// Change to the directory of the CSV file
err := os.Chdir(conf.WorkingDir)
if err != nil {
return nil, err
}

absSourcePath, absErr := filepath.Abs(source)
if absErr != nil {
return nil, absErr
}

fileInfo, statErr := os.Stat(absSourcePath)
fileInfo, statErr := os.Stat(source)
if statErr != nil {
// Skip missing source files
if errors.Is(statErr, os.ErrNotExist) {
Expand All @@ -79,15 +75,15 @@ func handleCSV(conf *config.Config) (file.Changes, error) {

fileName := fileInfo.Name()

sourceDir := filepath.Dir(absSourcePath)
sourceDir := filepath.Dir(source)

// Ensure that the file is not already processed in the case of
// duplicate rows
if processed[absSourcePath] {
if processed[source] {
continue
}

processed[absSourcePath] = true
processed[source] = true

match := &file.Change{
BaseDir: sourceDir,
Expand All @@ -96,7 +92,7 @@ func handleCSV(conf *config.Config) (file.Changes, error) {
Source: fileName,
Target: fileName,
OriginalName: fileName,
SourcePath: absSourcePath,
SourcePath: filepath.Join(sourceDir, fileName),
CSVRow: record,
Position: i,
}
Expand Down
25 changes: 17 additions & 8 deletions find/find.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ import (
"path/filepath"
"strings"

"github.com/adrg/xdg"

"github.com/ayoisaiah/f2/internal/config"
"github.com/ayoisaiah/f2/internal/file"
"github.com/ayoisaiah/f2/internal/osutil"
Expand Down Expand Up @@ -237,12 +235,18 @@ func searchPaths(conf *config.Config) (file.Changes, error) {
// from the backup file. It returns the changes or an error if the backup file
// cannot be found or parsed.
func loadFromBackup(conf *config.Config) (file.Changes, error) {
backupFilePath, err := xdg.SearchDataFile(
filepath.Join("f2", "backups", conf.BackupFilename),
backupFilePath := filepath.Join(
os.TempDir(),
"f2",
"backups",
conf.BackupFilename,
)
if err != nil {
//nolint:nilerr // The file does not exist, but it's not an error in this context

_, err := os.Stat(backupFilePath)
if os.IsNotExist(err) {
return nil, nil
} else if err != nil {
return nil, err
}

fileBytes, err := os.ReadFile(backupFilePath)
Expand All @@ -261,9 +265,14 @@ func loadFromBackup(conf *config.Config) (file.Changes, error) {
// Swap source and target for each change to revert the renaming
for i := range changes {
ch := changes[i]
p := filepath.Join(ch.TargetDir, ch.Target)
ch.Target = filepath.Base(p)
ch.TargetDir = filepath.Dir(p)

ch.Source, ch.Target = ch.Target, ch.Source
ch.SourcePath = filepath.Join(ch.TargetDir, ch.Source)
ch.TargetPath = filepath.Join(ch.BaseDir, ch.Target)
ch.BaseDir, ch.TargetDir = ch.TargetDir, ch.BaseDir
ch.SourcePath = filepath.Join(ch.BaseDir, ch.Source)
ch.TargetPath = filepath.Join(ch.TargetDir, ch.Target)
ch.Status = status.OK

_, err := os.Stat(ch.SourcePath)
Expand Down
6 changes: 2 additions & 4 deletions find/find_test/find_csv_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,10 @@ var csvCases = []testutil.TestCase{
},
Args: []string{"--csv", "testdata/input.csv"},
},
// TODO: Add more tests
}

// TestFindCSV tests file matching with CSV files.
// TODO: Test --csv.
func TestFindCSV(t *testing.T) {
_ = csvCases

t.Skip("not implemented")
findTest(t, csvCases, "")
}
8 changes: 4 additions & 4 deletions find/find_test/find_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -238,11 +238,9 @@ var testCases = []testutil.TestCase{
},
}

func findTest(t *testing.T, cases []testutil.TestCase) {
func findTest(t *testing.T, cases []testutil.TestCase, testDir string) {
t.Helper()

testDir := testutil.SetupFileSystem(t, "find", findFileSystem)

for i := range cases {
tc := cases[i]

Expand Down Expand Up @@ -275,7 +273,9 @@ func findTest(t *testing.T, cases []testutil.TestCase) {
// exclude, hidden, include-dir, only-dir, ignore-case, ignore-ext, max-depth,
// recursive, string-mode.
func TestFind(t *testing.T) {
findTest(t, testCases)
testDir := testutil.SetupFileSystem(t, "find", findFileSystem)

findTest(t, testCases, testDir)
}

// TODO: Test reverting from a backup file.
Expand Down
4 changes: 3 additions & 1 deletion find/find_test/find_unix_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,5 +34,7 @@ var unixTestCases = []testutil.TestCase{

// TestFindUnix only tests search behaviors perculiar to Linux and macOS.
func TestFindUnix(t *testing.T) {
findTest(t, unixTestCases)
testDir := testutil.SetupFileSystem(t, "find", findFileSystem)

findTest(t, unixTestCases, testDir)
}
4 changes: 3 additions & 1 deletion find/find_test/find_windows_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,5 +82,7 @@ var windowsTestCases = []testutil.TestCase{

// TestFindWindows only tests search behaviors perculiar to Windows
func TestFindWindows(t *testing.T) {
findTest(t, windowsTestCases)
testDir := testutil.SetupFileSystem(t, "find", findFileSystem)

findTest(t, windowsTestCases, testDir)
}
2 changes: 1 addition & 1 deletion find/find_test/testdata/input.csv
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
Filename,Replacement,Random
a.txt,aa.txt,GPLv3
c.txt,[csv.3}.txt,myname
c.txt,{csv.3}.txt,myname
d.txt,dd.txt,
1 change: 0 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ module github.com/ayoisaiah/f2
go 1.23

require (
github.com/adrg/xdg v0.5.0
github.com/barasher/go-exiftool v1.10.0
github.com/dhowden/tag v0.0.0-20240417053706-3d75831295e8
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51
Expand Down
12 changes: 0 additions & 12 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@ github.com/MarvinJWendt/testza v0.3.0/go.mod h1:eFcL4I0idjtIx8P9C6KkAuLgATNKpX4/
github.com/MarvinJWendt/testza v0.4.2/go.mod h1:mSdhXiKH8sg/gQehJ63bINcCKp7RtYewEjXsvsVUPbE=
github.com/MarvinJWendt/testza v0.5.2 h1:53KDo64C1z/h/d/stCYCPY69bt/OSwjq5KpFNwi+zB4=
github.com/MarvinJWendt/testza v0.5.2/go.mod h1:xu53QFE5sCdjtMCKk8YMQ2MnymimEctc4n3EjyIYvEY=
github.com/adrg/xdg v0.5.0 h1:dDaZvhMXatArP1NPHhnfaQUqWBLBsmx1h1HXQdMoFCY=
github.com/adrg/xdg v0.5.0/go.mod h1:dDdY4M4DF9Rjy4kHPeNL+ilVF+p2lK8IdM9/rTSGcI4=
github.com/araddon/dateparse v0.0.0-20210429162001-6b43995a97de h1:FxWPpzIjnTlhPwqqXc4/vE0f7GvRjuAsbW+HOIe8KnA=
github.com/araddon/dateparse v0.0.0-20210429162001-6b43995a97de/go.mod h1:DCaWoUhZrYW9p1lxo/cm8EmUOOzAPSEZNGF2DK1dJgw=
github.com/atomicgo/cursor v0.0.1/go.mod h1:cBON2QmmrysudxNBFthvMtN32r3jxVRIvzkUiF/RuIk=
Expand All @@ -27,8 +25,6 @@ github.com/barasher/go-exiftool v1.10.0/go.mod h1:F9s/a3uHSM8YniVfwF+sbQUtP8Gmh9
github.com/containerd/console v1.0.3/go.mod h1:7LqA/THxQ86k76b8c/EMSiaJ3h1eZkMkXar0TQ1gf3U=
github.com/containerd/console v1.0.4 h1:F2g4+oChYvBTsASRTz8NP6iIAi97J3TtSAsLbIFn4ro=
github.com/containerd/console v1.0.4/go.mod h1:YynlIjWYF8myEu6sdkwKIvGQq+cOckRm6So2avqoYAk=
github.com/cpuguy83/go-md2man/v2 v2.0.4 h1:wfIWP927BUkWJb2NmU/kNDYIBTh/ziUX91+lVfRxZq4=
github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/cpuguy83/go-md2man/v2 v2.0.5 h1:ZtcqGrnekaHpVLArFSe4HK5DoKx1T0rq2DwVB0alcyc=
github.com/cpuguy83/go-md2man/v2 v2.0.5/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
Expand Down Expand Up @@ -118,8 +114,6 @@ github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1/go.mod h1:Ohn+xnUBi
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/exp v0.0.0-20240823005443-9b4947da3948 h1:kx6Ds3MlpiUHKj7syVnbp57++8WpuKPcR5yjLBjvLEA=
golang.org/x/exp v0.0.0-20240823005443-9b4947da3948/go.mod h1:akd2r19cwCdwSwWeIdzYQGa/EZZyqcOdwWiwj5L5eKQ=
golang.org/x/exp v0.0.0-20240909161429-701f63a606c0 h1:e66Fs6Z+fZTbFBAxKfP3PALWBtpfqks2bwGcexMxgtk=
golang.org/x/exp v0.0.0-20240909161429-701f63a606c0/go.mod h1:2TbTHSBQa924w8M6Xs1QcRcFwyucIwBGpK1p2f1YFFY=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
Expand All @@ -144,26 +138,20 @@ golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg=
golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34=
golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/term v0.23.0 h1:F6D4vR+EHoL9/sWAWgAR1H2DcHr4PareCbAaCo1RpuU=
golang.org/x/term v0.23.0/go.mod h1:DgV24QBUrK6jhZXl+20l6UWznPlwAHm1Q1mGHtydmSk=
golang.org/x/term v0.24.0 h1:Mh5cbb+Zk2hqqXNO7S1iTjEphVL+jb8ZWaqh/g+JWkM=
golang.org/x/term v0.24.0/go.mod h1:lOBK/LVxemqiMij05LGJ0tzNr8xlmwBRJ81PX6wVLH8=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.17.0 h1:XtiM5bkSOt+ewxlOE/aE/AKEHibwj/6gvWMl9Rsh0Qc=
golang.org/x/text v0.17.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
golang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224=
golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
Expand Down
2 changes: 1 addition & 1 deletion internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ type ExiftoolOpts struct {

type Backup struct {
Changes file.Changes `json:"changes"`
CleanedDirs []string `json:"cleaned_dirs"`
CleanedDirs []string `json:"cleaned_dirs,omitempty"`
}

func (b Backup) RenderJSON(w io.Writer) error {
Expand Down
12 changes: 8 additions & 4 deletions rename/backup.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,20 @@ import (
"os"
"path/filepath"

"github.com/adrg/xdg"

"github.com/ayoisaiah/f2/internal/config"
"github.com/ayoisaiah/f2/internal/file"
"github.com/ayoisaiah/f2/internal/osutil"
)

func createBackupFile(fileName string) (io.Writer, error) {
backupFilePath, err := xdg.DataFile(
filepath.Join("f2", "backups", fileName),
backupFilePath := filepath.Join(
os.TempDir(),
"f2",
"backups",
fileName,
)

err := os.MkdirAll(filepath.Dir(backupFilePath), osutil.DirPermission)
if err != nil {
return nil, err
}
Expand Down
49 changes: 23 additions & 26 deletions rename/rename.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@ import (
"strings"
"time"

"github.com/adrg/xdg"

"github.com/ayoisaiah/f2/internal/apperr"
"github.com/ayoisaiah/f2/internal/config"
"github.com/ayoisaiah/f2/internal/file"
Expand All @@ -34,16 +32,16 @@ func commit(fileChanges file.Changes) []int {
var errIndices []int

for i := range fileChanges {
change := fileChanges[i]
ch := fileChanges[i]

if change.Status == status.Ignored {
if ch.Status == status.Ignored {
continue
}

targetPath := change.TargetPath
targetPath := ch.TargetPath

// skip paths that are unchanged in every aspect
if change.SourcePath == targetPath {
if ch.SourcePath == targetPath {
continue
}

Expand All @@ -54,48 +52,48 @@ func commit(fileChanges file.Changes) []int {
// 2. Rename <source> to <target>
// 3. Rename __<time>__<target>__<time>__ to <target>
var isCaseChangeOnly bool // only the target case is changing
if strings.EqualFold(change.SourcePath, targetPath) {
if strings.EqualFold(ch.SourcePath, targetPath) {
isCaseChangeOnly = true
timeStr := fmt.Sprintf("%d", time.Now().UnixNano())
targetPath = filepath.Join(
change.TargetDir,
"__"+timeStr+"__"+change.Target+"__"+timeStr+"__", // step 1
ch.TargetDir,
"__"+timeStr+"__"+ch.Target+"__"+timeStr+"__", // step 1
)
}

// If target contains a slash, create all missing
// directories before renaming the file
if strings.Contains(change.Target, "/") ||
strings.Contains(change.Target, `\`) &&
if strings.Contains(ch.Target, "/") ||
strings.Contains(ch.Target, `\`) &&
runtime.GOOS == osutil.Windows {
// No need to check if the `dir` exists or if there are several
// consecutive slashes since `os.MkdirAll` handles that
dir := filepath.Dir(change.Target)
dir := filepath.Dir(ch.Target)

err := os.MkdirAll(
filepath.Join(change.TargetDir, dir),
filepath.Join(ch.TargetDir, dir),
osutil.DirPermission,
)
if err != nil {
errIndices = append(errIndices, i)
change.Error = err
ch.Error = err

continue
}
}

traversedDirs[change.BaseDir] = change.BaseDir
traversedDirs[ch.BaseDir] = ch.BaseDir

err := os.Rename(change.SourcePath, targetPath) // step 2
err := os.Rename(ch.SourcePath, targetPath) // step 2
// if the intermediate rename is successful,
// proceed with the original renaming operation
if err == nil && isCaseChangeOnly {
err = os.Rename(targetPath, change.TargetPath) // step 3
err = os.Rename(targetPath, ch.TargetPath) // step 3
}

if err != nil {
errIndices = append(errIndices, i)
change.Error = err
ch.Error = err
}
}

Expand Down Expand Up @@ -134,7 +132,7 @@ func PostRename(

var cleanedDirs []string

if conf.Clean {
if conf.Clean && !conf.Revert {
for _, dir := range traversedDirs {
if dir == "." { // don't try to clean the working directory
continue
Expand Down Expand Up @@ -162,15 +160,14 @@ func PostRename(
}

if conf.Revert && renameErr == nil {
backupFilePath, err := xdg.SearchDataFile(
filepath.Join("f2", "backups", conf.BackupFilename),
backupFilePath := filepath.Join(
os.TempDir(),
"f2",
"backups",
conf.BackupFilename,
)
if err != nil {
report.BackupFileRemovalFailed(err)
return
}

if err = os.Remove(backupFilePath); err != nil {
if err := os.Remove(backupFilePath); err != nil {
report.BackupFileRemovalFailed(err)
return
}
Expand Down
2 changes: 1 addition & 1 deletion rename/rename_test/testdata/rename_a_file_backup.golden
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"changes":[{"status":"","base_dir":"","target_dir":"","source":"File.txt","target":"myFile.txt","is_dir":false}],"cleaned_dirs":null}
{"changes":[{"status":"","base_dir":"","target_dir":"","source":"File.txt","target":"myFile.txt","is_dir":false}]}
Loading

0 comments on commit 6848a37

Please sign in to comment.