main.go (1416B)
1 package main 2 3 import ( 4 "flag" 5 "fmt" 6 "os" 7 "time" 8 ) 9 10 var ( 11 now = time.Now() 12 13 year = flag.Int( 14 "y", 0, 15 "year; defaults to current year", 16 ) 17 month = flag.Int( 18 "m", 0, 19 "month; defaults to current month", 20 ) 21 22 ym = flag.Bool("ym", false, "create YY-MM directories") 23 ) 24 25 // TODO: path arguments. 26 func main() { 27 flag.Parse() 28 29 if *year < 0 { 30 fmt.Fprintf(os.Stderr, "invalid year: %d\n", *year) 31 return 32 } 33 if *year == 0 { 34 y := now.Year() 35 year = &y 36 } 37 38 // Create YY-MM directories. 39 if *ym { 40 mkdirYM(*year) 41 return 42 } 43 44 // Otherwise, create YYYY-MM-DD directories. 45 if *month < 0 || *month > 12 { 46 fmt.Fprintf(os.Stderr, "invalid month: %d\n", month) 47 return 48 } 49 if *month == 0 { 50 m := int(now.Month()) 51 month = &m 52 } 53 54 mkdirYMD(*year, *month) 55 } 56 57 func mkdirYM(year int) { 58 for m := 1; m <= 12; m++ { 59 name := fmt.Sprintf("%d-%02d", year, m) 60 if err := os.Mkdir(name, os.ModePerm); err != nil { 61 fmt.Fprintf(os.Stderr, "%v\n", err) 62 } 63 } 64 } 65 66 func mkdirYMD(year, month int) { 67 // Calculate the last day of the month in the input year. 68 last := time.Date( 69 year, time.Month(month), 1, 0, 0, 0, 0, time.Local, 70 ).AddDate(0, 1, 0).Add(-time.Nanosecond).Day() 71 72 // Create directories for each day of the month. 73 for d := 1; d <= last; d++ { 74 name := fmt.Sprintf("%d-%02d-%02d", year, month, d) 75 if err := os.Mkdir(name, os.ModePerm); err != nil { 76 fmt.Fprintf(os.Stderr, "%v\n", err) 77 } 78 } 79 }