-
Notifications
You must be signed in to change notification settings - Fork 584
/
config.go
61 lines (49 loc) · 1.1 KB
/
config.go
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
package npm
import (
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/pkg/errors"
)
const (
defaultConfigFilename = ".piperNpmrc" // default by npm
)
var (
propertiesLoadFile = os.ReadFile
propertiesWriteFile = os.WriteFile
)
func NewNPMRC(path string) NPMRC {
if !strings.HasSuffix(path, defaultConfigFilename) {
path = filepath.Join(path, defaultConfigFilename)
}
return NPMRC{filepath: path}
}
type NPMRC struct {
filepath string
content string
}
func (rc *NPMRC) Write() error {
if err := propertiesWriteFile(rc.filepath, []byte(rc.content), 0644); err != nil {
return errors.Wrapf(err, "failed to write %s", rc.filepath)
}
return nil
}
func (rc *NPMRC) Load() error {
bytes, err := propertiesLoadFile(rc.filepath)
if err != nil {
return err
}
rc.content = string(bytes)
return nil
}
func (rc *NPMRC) Set(key, value string) {
r := regexp.MustCompile(fmt.Sprintf(`(?m)^\s*%s\s*=.*$`, key))
keyValue := fmt.Sprintf("%s=%s", key, value)
if r.MatchString(rc.content) {
rc.content = r.ReplaceAllString(rc.content, keyValue)
} else {
rc.content += keyValue + "\n"
}
}