sync: Try to use a ssh key if no ssh-agent configured
This commit is contained in:
parent
3625af47d9
commit
9fe1374a77
1 changed files with 29 additions and 0 deletions
|
@ -2,10 +2,14 @@ package sync
|
|||
|
||||
import (
|
||||
"bufio"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
"path"
|
||||
|
||||
"github.com/go-git/go-git/v5"
|
||||
"github.com/go-git/go-git/v5/config"
|
||||
"github.com/go-git/go-git/v5/plumbing/transport/ssh"
|
||||
)
|
||||
|
||||
// GitImporter implements an Importer, where files to imports are located
|
||||
|
@ -13,12 +17,35 @@ import (
|
|||
type GitImporter struct {
|
||||
li LocalImporter
|
||||
Remote string
|
||||
Auth ssh.AuthMethod
|
||||
}
|
||||
|
||||
func NewGitImporter(li LocalImporter, remote string) GitImporter {
|
||||
var auth ssh.AuthMethod
|
||||
|
||||
// If there is no ssh-agent setup, try to use a default ssh key
|
||||
if _, exists := os.LookupEnv("SSH_AUTH_SOCK"); !exists {
|
||||
if home, exists := os.LookupEnv("HOME"); exists {
|
||||
for _, d := range []string{"id_fic", "id_ed25519", "id_rsa"} {
|
||||
pemBytes, err := ioutil.ReadFile(path.Join(home, ".ssh", d))
|
||||
if err == nil {
|
||||
log.Println("[GitImporter] Using", path.Join(home, ".ssh", d), "as ssh key to sync repository")
|
||||
auth, err = ssh.NewPublicKeys("git", pemBytes, "")
|
||||
if ccfg, err := auth.ClientConfig(); err != nil {
|
||||
if hkc, err := ssh.NewKnownHostsCallback(); err != nil {
|
||||
ccfg.HostKeyCallback = hkc
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return GitImporter{
|
||||
li: li,
|
||||
Remote: remote,
|
||||
Auth: auth,
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -57,6 +84,7 @@ func (i GitImporter) Init() error {
|
|||
_, err = git.PlainClone(i.li.Base, false, &git.CloneOptions{
|
||||
URL: i.Remote,
|
||||
RecurseSubmodules: git.DefaultSubmoduleRecursionDepth,
|
||||
Auth: i.Auth,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
|
@ -98,6 +126,7 @@ func (i GitImporter) Sync() error {
|
|||
Depth: 1,
|
||||
RecurseSubmodules: git.DefaultSubmoduleRecursionDepth,
|
||||
Force: true,
|
||||
Auth: i.Auth,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
|
Reference in a new issue