2021-09-10 22:54:02 +00:00
|
|
|
package git
|
|
|
|
|
|
|
|
import (
|
2021-09-14 14:00:15 +00:00
|
|
|
"fmt"
|
2021-09-10 22:54:02 +00:00
|
|
|
"os"
|
2021-11-02 12:36:40 +00:00
|
|
|
"path/filepath"
|
2021-09-14 14:00:15 +00:00
|
|
|
"strings"
|
2021-09-10 22:54:02 +00:00
|
|
|
|
|
|
|
"github.com/go-git/go-git/v5"
|
|
|
|
"github.com/go-git/go-git/v5/plumbing"
|
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Clone runs a git clone which accounts for different default branches.
|
|
|
|
func Clone(dir, url string) error {
|
|
|
|
if _, err := os.Stat(dir); os.IsNotExist(err) {
|
2021-12-23 23:43:42 +00:00
|
|
|
logrus.Debugf("%s does not exist, attempting to git clone from %s", dir, url)
|
2023-01-22 19:53:25 +00:00
|
|
|
|
|
|
|
_, err := git.PlainClone(dir, false, &git.CloneOptions{
|
|
|
|
URL: url,
|
|
|
|
Tags: git.AllTags,
|
|
|
|
ReferenceName: plumbing.ReferenceName("refs/heads/master"),
|
|
|
|
SingleBranch: true,
|
|
|
|
})
|
2021-09-10 22:54:02 +00:00
|
|
|
if err != nil {
|
2021-12-23 23:43:42 +00:00
|
|
|
logrus.Debugf("cloning %s default branch failed, attempting from main branch", url)
|
2023-01-22 19:53:25 +00:00
|
|
|
|
2021-09-10 22:54:02 +00:00
|
|
|
_, err := git.PlainClone(dir, false, &git.CloneOptions{
|
|
|
|
URL: url,
|
|
|
|
Tags: git.AllTags,
|
|
|
|
ReferenceName: plumbing.ReferenceName("refs/heads/main"),
|
2023-01-22 19:53:25 +00:00
|
|
|
SingleBranch: true,
|
2021-09-10 22:54:02 +00:00
|
|
|
})
|
|
|
|
if err != nil {
|
2021-11-02 12:36:40 +00:00
|
|
|
if strings.Contains(err.Error(), "authentication required") {
|
|
|
|
name := filepath.Base(dir)
|
|
|
|
return fmt.Errorf("unable to clone %s, does %s exist?", name, url)
|
|
|
|
}
|
2023-01-22 19:53:25 +00:00
|
|
|
|
2021-09-10 22:54:02 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
2023-01-22 19:53:25 +00:00
|
|
|
|
2021-12-23 23:43:42 +00:00
|
|
|
logrus.Debugf("%s has been git cloned successfully", dir)
|
2021-09-14 14:00:15 +00:00
|
|
|
} else {
|
2021-12-25 23:14:32 +00:00
|
|
|
logrus.Debugf("%s already exists", dir)
|
2021-09-10 22:54:02 +00:00
|
|
|
}
|
|
|
|
|
2021-09-14 14:00:15 +00:00
|
|
|
return nil
|
|
|
|
}
|