GitRoot

craft your forge, build your project, grow your community freely
 1package configuration
 2
 3import (
 4	"errors"
 5	"io/fs"
 6	"os"
 7	"path/filepath"
 8
 9	"github.com/goccy/go-yaml"
10	"golang.org/x/mod/semver"
11)
12
13type RootConfiguration struct {
14	RootRepositoryName string
15	Version            string
16}
17
18func (c *Configuration) LoadFromOrStoreToRootConf(path string, currentVersion string) (bool, error) {
19	rc := &RootConfiguration{
20		RootRepositoryName: c.RootRepositoryName,
21		Version:            currentVersion,
22	}
23	content, err := os.ReadFile(path)
24	if errors.Is(err, os.ErrNotExist) {
25		writeRootConf(path, rc)
26	} else if err != nil {
27		return false, err
28	}
29
30	if err := yaml.Unmarshal(content, rc); err != nil {
31		return false, err
32	}
33	c.RootRepositoryName = rc.RootRepositoryName
34	if semver.Compare(currentVersion, rc.Version) != 0 {
35		//update version in file
36		writeRootConf(path, &RootConfiguration{
37			RootRepositoryName: c.RootRepositoryName,
38			Version:            currentVersion,
39		})
40		return true, nil
41	}
42	return false, nil
43}
44
45func writeRootConf(path string, conf *RootConfiguration) error {
46	if c, err := yaml.Marshal(conf); err != nil {
47		return err
48	} else {
49		if err := os.MkdirAll(filepath.Dir(path), fs.ModePerm); err != nil {
50			return err
51		}
52		return os.WriteFile(path, c, fs.ModePerm)
53	}
54}