aboutsummaryrefslogtreecommitdiffstats
path: root/storage/filesystem/config.go
blob: dbdce54f2dec33eb18a6b3e58abf8af04fee81bb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package filesystem

import (
	stdioutil "io/ioutil"
	"os"

	"github.com/go-git/go-git/v5/config"
	format "github.com/go-git/go-git/v5/plumbing/format/config"
	"github.com/go-git/go-git/v5/storage/filesystem/dotgit"
	"github.com/go-git/go-git/v5/utils/ioutil"
)

type ConfigStorage struct {
	dir *dotgit.DotGit
}

func (c *ConfigStorage) Config() (*config.Config, error) {
	cfg := config.NewConfig()

	// local config (./.git/config)
	f, err := c.dir.LocalConfig()
	if err != nil {
		if os.IsNotExist(err) {
			return cfg, nil
		}

		return nil, err
	}

	defer ioutil.CheckClose(f, &err)

	b, err := stdioutil.ReadAll(f)
	if err != nil {
		return cfg, err
	}

	if err = cfg.UnmarshalScoped(format.LocalScope, b); err != nil {
		return cfg, err
	}

	// global config (~/.gitconfig)
	f, err = c.dir.GlobalConfig()
	if err != nil {
		if os.IsNotExist(err) {
			return cfg, nil
		}

		return nil, err
	}

	defer ioutil.CheckClose(f, &err)

	b, err = stdioutil.ReadAll(f)
	if err != nil {
		return cfg, err
	}

	if err = cfg.UnmarshalScoped(format.GlobalScope, b); err != nil {
		return cfg, err
	}

	// system config (/etc/gitconfig)
	f, err = c.dir.SystemConfig()
	if err != nil {
		if os.IsNotExist(err) {
			return cfg, nil
		}

		return nil, err
	}

	defer ioutil.CheckClose(f, &err)

	b, err = stdioutil.ReadAll(f)
	if err != nil {
		return cfg, err
	}

	if err = cfg.UnmarshalScoped(format.SystemScope, b); err != nil {
		return cfg, err
	}

	return cfg, err
}

func (c *ConfigStorage) SetConfig(cfg *config.Config) (err error) {
	if err = cfg.Validate(); err != nil {
		return err
	}

	f, err := c.dir.LocalConfigWriter()
	if err != nil {
		return err
	}

	defer ioutil.CheckClose(f, &err)

	b, err := cfg.Marshal()
	if err != nil {
		return err
	}

	_, err = f.Write(b)
	return err
}