files
simple_backup/internal/path/path.go
2025-08-01 13:57:02 +09:00

79 lines
2.0 KiB
Go

package path
import (
"fmt"
"os"
"sync"
"time"
"git.lhk.o-r.kr/freerer2/simple_backup/internal/constants"
)
// GetGroupByFolder generates a simple_backup path based on the groupBy option and time.
// If groupBy is invalid or empty, it returns the basePath unchanged.
//
// Parameters:
// - basePath: the base directory path for simple_backup
// - groupBy: grouping option (year, mon, day, hour, min, sec)
// - t: time to use for path generation
//
// Returns:
// - string: generated path based on groupBy option
func GetGroupByFolder(basePath, groupBy string, t time.Time) string {
switch groupBy {
case constants.GroupByYear:
return fmt.Sprintf("%s/%d", basePath, t.Year())
case constants.GroupByMonth:
return fmt.Sprintf("%s/%d%02d", basePath, t.Year(), t.Month())
case constants.GroupByDay:
return fmt.Sprintf("%s/%d%02d%02d", basePath, t.Year(), t.Month(), t.Day())
case constants.GroupByHour:
return fmt.Sprintf("%s/%d%02d%02d_%02d", basePath, t.Year(), t.Month(), t.Day(), t.Hour())
case constants.GroupByMin:
return fmt.Sprintf("%s/%d%02d%02d_%02d%02d", basePath, t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute())
case constants.GroupBySec:
return fmt.Sprintf("%s/%d%02d%02d_%02d%02d%02d", basePath, t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second())
case "":
return basePath
default:
fmt.Printf("지원하지 않는 group-by 옵션입니다: %s\n", groupBy)
return basePath
}
}
// 디렉토리 캐시
type DirCache struct {
sync.RWMutex
exists map[string]bool
}
func NewDirCache() *DirCache {
return &DirCache{
exists: make(map[string]bool),
}
}
func (c *DirCache) EnsureDir(path string) error {
c.RLock()
if c.exists[path] {
c.RUnlock()
return nil
}
c.RUnlock()
c.Lock()
defer c.Unlock()
// 다시 확인 (다른 고루틴이 생성했을 수 있음)
if c.exists[path] {
return nil
}
if err := os.MkdirAll(path, constants.DefaultFileMode); err != nil {
return err
}
c.exists[path] = true
return nil
}