file_name_util.go 1.3 KB

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