2013-11-02 00:31:11 +00:00
|
|
|
package gitmediaclient
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"fmt"
|
|
|
|
"net/url"
|
|
|
|
"os/exec"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2013-11-02 00:54:33 +00:00
|
|
|
func credentials(u *url.URL) (Creds, error) {
|
|
|
|
creds := Creds{"protocol": u.Scheme, "host": u.Host}
|
|
|
|
cmd, err := execCreds(creds, "fill")
|
2013-11-02 00:31:11 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return cmd.Credentials(), nil
|
|
|
|
}
|
|
|
|
|
2013-11-02 00:54:33 +00:00
|
|
|
func execCreds(input Creds, subCommand string) (*CredentialCmd, error) {
|
2013-11-02 00:31:11 +00:00
|
|
|
cmd := NewCommand(input, subCommand)
|
|
|
|
err := cmd.Start()
|
2013-11-02 00:36:20 +00:00
|
|
|
if err == nil {
|
|
|
|
err = cmd.Wait()
|
|
|
|
}
|
|
|
|
|
2013-11-02 00:31:11 +00:00
|
|
|
if err != nil {
|
2013-11-02 00:36:20 +00:00
|
|
|
return cmd, fmt.Errorf("'git credential %s' error: %s\n%s", cmd.SubCommand, err.Error(), cmd.StderrString())
|
2013-11-02 00:31:11 +00:00
|
|
|
}
|
|
|
|
|
2013-11-02 00:36:20 +00:00
|
|
|
return cmd, nil
|
2013-11-02 00:31:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type CredentialCmd struct {
|
2013-11-02 00:36:20 +00:00
|
|
|
output *bytes.Buffer
|
|
|
|
err *bytes.Buffer
|
|
|
|
SubCommand string
|
2013-11-02 00:31:11 +00:00
|
|
|
*exec.Cmd
|
|
|
|
}
|
|
|
|
|
2013-11-02 00:54:33 +00:00
|
|
|
func NewCommand(input Creds, subCommand string) *CredentialCmd {
|
2013-11-02 00:31:11 +00:00
|
|
|
buf1 := new(bytes.Buffer)
|
|
|
|
buf2 := new(bytes.Buffer)
|
|
|
|
cmd := exec.Command("git", "credential", subCommand)
|
2013-11-02 00:54:33 +00:00
|
|
|
cmd.Stdin = input.Buffer()
|
2013-11-02 00:31:11 +00:00
|
|
|
cmd.Stdout = buf1
|
|
|
|
cmd.Stderr = buf2
|
2013-11-02 00:36:20 +00:00
|
|
|
return &CredentialCmd{buf1, buf2, subCommand, cmd}
|
2013-11-02 00:31:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *CredentialCmd) StderrString() string {
|
2013-11-02 00:36:20 +00:00
|
|
|
return c.err.String()
|
2013-11-02 00:31:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *CredentialCmd) StdoutString() string {
|
2013-11-02 00:36:20 +00:00
|
|
|
return c.output.String()
|
2013-11-02 00:31:11 +00:00
|
|
|
}
|
|
|
|
|
2013-11-02 00:54:33 +00:00
|
|
|
func (c *CredentialCmd) Credentials() Creds {
|
|
|
|
creds := make(Creds)
|
2013-11-02 00:31:11 +00:00
|
|
|
|
|
|
|
for _, line := range strings.Split(c.StdoutString(), "\n") {
|
|
|
|
pieces := strings.SplitN(line, "=", 2)
|
|
|
|
if len(pieces) < 2 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
creds[pieces[0]] = pieces[1]
|
|
|
|
}
|
|
|
|
|
|
|
|
return creds
|
|
|
|
}
|
2013-11-02 00:54:33 +00:00
|
|
|
|
|
|
|
type Creds map[string]string
|
|
|
|
|
|
|
|
func (c Creds) Buffer() *bytes.Buffer {
|
|
|
|
buf := new(bytes.Buffer)
|
|
|
|
|
|
|
|
for k, v := range c {
|
|
|
|
buf.Write([]byte(k))
|
|
|
|
buf.Write([]byte("="))
|
|
|
|
buf.Write([]byte(v))
|
|
|
|
buf.Write([]byte("\n"))
|
|
|
|
}
|
|
|
|
|
|
|
|
return buf
|
|
|
|
}
|