WIP: the beginning of catalogue generation

See coop-cloud/organising#159.
This commit is contained in:
2021-09-14 16:00:15 +02:00
parent f93563588a
commit d290a4ec0b
4 changed files with 122 additions and 3 deletions

View File

@ -1,9 +1,12 @@
package git
import (
"fmt"
"os"
"strings"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/config"
"github.com/go-git/go-git/v5/plumbing"
"github.com/sirupsen/logrus"
)
@ -15,7 +18,6 @@ func Clone(dir, url string) error {
_, err := git.PlainClone(dir, false, &git.CloneOptions{URL: url, Tags: git.AllTags})
if err != nil {
logrus.Debugf("cloning from default branch failed, attempting from main branch")
// try with main branch because Git is being a Git
_, err := git.PlainClone(dir, false, &git.CloneOptions{
URL: url,
Tags: git.AllTags,
@ -25,9 +27,66 @@ func Clone(dir, url string) error {
return err
}
}
logrus.Debugf("'%s' has been git cloned successfully", dir)
} else {
logrus.Debugf("'%s' already exists, doing nothing", dir)
}
logrus.Debugf("'%s' has been git cloned successfully", dir)
return nil
}
// EnsureUpToDate ensures that a git repo on disk has the latest changes (git-fetch).
func EnsureUpToDate(dir string) error {
repo, err := git.PlainOpen(dir)
if err != nil {
return err
}
branch := "master"
if _, err := repo.Branch("master"); err != nil {
if _, err := repo.Branch("main"); err != nil {
return err
}
branch = "main"
}
logrus.Debugf("choosing '%s' as main git branch for in '%s'", branch, dir)
worktree, err := repo.Worktree()
if err != nil {
return err
}
refName := fmt.Sprintf("refs/heads/%s", branch)
checkOutOpts := &git.CheckoutOptions{
Create: false,
Force: true,
Keep: false,
Branch: plumbing.ReferenceName(refName),
}
if err := worktree.Checkout(checkOutOpts); err != nil {
return err
}
logrus.Debugf("successfully checked out '%s'", branch)
remote, err := repo.Remote("origin")
if err != nil {
return err
}
fetchOpts := &git.FetchOptions{
RemoteName: "origin",
RefSpecs: []config.RefSpec{"refs/heads/*:refs/remotes/origin/*"},
Force: true,
}
if err := remote.Fetch(fetchOpts); err != nil {
if !strings.Contains(err.Error(), "already up-to-date") {
return err
}
}
logrus.Debugf("successfully fetched all changes in '%s'", dir)
return nil
}