Skip to content

Commit

Permalink
add GetBranch to refs (#98)
Browse files Browse the repository at this point in the history
  • Loading branch information
JunNishimura committed Jun 4, 2023
1 parent e8c518a commit e015550
Showing 1 changed file with 27 additions and 14 deletions.
41 changes: 27 additions & 14 deletions internal/store/refs.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package store

import (
"fmt"
"os"
"path/filepath"

Expand All @@ -12,13 +13,33 @@ type branch struct {
hash sha.SHA1
}

func newBranch(rootGoitPath, branchName string) (*branch, error) {
branchPath := filepath.Join(rootGoitPath, "refs", "heads", branchName)
hashByte, err := os.ReadFile(branchPath)
if err != nil {
return nil, err
}
hashString := string(hashByte)
hash, err := sha.ReadHash(hashString)
if err != nil {
return nil, err
}
return &branch{
Name: branchName,
hash: hash,
}, nil
}

type Refs struct {
Heads []*branch
}

func NewRefs(rootGoitPath string) (*Refs, error) {
r := newRefs()
headsPath := filepath.Join(rootGoitPath, "refs", "heads")
if _, err := os.Stat(headsPath); os.IsNotExist(err) {
return r, nil
}
files, err := os.ReadDir(headsPath)
if err != nil {
return nil, err
Expand All @@ -39,19 +60,11 @@ func newRefs() *Refs {
}
}

func newBranch(rootGoitPath, branchName string) (*branch, error) {
branchPath := filepath.Join(rootGoitPath, "refs", "heads", branchName)
hashByte, err := os.ReadFile(branchPath)
if err != nil {
return nil, err
}
hashString := string(hashByte)
hash, err := sha.ReadHash(hashString)
if err != nil {
return nil, err
func (r *Refs) GetBranch(name string) (*branch, error) {
for _, b := range r.Heads {
if b.Name == name {
return b, nil
}
}
return &branch{
Name: branchName,
hash: hash,
}, nil
return nil, fmt.Errorf("fail to find '%s' branch", name)
}

0 comments on commit e015550

Please sign in to comment.