config.go

 1package config
 2
 3import (
 4	"log"
 5	"path/filepath"
 6
 7	"github.com/meowgorithm/babyenv"
 8)
 9
10// Callbacks provides an interface that can be used to run callbacks on different events.
11type Callbacks interface {
12	Tui(action string)
13	Push(repo string)
14	Fetch(repo string)
15}
16
17// Config is the configuration for Soft Serve.
18type Config struct {
19	Host            string `env:"SOFT_SERVE_HOST"`
20	Port            int    `env:"SOFT_SERVE_PORT"`
21	KeyPath         string `env:"SOFT_SERVE_KEY_PATH"`
22	RepoPath        string `env:"SOFT_SERVE_REPO_PATH"`
23	InitialAdminKey string `env:"SOFT_SERVE_INITIAL_ADMIN_KEY"`
24	Callbacks       Callbacks
25}
26
27func (c *Config) applyDefaults() {
28	if c.Port == 0 {
29		c.Port = 23231
30	}
31	if c.KeyPath == "" {
32		// NB: cross-platform-compatible path
33		c.KeyPath = filepath.Join(".ssh", "soft_serve_server_ed25519")
34	}
35	if c.RepoPath == "" {
36		c.RepoPath = ".repos"
37	}
38}
39
40// DefaultConfig returns a Config with the values populated with the defaults
41// or specified environment variables.
42func DefaultConfig() *Config {
43	var scfg Config
44	err := babyenv.Parse(&scfg)
45	if err != nil {
46		log.Fatalln(err)
47	}
48	scfg.applyDefaults()
49	return scfg.WithCallbacks(nil)
50}
51
52// WithCallbacks applies the given Callbacks to the configuration.
53func (cfg *Config) WithCallbacks(c Callbacks) *Config {
54	cfg.Callbacks = c
55	return cfg
56}