Skip to content

Commit

Permalink
add delete branch (#98)
Browse files Browse the repository at this point in the history
  • Loading branch information
JunNishimura committed Jun 5, 2023
1 parent 5f4ea28 commit e8e4286
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
29 changes: 29 additions & 0 deletions cmd/branch.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,29 @@ func rename(client *store.Client, newName string) error {
return nil
}

func delete(client *store.Client, branchName string) error {
// branch validation
if branchName == client.Head.Reference {
return fmt.Errorf("error: cannot delete current branch '%s'", client.Head.Reference)
}
isBranchFound := false
for _, branch := range client.Refs.Heads {
if branch.Name == branchName {
isBranchFound = true
}
}
if !isBranchFound {
return fmt.Errorf("error: branch '%s' not found", branchName)
}

// delete branch
if err := client.Refs.DeleteBranch(client.RootGoitPath, branchName); err != nil {
return err
}

return nil
}

// branchCmd represents the branch command
var branchCmd = &cobra.Command{
Use: "branch",
Expand Down Expand Up @@ -93,6 +116,12 @@ var branchCmd = &cobra.Command{
}
}

if deleteOption != "" {
if err := delete(client, deleteOption); err != nil {
return err
}
}

return nil
},
}
Expand Down
26 changes: 26 additions & 0 deletions internal/store/refs.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,29 @@ func (r *Refs) GetBranch(name string) (*branch, error) {
}
return nil, fmt.Errorf("fail to find '%s' branch", name)
}

func getBranchPos(branches []*branch, name string) (int, bool) {
for n, branch := range branches {
if branch.Name == name {
return n, true
}
}
return -1, false
}

func (r *Refs) DeleteBranch(rootGoitPath, name string) error {
// delete branch from Refs
p, isBranchFound := getBranchPos(r.Heads, name)
if !isBranchFound {
return fmt.Errorf("branch '%s' not found", name)
}
r.Heads = append(r.Heads[:p], r.Heads[p+1:]...)

// delete branch file
branchPath := filepath.Join(rootGoitPath, "refs", "heads", name)
if err := os.Remove(branchPath); err != nil {
return err
}

return nil
}

0 comments on commit e8e4286

Please sign in to comment.