Skip to content
Permalink
Browse files

Save GitConfig to file using Save()

Signed-off-by: Jiang Xin <zhiyou.jx@alibaba-inc.com>
  • Loading branch information...
jiangxin committed Mar 11, 2019
1 parent 5a23ce4 commit b826f4926857921ac0851ae98926ddb82dd7dbcc
Showing with 63 additions and 0 deletions.
  1. +21 −0 git-config.go
  2. +42 −0 load_test.go
@@ -2,6 +2,8 @@ package goconfig

import (
"fmt"
"io/ioutil"
"os"
"reflect"
"sort"
"strconv"
@@ -407,3 +409,22 @@ func (v GitConfig) StringOfScope(scope Scope) string {
}
return strings.Join(lines, "\n") + "\n"
}

// Save will save git config to file
func (v GitConfig) Save(file string) error {
lockFile := file + ".lock"

err := ioutil.WriteFile(lockFile, []byte(v.String()), 0644)
defer os.Remove(lockFile)

if err != nil {
return err
}

_, err = LoadFile(lockFile, false)
if err != nil {
return fmt.Errorf("fail to save '%s': %s", file, err)
}

return os.Rename(lockFile, file)
}
@@ -316,3 +316,45 @@ func TestAllConfig(t *testing.T) {
assert.Equal("repo 4", allConfig.Get("test.key4"))
assert.Equal("repo 5", allConfig.Get("test.key5"))
}

func TestSaveConfig(t *testing.T) {
assert := assert.New(t)

tmpdir, err := ioutil.TempDir("", "goconfig")
if err != nil {
panic(err)
}
defer func(dir string) {
os.RemoveAll(dir)
}(tmpdir)

home := os.Getenv("HOME")
os.Setenv("HOME", tmpdir)
defer os.Setenv("HOME", home)

// Create system config
cfgFile := filepath.Join(tmpdir, "gitconfig")

assert.Nil(exec.Command("git", "config", "-f", cfgFile, "ab.cd.ef", "value-1").Run())
assert.Nil(exec.Command("git", "config", "-f", cfgFile, "ab.cd e.fg", "value 2").Run())
assert.Nil(exec.Command("git", "config", "-f", cfgFile, "--add", "ab.cd e.fg", "value 3").Run())
assert.Nil(exec.Command("git", "config", "-f", cfgFile, "--add", "ab.cd e.fg", "value 4").Run())
assert.Nil(exec.Command("git", "config", "-f", cfgFile, "ab.cd", "value has space ").Run())

// Load cfgFile
cfg, err := LoadFile(cfgFile, false)
assert.Nil(err)
assert.Equal("value has space ", cfg.Get("ab.cd"))

// Save file
newCfgFile := cfgFile + ".new"
err = cfg.Save(newCfgFile)
assert.Nil(err)
_, err = os.Stat(newCfgFile)
assert.Nil(err)

// Load new file
newCfg, err := LoadFile(newCfgFile, false)
assert.Nil(err)
assert.Equal(cfg, newCfg)
}

0 comments on commit b826f49

Please sign in to comment.
You can’t perform that action at this time.