config.go (1308B)
1 package config 2 3 import ( 4 "flag" 5 "fmt" 6 "os" 7 "time" 8 9 "code.dwrz.net/src/pkg/dqs/entry" 10 ) 11 12 const ( 13 defaultDir = "" 14 dirUsage = "the path to the dqs directory" 15 16 defaultDate = "" 17 dateUsage = "the entry date to use, formatted as YYYYMMDD" 18 ) 19 20 type Config struct { 21 Date time.Time 22 Dir string 23 } 24 25 func Get() (*Config, error) { 26 var ( 27 cfg = &Config{} 28 date string 29 ) 30 31 flag.StringVar(&cfg.Dir, "dir", defaultDir, dirUsage) 32 flag.StringVar(&date, "d", defaultDate, dateUsage) 33 flag.StringVar(&date, "date", defaultDate, dateUsage) 34 35 flag.Parse() 36 37 // If unset, use the default directory. 38 if cfg.Dir == "" { 39 dir, err := DefaultDirectory() 40 if err != nil { 41 return nil, err 42 } 43 44 cfg.Dir = dir 45 } 46 47 // Parse and set the date. 48 // If unset, use the current date. 49 switch date { 50 case defaultDate: 51 now := time.Now() 52 cfg.Date = time.Date( 53 now.Year(), now.Month(), now.Day(), 54 0, 0, 0, 0, time.Local, 55 ) 56 default: 57 var err error 58 cfg.Date, err = time.Parse(entry.DateFormat, date) 59 if err != nil { 60 return nil, fmt.Errorf("invalid date: %w", err) 61 } 62 } 63 64 return cfg, nil 65 } 66 67 func DefaultDirectory() (string, error) { 68 dir, err := os.UserConfigDir() 69 if err != nil { 70 return "", fmt.Errorf( 71 "failed to get user config dir: %w", err, 72 ) 73 } 74 75 return fmt.Sprintf("%s/dqs", dir), nil 76 }