Files
abra/pkg/git/init.go
decentral1se 37c0257851
Some checks failed
continuous-integration/drone/push Build is failing
WIP: feat: translation support
See #483
2025-08-23 17:03:53 +02:00

77 lines
2.0 KiB
Go

package git
import (
"errors"
"coopcloud.tech/abra/pkg/log"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/object"
"coopcloud.tech/abra/pkg/i18n"
)
// Init inits a new repo and commits all the stuff if you want
func Init(repoPath string, commit bool, gitName, gitEmail string) error {
repo, err := git.PlainInit(repoPath, false)
if err != nil {
return errors.New(i18n.G("git init: %s", err))
}
if err = SwitchToMain(repo); err != nil {
return errors.New(i18n.G("git branch rename: %s", err))
}
log.Debug(i18n.G("initialised new git repo in %s", repoPath))
if commit {
commitRepo, err := git.PlainOpen(repoPath)
if err != nil {
return errors.New(i18n.G("git open: %s", err))
}
commitWorktree, err := commitRepo.Worktree()
if err != nil {
return errors.New(i18n.G("git worktree: %s", err))
}
if err := commitWorktree.AddWithOptions(&git.AddOptions{All: true}); err != nil {
return errors.New(i18n.G("git add: %s", err))
}
var author *object.Signature
if gitName != "" && gitEmail != "" {
author = &object.Signature{Name: gitName, Email: gitEmail}
}
if _, err = commitWorktree.Commit("init", &git.CommitOptions{Author: author}); err != nil {
return errors.New(i18n.G("git commit: %s", err))
}
log.Debug(i18n.G("init committed all files for new git repo in %s", repoPath))
}
return nil
}
// SwitchToMain sets the default branch to "main".
func SwitchToMain(repo *git.Repository) error {
ref := plumbing.NewSymbolicReference(plumbing.HEAD, plumbing.ReferenceName("refs/heads/main"))
if err := repo.Storer.SetReference(ref); err != nil {
return errors.New(i18n.G("set reference: %s", err))
}
cfg, err := repo.Config()
if err != nil {
return errors.New(i18n.G("repo config: %s", err))
}
cfg.Init.DefaultBranch = "main"
if err := repo.SetConfig(cfg); err != nil {
return errors.New(i18n.G("repo set config: %s", err))
}
log.Debug(i18n.G("set 'main' as the default branch"))
return nil
}