~hristoast/mousikofidi

020638625f5b53925330aef6859c208adb757797 — Hristos N. Triantafillou a month ago a5bab91
Create a config file if it doesn't exist
1 files changed, 39 insertions(+), 13 deletions(-)

M cfg/main.go
M cfg/main.go => cfg/main.go +39 -13
@@ 3,25 3,28 @@ package cfg

import (
	"errors"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/BurntSushi/toml"
)

//TODO: log level option
const defaultCfg string = `#
# Generated on: %s
var defaultCfg string = `#
# Generated at: %s
#

title = "MousikóFídi Server Configuration"
version = "1"

[library]
dirs = [
  "%s",
  "%s/music",
  "%s/video",
]

[player]


@@ 46,7 49,7 @@ show_errors = true
site_name = "MousikóFídi - Your Music Cloud"
theme = "light"
`

var defaultCfgPath string = filepath.Join(CfgDir(), "fidi.toml")
var Version string = "0.0.0"

type Config struct {


@@ 84,6 87,7 @@ func (c *Config) Validate() []error {

type tomlCfg struct {
	Title
	Version   CfgVersion
	Library   library
	Player    player
	Playlists playlists


@@ 92,6 96,7 @@ type tomlCfg struct {
}

type Title string
type CfgVersion string

type library struct {
	Dirs []string


@@ 128,21 133,42 @@ func CfgDir() string {
}

func Read() (*Config, error) {
	// cfgPath := filepath.Join(CfgDir(), "fidi.toml")
	//TODO:
	//check cfgDir exists, create if not
	//check cfgPath exists, write default if not
	defaultDir := CfgDir()
	info, err := os.Stat(defaultDir)
	if err != nil {
		log.Printf("creating dir path %s...", defaultDir)
		err = os.MkdirAll(defaultDir, 0755)
		if err != nil {
			return nil, err
		}
	}

	if info != nil && !info.IsDir() {
		return nil, fmt.Errorf("%s exists but is not a directory", CfgDir())
	}

	info, err = os.Stat(defaultCfgPath)
	if err != nil {
		log.Printf("creating default cfg: %s...", defaultCfgPath)
		home := os.Getenv("HOME")
		now := time.Now().Format("2006-01-02 15:04:05")
		cfgData := fmt.Sprintf(defaultCfg, now, home, home, home)
		err = os.WriteFile(defaultCfgPath, []byte(cfgData), 0644)
		if err != nil {
			return nil, err
		}
	}

	if info != nil && info.IsDir() {
		return nil, fmt.Errorf("%s exists but is a directory", defaultCfgPath)
	}

	var c tomlCfg
	md, err := toml.DecodeFile("fidi.toml", &c)
	md, err := toml.DecodeFile(defaultCfgPath, &c)
	if err != nil {
		return nil, err
	}

	// os.Stdout.WriteString("\n")
	// os.Stdout.WriteString(fmt.Sprintf("%#v\n", c))
	// os.Stdout.WriteString("\n")

	conf := &Config{
		AllowDelete:  true,
		AllowSave:    true,