Skip to content

Commit

Permalink
util: use slices for walkdirexcluded
Browse files Browse the repository at this point in the history
  • Loading branch information
apprehensions committed Oct 22, 2023
1 parent 1463d85 commit 0b43ad5
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 31 deletions.
5 changes: 2 additions & 3 deletions internal/config/state/cleaners.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package state
import (
"log"
"os"
"path/filepath"

"github.com/vinegarhq/vinegar/internal/dirs"
"github.com/vinegarhq/vinegar/util"
Expand All @@ -19,7 +18,7 @@ func CleanPackages() error {

return util.WalkDirExcluded(dirs.Downloads, pkgs, func(path string) error {
log.Printf("Removing unused package %s", path)
return os.Remove(filepath.Join(dirs.Downloads, path))
return os.Remove(path)
})
}

Expand All @@ -33,6 +32,6 @@ func CleanVersions() error {

return util.WalkDirExcluded(dirs.Versions, vers, func(path string) error {
log.Printf("Removing unused version directory %s", path)
return os.RemoveAll(filepath.Join(dirs.Versions, path))
return os.RemoveAll(path)
})
}
34 changes: 6 additions & 28 deletions util/paths.go
Original file line number Diff line number Diff line change
@@ -1,50 +1,28 @@
package util

import (
"io/fs"
"os"
"path/filepath"
"time"
"slices"
)

// WalkDirExcluded will walk the file tree located at dir, calling
// onExcluded for every file or directory that does not have a name in included.
func WalkDirExcluded(dir string, included []string, onExcluded func(string) error) error {
files, err := os.ReadDir(dir)
if err != nil {
return err
}

find:
for _, file := range files {
for _, inc := range included {
if file.Name() == inc {
continue find
}
if slices.Contains(included, file.Name()) {
continue
}

if err := onExcluded(file.Name()); err != nil {
if err := onExcluded(filepath.Join(dir, file.Name())); err != nil {
return err
}
}

return nil
}

func FindTimeFile(dir string, comparison *time.Time) (string, error) {
var name string

err := filepath.Walk(dir, func(p string, i fs.FileInfo, err error) error {
if i.ModTime().After(*comparison) {
name = p
}
return nil
})
if err != nil {
return "", err
}

if name == "" {
return "", os.ErrNotExist
}

return name, nil
}

0 comments on commit 0b43ad5

Please sign in to comment.