~adnano/astronaut

ffeb31425dcbb40f6c5cfecadd2fcdd211661ac4 — Adnan Maolood 6 months ago 65d507f 0.1.2
Embed default configuration files
2 files changed, 15 insertions(+), 34 deletions(-)

M Makefile
M main.go
M Makefile => Makefile +1 -3
@@ 13,9 13,7 @@ GOFLAGS=
all: astronaut docs

astronaut:
	$(GO) build $(GOFLAGS) \
		-ldflags "-X main.ShareDir=$(SHAREDIR)" \
		-o $@
	$(GO) build $(GOFLAGS) -o $@

docs: docs/astronaut.1


M main.go => main.go +14 -31
@@ 3,6 3,7 @@ package main
import (
	"astronaut/styles"
	"astronaut/ui"
	"embed"
	"errors"
	"flag"
	"fmt"


@@ 10,6 11,7 @@ import (
	"io/fs"
	"log"
	"os"
	"path"
	"path/filepath"
	"time"



@@ 17,9 19,8 @@ import (
	"git.sr.ht/~emersion/go-scfg"
)

var (
	ShareDir string
)
//go:embed config/*
var embedFS embed.FS

func main() {
	flag := flag.NewFlagSet("", flag.ExitOnError)


@@ 43,10 44,10 @@ func run(url string) error {
	configHome := filepath.Join(xdg.ConfigHome(), "astronaut")

	config := &Config{Binds: Binds{}}
	if err := parseConfig("astronaut.conf", configHome, ShareDir, config.Parse); err != nil {
	if err := parseConfig(configHome, "astronaut.conf", config.Parse); err != nil {
		return err
	}
	if err := parseConfig("style.conf", configHome, ShareDir, styles.Parse); err != nil {
	if err := parseConfig(configHome, "style.conf", styles.Parse); err != nil {
		return err
	}



@@ 86,39 87,21 @@ func run(url string) error {
	return nil
}

func openConfigFile(name, dir, sharedir string) (fs.File, error) {
	// Try to open the file
	path := filepath.Join(dir, name)
	f, err := os.Open(path)
func openConfigFile(dir, name string) (fs.File, error) {
	// Use the file if it exists
	f, err := os.Open(filepath.Join(dir, name))
	if err == nil {
		return f, nil
	}

	// Return the error if the file exists or sharedir is empty
	if !errors.Is(err, os.ErrNotExist) || len(sharedir) == 0 {
		return nil, err
	}

	// Create the directory if it does not exist
	if _, err := os.Stat(dir); errors.Is(err, os.ErrNotExist) {
		if err := os.MkdirAll(dir, 0755); err != nil {
			return nil, err
		}
	}

	// Copy the file
	data, err := os.ReadFile(filepath.Join(sharedir, name))
	if err != nil {
		return nil, err
	}
	if err := os.WriteFile(path, data, 0644); err != nil {
	if !errors.Is(err, fs.ErrNotExist) {
		return nil, err
	}
	return os.Open(path)
	// Use default configuration
	return embedFS.Open(path.Join("config", name))
}

func parseConfig(name, dir, sharedir string, parse func(scfg.Block) error) error {
	f, err := openConfigFile(name, dir, sharedir)
func parseConfig(dir, name string, parse func(scfg.Block) error) error {
	f, err := openConfigFile(dir, name)
	if err != nil {
		return err
	}