diff --git a/cmd/switch.go b/cmd/switch.go new file mode 100644 index 0000000..309229c --- /dev/null +++ b/cmd/switch.go @@ -0,0 +1,63 @@ +/* +Copyright © 2023 NAME HERE +*/ +package cmd + +import ( + "errors" + "fmt" + + "github.com/spf13/cobra" +) + +var ( + createOption string +) + +// switchCmd represents the switch command +var switchCmd = &cobra.Command{ + Use: "switch", + Short: "switch branches", + Long: "switch branches", + PreRunE: func(cmd *cobra.Command, args []string) error { + if client.RootGoitPath == "" { + return ErrGoitNotInitialized + } + return nil + }, + RunE: func(cmd *cobra.Command, args []string) error { + // validation + if len(args) >= 2 { + return errors.New("fatal: only one reference expected") + } + if createOption == "" && len(args) == 0 { + return errors.New("fatal: missing branch") + } else if createOption != "" && len(args) >= 1 { + return errors.New("invalid create option format") + } + + // switch branch == update HEAD + if len(args) == 1 { + if err := client.Head.Update(client.Refs, client.RootGoitPath, args[0]); err != nil { + return fmt.Errorf("fail to update HEAD: %w", err) + } + } + + if createOption != "" { + if err := client.Refs.AddBranch(client.RootGoitPath, createOption, client.Head.Commit.Hash); err != nil { + return fmt.Errorf("fail to create new branch %s: %w", createOption, err) + } + if err := client.Head.Update(client.Refs, client.RootGoitPath, createOption); err != nil { + return fmt.Errorf("fail to update HEAD: %w", err) + } + } + + return nil + }, +} + +func init() { + rootCmd.AddCommand(switchCmd) + + switchCmd.Flags().StringVarP(&createOption, "create", "c", "", "create new branch") +} diff --git a/internal/store/head.go b/internal/store/head.go index daf3170..3aa665c 100644 --- a/internal/store/head.go +++ b/internal/store/head.go @@ -85,7 +85,13 @@ func newHead() *Head { return &Head{} } -func (h *Head) Update(rootGoitPath, newRef string) error { +func (h *Head) Update(refs *Refs, rootGoitPath, newRef string) error { + // check if branch exists + n := refs.getBranchPos(newRef) + if n == NewBranchFlag { + return fmt.Errorf("branch %s does not exist", newRef) + } + headPath := filepath.Join(rootGoitPath, "HEAD") if _, err := os.Stat(headPath); os.IsNotExist(err) { return errors.New("fail to find HEAD, cannot update") diff --git a/internal/store/refs.go b/internal/store/refs.go index 748d4b3..c92b605 100644 --- a/internal/store/refs.go +++ b/internal/store/refs.go @@ -134,7 +134,7 @@ func (r *Refs) RenameBranch(head *Head, rootGoitPath, newBranchName string) erro } // update HEAD - if err := head.Update(rootGoitPath, newBranchName); err != nil { + if err := head.Update(r, rootGoitPath, newBranchName); err != nil { return fmt.Errorf("fail to update HEAD: %w", err) }