josie / simplegit

// Package config loads simplegit's runtime settings from a TOML file.
package config

import (
	"errors"
	"fmt"
	"io/fs"

	"github.com/BurntSushi/toml"
)

// Config holds the settings needed to run the server.
type Config struct {
	// DataDir is the root for runtime state: bare repos, the SQLite
	// database, and uploads.
	DataDir string `toml:"data_dir"`
	// ListenAddr is the address the HTTP server binds. TLS is terminated
	// by the reverse proxy, so this is plain HTTP.
	ListenAddr string `toml:"listen_addr"`
	// BaseURL is the public URL, used to build clone URLs and links.
	BaseURL string `toml:"base_url"`
}

// Default returns the built-in configuration, used when no file is present.
// Listen on loopback: the server speaks plain HTTP and must not be
// reachable by anything that can see a public interface.
func Default() Config {
	return Config{
		DataDir:    "data",
		ListenAddr: "127.0.0.1:8080",
		BaseURL:    "http://localhost:8080",
	}
}

// Load reads path on top of the defaults. A missing file is not an error:
// the defaults are returned so the binary runs out of the box.
func Load(path string) (Config, error) {
	cfg := Default()
	if path == "" {
		return cfg, nil
	}
	if _, err := toml.DecodeFile(path, &cfg); err != nil {
		if errors.Is(err, fs.ErrNotExist) {
			return cfg, nil
		}
		return Config{}, fmt.Errorf("load config %s: %w", path, err)
	}
	return cfg, nil
}