Skip to content

Commit

Permalink
add list and rename (#98)
Browse files Browse the repository at this point in the history
  • Loading branch information
JunNishimura committed Jun 4, 2023
1 parent e35cc26 commit 5f4ea28
Showing 1 changed file with 50 additions and 6 deletions.
56 changes: 50 additions & 6 deletions cmd/branch.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ package cmd

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

"github.com/JunNishimura/Goit/internal/store"
"github.com/fatih/color"
"github.com/spf13/cobra"
)
Expand All @@ -15,6 +18,46 @@ var (
deleteOption string = ""
)

func list(client *store.Client) {
for _, branch := range client.Refs.Heads {
if branch.Name == client.Head.Reference {
color.Green("* %s", branch.Name)
} else {
fmt.Println(branch.Name)
}
}
}

func rename(client *store.Client, newName string) error {
// check if new name is not used for other branches
for _, branch := range client.Refs.Heads {
if branch.Name == newName {
return fmt.Errorf("fatal: branch named '%s' already exists", newName)
}
}

// rename current branch
branch, err := client.Refs.GetBranch(client.Head.Reference)
if err != nil {
return err
}
branch.Name = newName

// rename file
oldPath := filepath.Join(client.RootGoitPath, "refs", "heads", client.Head.Reference)
newPath := filepath.Join(client.RootGoitPath, "refs", "heads", newName)
if err := os.Rename(oldPath, newPath); err != nil {
return fmt.Errorf("fail to rename: %w", err)
}

// rename HEAD
if err := client.Head.Update(client.RootGoitPath, newName); err != nil {
return err
}

return nil
}

// branchCmd represents the branch command
var branchCmd = &cobra.Command{
Use: "branch",
Expand All @@ -40,12 +83,13 @@ var branchCmd = &cobra.Command{

// list branches
if isList {
for _, branch := range client.Refs.Heads {
if branch.Name == client.Head.Reference {
color.Green("* %s", branch.Name)
} else {
fmt.Println(branch.Name)
}
list(client)
}

// rename current branch
if renameOption != "" {
if err := rename(client, renameOption); err != nil {
return err
}
}

Expand Down

0 comments on commit 5f4ea28

Please sign in to comment.