-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathdb.go
74 lines (58 loc) · 1.11 KB
/
db.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main
import (
"errors"
"os"
"path"
)
var errIsNotAFile = errors.New("the database path is not a file")
var errLocalDbFileNotFound = errors.New("the local .todos file was not found")
var cachedDBPath = ""
func getDBPath() string {
if cachedDBPath != "" {
return cachedDBPath
}
dbPath, err := calculateDBPath()
if err != nil {
return ""
}
cachedDBPath = dbPath
return dbPath
}
func calculateDBPath() (string, error) {
dbPath, err := tryCwdAndParentFolders()
if err != nil {
dbPath, err = tryEnv()
}
return dbPath, err
}
func tryDir(dir string) (string, error) {
dbPath := path.Join(dir, ".todos")
fi, err := os.Stat(dbPath)
if err != nil {
return "", err
}
if fi.IsDir() {
return "", errIsNotAFile
}
return dbPath, nil
}
func tryCwdAndParentFolders() (string, error) {
cwd, err := os.Getwd()
if err != nil {
return "", err
}
for {
filePath, err := tryDir(cwd)
if err == nil {
return filePath, err
}
if len(cwd) == 1 {
break
}
cwd = path.Dir(cwd)
}
return "", errLocalDbFileNotFound
}
func tryEnv() (string, error) {
return os.Getenv("TODO_DB_PATH"), nil
}