github.com/driusan/bug@v0.3.2-0.20190306121946-d7f4e7f33fea/bugs/Directory.go (about) 1 package bugs 2 3 import ( 4 "os" 5 "regexp" 6 "strings" 7 "time" 8 ) 9 10 func GetRootDir() Directory { 11 dir := os.Getenv("PMIT") 12 if dir != "" { 13 return Directory(dir) 14 } 15 16 wd, _ := os.Getwd() 17 18 if dirinfo, err := os.Stat(wd + "/issues"); err == nil && dirinfo.IsDir() { 19 return Directory(wd) 20 } 21 22 // There's no environment variable and no issues 23 // directory, so walk up the tree until we find one 24 pieces := strings.Split(wd, "/") 25 26 for i := len(pieces); i > 0; i -= 1 { 27 dir := strings.Join(pieces[0:i], "/") 28 if dirinfo, err := os.Stat(dir + "/issues"); err == nil && dirinfo.IsDir() { 29 return Directory(dir) 30 } 31 } 32 return "" 33 } 34 35 func GetIssuesDir() Directory { 36 root := GetRootDir() 37 if root == "" { 38 return root 39 } 40 return GetRootDir() + "/issues/" 41 } 42 43 type Directory string 44 45 func (d Directory) GetShortName() Directory { 46 pieces := strings.Split(string(d), "/") 47 return Directory(pieces[len(pieces)-1]) 48 } 49 50 func (d Directory) ToTitle() string { 51 multidash := regexp.MustCompile("([_]*)-([-_]*)") 52 dashReplacement := strings.Replace(string(d), " ", "/", -1) 53 return multidash.ReplaceAllStringFunc(dashReplacement, func(match string) string { 54 if match == "-" { 55 return " " 56 } 57 if strings.Count(match, "_") == 0 { 58 return match[1:] 59 } 60 return strings.Replace(match, "_", " ", -1) 61 }) 62 } 63 64 func (d Directory) LastModified() time.Time { 65 var t time.Time 66 stat, err := os.Stat(string(d)) 67 if err != nil { 68 panic("Directory " + string(d) + " is not a directory.") 69 } 70 71 if stat.IsDir() == false { 72 return stat.ModTime() 73 } 74 75 dir, _ := os.Open(string(d)) 76 files, _ := dir.Readdir(-1) 77 if len(files) == 0 { 78 t = stat.ModTime() 79 } 80 for _, file := range files { 81 if file.IsDir() { 82 mtime := (d + "/" + Directory(file.Name())).LastModified() 83 if mtime.After(t) { 84 t = mtime 85 } 86 } else { 87 mtime := file.ModTime() 88 if mtime.After(t) { 89 t = mtime 90 } 91 92 } 93 } 94 return t 95 }