file_name_util.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334
  1. package util
  2. import (
  3. "log"
  4. "regexp"
  5. "strconv"
  6. "time"
  7. )
  8. const FileNameFormatStr = "2006-01-02-15-04"
  9. // FileNameBeforeDays 查找文件名中有多少在指定天数之前的
  10. func FileNameBeforeDays(days int, fileNames []string, projectName string) []string {
  11. oldFiles := make([]string, 0)
  12. // 2006-01-02-15-04
  13. fileRegxp := regexp.MustCompile(`([\d]{4})-([\d]{2})-([\d]{2})-([\d]{2})-([\d]{2})`)
  14. subDuration, _ := time.ParseDuration("-" + strconv.Itoa(days*24) + "h")
  15. before := time.Now().Add(subDuration)
  16. for i := 0; i < len(fileNames); i++ {
  17. dateString := fileRegxp.FindString(fileNames[i])
  18. if dateString != "" {
  19. if fileTime, err := time.Parse(FileNameFormatStr, dateString); err == nil && fileTime.Before(before) {
  20. oldFiles = append(oldFiles, fileNames[i])
  21. }
  22. }
  23. }
  24. // 待删除的过期文件为所有的文件,将不会进行删除
  25. if len(oldFiles)-len(fileNames) >= 0 {
  26. log.Printf("项目 %s 待删除的过期文件为所有的文件,将不会进行删除!\n", projectName)
  27. return []string{}
  28. }
  29. return oldFiles
  30. }