-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
0e436d4
commit e765475
Showing
4 changed files
with
64 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.
Empty file.