GitRoot

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