This repository has been archived on 2024-02-15. You can view files and clone it, but cannot push or open issues or pull requests.
config-mapper/internal/git.go

103 lines
1.9 KiB
Go
Raw Normal View History

2022-02-25 00:17:02 +01:00
package mapper
2022-02-24 22:38:17 +01:00
import (
"errors"
2022-02-26 01:28:36 +01:00
"fmt"
2022-02-24 22:38:17 +01:00
"os"
2022-02-26 01:28:36 +01:00
"path"
"strings"
2022-02-24 22:38:17 +01:00
"github.com/go-git/go-git/v5"
2022-02-26 01:28:36 +01:00
"github.com/go-git/go-git/v5/plumbing/transport"
2022-02-24 22:38:17 +01:00
"github.com/go-git/go-git/v5/plumbing/transport/http"
2022-02-26 01:28:36 +01:00
"github.com/go-git/go-git/v5/plumbing/transport/ssh"
2022-02-24 22:38:17 +01:00
)
var (
2022-02-26 01:28:36 +01:00
ErrDirIsFile = errors.New("path is a file")
ErrInvalidEnv = errors.New("found invalid environment variable in path")
2022-02-24 22:38:17 +01:00
)
2022-02-26 01:28:36 +01:00
func OpenGitRepo(c Git, l string) (*git.Repository, error) {
s, err := os.Stat(l)
2022-02-24 22:38:17 +01:00
if err != nil {
if os.IsNotExist(err) {
2022-02-26 01:28:36 +01:00
var auth transport.AuthMethod
if c.SSH.Passphrase != "" && c.SSH.PrivateKey != "" {
privateKey, err := absolutePath(c.SSH.PrivateKey)
if err != nil {
return nil, err
}
if _, err := os.Stat(privateKey); err != nil {
return nil, err
}
auth, err = ssh.NewPublicKeysFromFile("git", privateKey, c.SSH.Passphrase)
if err != nil {
return nil, err
}
} else {
auth = &http.BasicAuth{
Username: c.BasicAuth.Username,
Password: c.BasicAuth.Password,
}
2022-02-24 22:38:17 +01:00
}
2022-02-26 01:28:36 +01:00
repo, err := git.PlainClone(l, false, &git.CloneOptions{
URL: c.Repository,
2022-02-24 22:38:17 +01:00
Progress: os.Stdout,
2022-02-26 01:28:36 +01:00
Auth: auth,
2022-02-24 22:38:17 +01:00
})
if err != nil {
return nil, err
}
return repo, nil
}
return nil, err
}
2022-02-26 01:28:36 +01:00
if !s.IsDir() {
2022-02-24 22:38:17 +01:00
return nil, ErrDirIsFile
}
2022-02-26 01:28:36 +01:00
repo, err := git.PlainOpen(l)
2022-02-24 22:38:17 +01:00
if err != nil {
return nil, err
}
return repo, nil
}
2022-02-26 01:28:36 +01:00
func absolutePath(p string) (string, error) {
finalPath := p
if strings.Contains(finalPath, "~") {
h, err := os.UserHomeDir()
if err != nil {
return "", err
}
finalPath = strings.Replace(p, "~", h, 1)
}
splitted := strings.Split(finalPath, "/")
finalPath = ""
for _, s := range splitted {
pathPart := s
if strings.Contains(s, "$") {
env := os.Getenv(s)
if env == "" {
return "", ErrInvalidEnv
}
pathPart = env
}
finalPath += fmt.Sprintf("/%s", pathPart)
}
return path.Clean(finalPath), nil
}