github.com/v2pro/plz@v0.0.0-20221028024117-e5f9aec5b631/countlog/output/rotation/name_by_time.go (about) 1 package rotation 2 3 import ( 4 "os" 5 "time" 6 "path" 7 "sort" 8 "github.com/v2pro/plz/clock" 9 ) 10 11 type NameByTime struct { 12 Directory string 13 Pattern string 14 } 15 16 func (namer *NameByTime) NextFile() (string, error) { 17 now := clock.Now() 18 return path.Join(namer.Directory, now.Format(namer.Pattern)), nil 19 } 20 21 func (namer *NameByTime) ListFiles() ([]Archive, error) { 22 dir, err := os.Open(namer.Directory) 23 if err != nil { 24 return nil, err 25 } 26 names, err := dir.Readdirnames(0) 27 if err != nil { 28 return nil, err 29 } 30 var timedFiles timedFiles 31 for _, name := range names { 32 fileTime, err := time.Parse(namer.Pattern, name) 33 if err != nil { 34 continue 35 } 36 timedFiles = append(timedFiles, timedFile{ 37 file: path.Join(namer.Directory, name), 38 time: fileTime, 39 }) 40 } 41 sort.Sort(timedFiles) 42 archives := make([]Archive, len(timedFiles)) 43 for i, timedFile := range timedFiles { 44 stat, err := os.Stat(timedFile.file) 45 if err != nil { 46 return nil, err 47 } 48 archives[i] = Archive{ 49 Path: timedFile.file, 50 ArchivedAt: timedFile.time, 51 Size: stat.Size(), 52 } 53 } 54 return archives, nil 55 } 56 57 type timedFile struct { 58 file string 59 time time.Time 60 } 61 62 type timedFiles []timedFile 63 64 func (a timedFiles) Len() int { return len(a) } 65 func (a timedFiles) Swap(i, j int) { a[i], a[j] = a[j], a[i] } 66 func (a timedFiles) Less(i, j int) bool { return a[i].time.Before(a[j].time) }