From f46fef4495322a5c748eec935df2433df85e963d Mon Sep 17 00:00:00 2001 From: Jun Nishimura Date: Sun, 11 Jun 2023 23:42:03 +0900 Subject: [PATCH] fix bug (#113) --- cmd/commit.go | 14 +++++++++++--- internal/store/refs.go | 9 +++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/cmd/commit.go b/cmd/commit.go index 17e4a38..d51b07c 100644 --- a/cmd/commit.go +++ b/cmd/commit.go @@ -63,9 +63,17 @@ func commit() error { return fmt.Errorf("fail to write commit object: %w", err) } - // update branch - if err := client.Refs.UpdateBranchHash(client.RootGoitPath, client.Head.Reference, commit.Hash); err != nil { - return fmt.Errorf("fail to update branch %s: %w", client.Head.Reference, err) + // create/update branch + if client.Refs.IsBranchExist(client.Head.Reference) { + // update + if err := client.Refs.UpdateBranchHash(client.RootGoitPath, client.Head.Reference, commit.Hash); err != nil { + return fmt.Errorf("fail to update branch %s: %w", client.Head.Reference, err) + } + } else { + // create + if err := client.Refs.AddBranch(client.RootGoitPath, client.Head.Reference, commit.Hash); err != nil { + return fmt.Errorf("fail to create branch %s: %w", client.Head.Reference, err) + } } return nil diff --git a/internal/store/refs.go b/internal/store/refs.go index 0f42a93..f38ae31 100644 --- a/internal/store/refs.go +++ b/internal/store/refs.go @@ -98,6 +98,11 @@ func (r *Refs) ListBranches(headBranchName string) { } } +func (r *Refs) IsBranchExist(branchName string) bool { + p := r.getBranchPos(branchName) + return p != NewBranchFlag +} + func (r *Refs) AddBranch(rootGoitPath, newBranchName string, newBranchHash sha.SHA1) error { // check if branch already exists n := r.getBranchPos(newBranchName) @@ -153,6 +158,10 @@ func (r *Refs) RenameBranch(head *Head, rootGoitPath, newBranchName string) erro // return the index of branch in the Refs Heads. // if not found, return NewBranchFlag which is -1. func (r *Refs) getBranchPos(branchName string) int { + if len(r.Heads) == 0 { + return NewBranchFlag + } + // binary search left := 0 right := len(r.Heads)