diff --git a/pkg/git/init.go b/pkg/git/init.go index fe262780..30ffa1ae 100644 --- a/pkg/git/init.go +++ b/pkg/git/init.go @@ -5,14 +5,19 @@ import ( "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" ) // Init inits a new repo and commits all the stuff if you want func Init(repoPath string, commit bool, gitName, gitEmail string) error { - if _, err := git.PlainInit(repoPath, false); err != nil { + repo, err := git.PlainInit(repoPath, false) + if err != nil { return fmt.Errorf("git init: %s", err) } + if err = SwitchToMain(repo); err != nil { + return fmt.Errorf("git branch rename: %s", err) + } log.Debugf("initialised new git repo in %s", repoPath) if commit { @@ -42,3 +47,21 @@ func Init(repoPath string, commit bool, gitName, gitEmail string) error { return nil } + +// Set the default branch for the passed repo as "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 fmt.Errorf("set reference: %s", err) + } + cfg, err := repo.Config() + if err != nil { + return fmt.Errorf("repo config: %s", err) + } + cfg.Init.DefaultBranch = "main" + if err := repo.SetConfig(cfg); err != nil { + return fmt.Errorf("repo set config: %s", err) + } + log.Debug("set 'main' as the default branch.") + return nil +} diff --git a/pkg/git/init_test.go b/pkg/git/init_test.go new file mode 100644 index 00000000..29fcb057 --- /dev/null +++ b/pkg/git/init_test.go @@ -0,0 +1,36 @@ +package git + +import ( + "testing" + + "github.com/go-git/go-git/v5" + "github.com/go-git/go-git/v5/plumbing" + "github.com/go-git/go-git/v5/storage/memory" +) + +// Verify that SwitchToMain has the desired effect on the repo +func TestSwitchToMain(t *testing.T) { + storage := memory.NewStorage() + repo, err := git.Init(storage, nil) + if err != nil { + t.Fatalf("failed to create in-memory repository: %v", err) + } + err = SwitchToMain(repo) + if err != nil { + t.Fatalf("SwitchToMain failed: %v", err) + } + ref, err := repo.Reference(plumbing.HEAD, false) + if err != nil { + t.Fatalf("failed to get HEAD reference: %v", err) + } + if ref.Target().String() != "refs/heads/main" { + t.Errorf("expected HEAD to point to 'refs/heads/main', got %s", ref.Target().String()) + } + cfg, err := repo.Config() + if err != nil { + t.Fatalf("failed to get repository config: %v", err) + } + if cfg.Init.DefaultBranch != "main" { + t.Errorf("expected default branch to be 'main', got %s", cfg.Init.DefaultBranch) + } +}