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 return false, nil
31 } else if err != nil {
32 return false, err
33 }
34
35 if err := yaml.Unmarshal(content, rc); err != nil {
36 return false, err
37 }
38 c.RootRepositoryName = rc.RootRepositoryName
39 if semver.Compare(currentVersion, rc.Version) != 0 {
40 //update version in file
41 writeRootConf(path, &RootConfiguration{
42 RootRepositoryName: c.RootRepositoryName,
43 Version: currentVersion,
44 })
45 return true, nil
46 }
47 return false, nil
48}
49
50func writeRootConf(path string, conf *RootConfiguration) error {
51 if c, err := yaml.Marshal(conf); err != nil {
52 return err
53 } else {
54 if err := os.MkdirAll(filepath.Dir(path), fs.ModePerm); err != nil {
55 return err
56 }
57 return os.WriteFile(path, c, fs.ModePerm)
58 }
59}