Skip to content

Commit

Permalink
replace updateReference function with refs.UpdateBranchHash method (#109
Browse files Browse the repository at this point in the history
)
  • Loading branch information
JunNishimura committed Jun 10, 2023
1 parent 201e7ba commit be919d6
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 21 deletions.
4 changes: 2 additions & 2 deletions cmd/commit.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,8 @@ func commit() error {
}

// update branch
if err := updateReference(branchPath, commit.Hash); err != nil {
return fmt.Errorf("fail to update branch %s: %w", branchPath, err)
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)
}

return nil
Expand Down
33 changes: 14 additions & 19 deletions cmd/updateRef.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,16 @@ import (
"fmt"
"os"
"path/filepath"
"regexp"
"strings"

"github.com/JunNishimura/Goit/internal/sha"
"github.com/spf13/cobra"
)

func updateReference(refPath string, hash sha.SHA1) error {
f, err := os.Create(refPath)
if err != nil {
return fmt.Errorf("%w: %s", ErrIOHandling, refPath)
}
defer f.Close()

_, err = f.WriteString(hash.String())
if err != nil {
return fmt.Errorf("fail to write hash(%s) to %s", hash.String(), refPath)
}

return nil
}
var (
branchRegexp = regexp.MustCompile("refs/heads/.+")
)

// updateRefCmd represents the updateRef command
var updateRefCmd = &cobra.Command{
Expand All @@ -44,7 +35,11 @@ var updateRefCmd = &cobra.Command{
}

// get reference path
refPath := filepath.Join(client.RootGoitPath, args[0])
if ok := branchRegexp.MatchString(args[0]); !ok {
return fmt.Errorf("invalid branch path %s", args[0])
}
branchSplit := strings.Split(args[0], "/")
branchName := branchSplit[len(branchSplit)-1]

// hash validation
hashString := args[1]
Expand All @@ -53,15 +48,15 @@ var updateRefCmd = &cobra.Command{
}
hashPath := filepath.Join(client.RootGoitPath, "objects", hashString[:2], hashString[2:])
if _, err := os.Stat(hashPath); os.IsNotExist(err) {
return fmt.Errorf("fatal: trying to write ref '%s' with nonexistent object %s", refPath, hashString)
return fmt.Errorf("fatal: trying to write ref '%s' with nonexistent object %s", args[0], hashString)
}
hash, err := sha.ReadHash(hashString)
newHash, err := sha.ReadHash(hashString)
if err != nil {
return ErrInvalidHash
}

if err := updateReference(refPath, hash); err != nil {
return fmt.Errorf("fail to update reference %s: %w", refPath, err)
if err := client.Refs.UpdateBranchHash(client.RootGoitPath, branchName, newHash); err != nil {
return fmt.Errorf("fail to update reference %s: %w", args[0], err)
}

return nil
Expand Down

0 comments on commit be919d6

Please sign in to comment.