/
file.go
64 lines (59 loc) · 1.59 KB
/
file.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
package configs
import (
"github.com/pkg/errors"
"github.com/statping/statping/utils"
"os"
"path/filepath"
"strings"
)
var log = utils.Log.WithField("type", "configs")
// ConnectConfigs will connect to the database and save the config.yml file
func ConnectConfigs(configs *DbConfig, retry bool) error {
err := Connect(configs, retry)
if err != nil {
return errors.Wrap(err, "error connecting to database")
}
if err := configs.Save(utils.Directory); err != nil {
return errors.Wrap(err, "error saving configuration")
}
return nil
}
// findDbFile will attempt to find the "statping.db" database file in the current
// working directory, or from STATPING_DIR env.
func findDbFile(configs *DbConfig) (string, error) {
location := utils.Directory + "/" + SqliteFilename
if configs == nil {
file, err := findSQLin(utils.Directory)
if err != nil {
log.Errorln(err)
return location, nil
}
location = file
}
if configs != nil && configs.SqlFile != "" {
return configs.SqlFile, nil
}
return location, nil
}
// findSQLin walks the current walking directory for statping.db
func findSQLin(path string) (string, error) {
filename := SqliteFilename
var found []string
err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
return nil
}
if filepath.Ext(path) == ".db" {
filename = info.Name()
found = append(found, filename)
}
return nil
})
if err != nil {
return filename, err
}
if len(found) > 1 {
return filename, errors.Errorf("found multiple database files: %s", strings.Join(found, ", "))
}
return filename, nil
}