aboutsummaryrefslogtreecommitdiffstats
path: root/internal/config/config.go
blob: 89acd23d50ae660092d91a602ad6a7e0754ff6a0 (plain) (blame)
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
75
76
77
78
79
80
81
82
package config

import (
	"errors"
	"fmt"
	"os"
	"path/filepath"

	"github.com/BurntSushi/toml"
)

const configFileName = "bolt.toml"

var config *Config

type Config struct {
	// Relative file path from the bolt configuration file.
	// This is optional and will default to "migrations" if
	// not specified.
	MigrationsDir string `toml:"migrations_dir"`

	// Information related to how to connect to the database
	// that is desired to run migrations against.
	Connection connectionConfig
}

type connectionConfig struct {
	Host     string
	Port     int
	User     string
	Password string
	DBName   string
	Driver   string
}

func NewConfig() (*Config, error) {
	if config == nil {
		filePath, err := findConfigFilePath()
		if err != nil {
			return nil, err
		}

		config = &Config{}
		_, err = toml.DecodeFile(filePath, &config)
		if err != nil {
			return nil, err
		}
	}

	return config, nil
}

func findConfigFilePath() (filePath string, err error) {
	dir, err := os.Getwd()
	if err != nil {
		return "", err
	}

	for {
		entries, err := os.ReadDir(dir)
		if err != nil {
			return "", err
		}

		for _, e := range entries {
			if e.Name() == configFileName {
				return filepath.Join(dir, e.Name()), nil
			}
		}

		// TODO: This won't support Windows.
		if dir == "/" {
			errMsg := fmt.Sprintf(
				"%s not found in current directory or any parent directories.",
				configFileName,
			)
			return "", errors.New(errMsg)
		}

		dir = filepath.Dir(dir)
	}
}