|
| 1 | +// This code is adapted from https://github.com/boltdb/bolt/blob/master/cmd/bolt/main.go |
| 2 | +// which is licensed under the MIT License |
| 3 | + |
| 4 | +package bolthelper |
| 5 | + |
| 6 | +import ( |
| 7 | + "os" |
| 8 | + "path/filepath" |
| 9 | + "strings" |
| 10 | + "time" |
| 11 | + |
| 12 | + "github.com/pkg/errors" |
| 13 | + bolt "go.etcd.io/bbolt" |
| 14 | +) |
| 15 | + |
| 16 | +const ( |
| 17 | + dbOpenTimeout = 2 * time.Minute |
| 18 | +) |
| 19 | + |
| 20 | +// New returns an instance of the persistent BoltDB store |
| 21 | +func New(path string) (*bolt.DB, error) { |
| 22 | + dirPath := filepath.Dir(path) |
| 23 | + if _, err := os.Stat(dirPath); os.IsNotExist(err) { |
| 24 | + err = os.MkdirAll(dirPath, 0700) |
| 25 | + if err != nil { |
| 26 | + return nil, errors.Wrapf(err, "Error creating db path %v", dirPath) |
| 27 | + } |
| 28 | + } else if err != nil { |
| 29 | + return nil, err |
| 30 | + } |
| 31 | + options := *bolt.DefaultOptions |
| 32 | + options.FreelistType = bolt.FreelistMapType |
| 33 | + options.Timeout = dbOpenTimeout |
| 34 | + db, err := bolt.Open(path, 0600, &options) |
| 35 | + if err != nil { |
| 36 | + return nil, err |
| 37 | + } |
| 38 | + |
| 39 | + return db, nil |
| 40 | +} |
| 41 | + |
| 42 | +// NewTemp creates a new DB, but places it in the host temporary directory. |
| 43 | +func NewTemp(dbPath string) (*bolt.DB, error) { |
| 44 | + tmpDir, err := os.MkdirTemp("", "") |
| 45 | + if err != nil { |
| 46 | + return nil, err |
| 47 | + } |
| 48 | + return New(filepath.Join(tmpDir, strings.Replace(dbPath, "/", "_", -1))) |
| 49 | +} |
0 commit comments