Skip to content

Commit

Permalink
feat: file utils
Browse files Browse the repository at this point in the history
  • Loading branch information
OnlyPiglet committed Nov 28, 2024
1 parent 0e436d4 commit e765475
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 0 deletions.
54 changes: 54 additions & 0 deletions filetools/filetools.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package filetools

import (
"fmt"
"os"
"sort"
"time"
)

type FileInfo struct {
ModTime time.Time
FileName string
}

func RecentFileMaxKept(dir string, maxKept int) error {

rd, err := os.ReadDir(dir)
if err != nil {
return err
}

all := make([]FileInfo, 0)

for _, entry := range rd {
if entry.IsDir() {
continue
}
info, err := entry.Info()
if err != nil {
return err
}
all = append(all, FileInfo{
ModTime: info.ModTime(),
FileName: info.Name(),
})
}

sort.Slice(all, func(i, j int) bool {
return all[i].ModTime.Before(all[j].ModTime)
})

for i, fi := range all {
if i < maxKept {
continue
}
fn := fmt.Sprintf("%s%s%s", dir, string(os.PathSeparator), fi.FileName)
err := os.Remove(fn)
if err != nil {
return err
}
}

return nil
}
10 changes: 10 additions & 0 deletions filetools/filetools_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package filetools

import "testing"

func TestMaxKept(t *testing.T) {
err := RecentFileMaxKept("./test", 2)
if err != nil {
t.Fatal(err)
}
}
Empty file added filetools/test/1
Empty file.
Empty file added filetools/test/2
Empty file.

0 comments on commit e765475

Please sign in to comment.