forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
util.go
57 lines (51 loc) · 1.59 KB
/
util.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
package scmauth
import (
"fmt"
"io/ioutil"
"path/filepath"
"strings"
"github.com/openshift/origin/pkg/util/file"
)
func createGitConfig(includePath string, context SCMAuthContext) error {
tempDir, err := ioutil.TempDir("", "git")
if err != nil {
return err
}
gitconfig := filepath.Join(tempDir, ".gitconfig")
content := fmt.Sprintf("[include]\npath = %s\n", includePath)
if err := ioutil.WriteFile(gitconfig, []byte(content), 0600); err != nil {
return err
}
// The GIT_CONFIG variable won't affect regular git operation
// therefore the HOME variable needs to be set so git can pick up
// .gitconfig from that location. The GIT_CONFIG variable is still used
// to track the location of the GIT_CONFIG for multiple SCMAuth objects.
if err := context.Set("HOME", tempDir); err != nil {
return err
}
if err := context.Set("GIT_CONFIG", gitconfig); err != nil {
return err
}
return nil
}
// ensureGitConfigIncludes ensures that the OS env var GIT_CONFIG is set and
// that it points to a file that has an include statement for the given path
func ensureGitConfigIncludes(path string, context SCMAuthContext) error {
gitconfig, present := context.Get("GIT_CONFIG")
if !present {
return createGitConfig(path, context)
}
lines, err := file.ReadLines(gitconfig)
if err != nil {
return err
}
for _, line := range lines {
// If include already exists, return with no error
if line == fmt.Sprintf("path = %s", path) {
return nil
}
}
lines = append(lines, fmt.Sprintf("path = %s", path))
content := []byte(strings.Join(lines, "\n"))
return ioutil.WriteFile(gitconfig, content, 0600)
}