2021-07-15 14:46:04 +02:00
|
|
|
package npm
|
|
|
|
|
|
|
|
import (
|
2022-03-04 11:26:46 +02:00
|
|
|
"fmt"
|
2023-08-16 12:57:04 +02:00
|
|
|
"os"
|
2021-07-15 14:46:04 +02:00
|
|
|
"path/filepath"
|
2022-03-04 11:26:46 +02:00
|
|
|
"regexp"
|
2021-07-15 14:46:04 +02:00
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2022-03-02 15:06:51 +02:00
|
|
|
defaultConfigFilename = ".piperNpmrc" // default by npm
|
2021-07-15 14:46:04 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2023-08-16 12:57:04 +02:00
|
|
|
propertiesLoadFile = os.ReadFile
|
|
|
|
propertiesWriteFile = os.WriteFile
|
2021-07-15 14:46:04 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
func NewNPMRC(path string) NPMRC {
|
2022-03-02 15:06:51 +02:00
|
|
|
if !strings.HasSuffix(path, defaultConfigFilename) {
|
|
|
|
path = filepath.Join(path, defaultConfigFilename)
|
2021-07-15 14:46:04 +02:00
|
|
|
}
|
2022-03-02 15:06:51 +02:00
|
|
|
|
2022-03-04 11:26:46 +02:00
|
|
|
return NPMRC{filepath: path}
|
2021-07-15 14:46:04 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
type NPMRC struct {
|
|
|
|
filepath string
|
2022-03-04 11:26:46 +02:00
|
|
|
content string
|
2021-07-15 14:46:04 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (rc *NPMRC) Write() error {
|
2022-03-04 11:26:46 +02:00
|
|
|
if err := propertiesWriteFile(rc.filepath, []byte(rc.content), 0644); err != nil {
|
2021-07-15 14:46:04 +02:00
|
|
|
return errors.Wrapf(err, "failed to write %s", rc.filepath)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (rc *NPMRC) Load() error {
|
2022-03-04 11:26:46 +02:00
|
|
|
bytes, err := propertiesLoadFile(rc.filepath)
|
2021-07-15 14:46:04 +02:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-03-04 11:26:46 +02:00
|
|
|
rc.content = string(bytes)
|
2021-07-15 14:46:04 +02:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (rc *NPMRC) Set(key, value string) {
|
2022-03-04 11:26:46 +02:00
|
|
|
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"
|
|
|
|
}
|
2021-07-15 14:46:04 +02:00
|
|
|
}
|