-
Notifications
You must be signed in to change notification settings - Fork 0
/
git_credential_manager.go
91 lines (75 loc) · 2.25 KB
/
git_credential_manager.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
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
package git
import (
"bytes"
"fmt"
"path/filepath"
"strings"
"github.com/paketo-buildpacks/packit/v2/pexec"
"github.com/paketo-buildpacks/packit/v2/scribe"
"github.com/paketo-buildpacks/packit/v2/servicebindings"
)
//go:generate faux --interface BindingResolver --output fakes/binding_resolver.go
type BindingResolver interface {
Resolve(typ, provider, platformDir string) ([]servicebindings.Binding, error)
}
type GitCredentialManager struct {
bindingResolver BindingResolver
executable Executable
logs scribe.Emitter
}
func NewGitCredentialManager(bindingResolver BindingResolver, executable Executable, logs scribe.Emitter) GitCredentialManager {
return GitCredentialManager{
bindingResolver: bindingResolver,
executable: executable,
logs: logs,
}
}
func (g GitCredentialManager) Setup(workingDir, platformDir string) error {
bindings, err := g.bindingResolver.Resolve("git-credentials", "", platformDir)
if err != nil {
return err
}
if len(bindings) == 0 {
// If there are no bindings then we are done
return nil
}
g.logs.Process("Configuring credentials")
uniqueContext := map[string]interface{}{}
for _, b := range bindings {
context := "credential.helper"
if entry, ok := b.Entries["context"]; ok {
domain, err := entry.ReadString()
if err != nil {
return err
}
context = fmt.Sprintf("credential.%s.helper", strings.TrimSpace(domain))
}
// Checks to see if the context is unique if not error because having
// multiple credentials for the same context is not supported
_, exists := uniqueContext[context]
if !exists {
uniqueContext[context] = nil
} else {
return fmt.Errorf("failed: there are two or more bindings for the same context: please limit the bindings to one per context")
}
buffer := bytes.NewBuffer(nil)
err := g.executable.Execute(pexec.Execution{
Args: []string{
"config",
"--global",
context,
fmt.Sprintf("!f() { cat %q; }; f", filepath.Join(b.Path, "credentials")),
},
Dir: workingDir,
Stdout: buffer,
Stderr: buffer,
})
if err != nil {
g.logs.Detail(buffer.String())
return err
}
}
g.logs.Process("Added %d custom git credential manager(s) to the git config", len(uniqueContext))
g.logs.Break()
return nil
}