diff --git a/cmd/mg/cmd/register.go b/cmd/mg/cmd/register.go index 3160b6c..0026174 100644 --- a/cmd/mg/cmd/register.go +++ b/cmd/mg/cmd/register.go @@ -20,6 +20,9 @@ var registerCmd = &cobra.Command{ } if len(args) == 1 { path = args[0] + } else if len(args) > 1 { + log.Println("too many arguments") + os.Exit(1) } r, err := git.PlainOpenWithOptions(path, &(git.PlainOpenOptions{DetectDotGit: true})) if err != nil { diff --git a/cmd/mg/cmd/unregister.go b/cmd/mg/cmd/unregister.go index 223f97c..70386a1 100644 --- a/cmd/mg/cmd/unregister.go +++ b/cmd/mg/cmd/unregister.go @@ -1,17 +1,57 @@ package cmd import ( - "fmt" + "log" + "os" + git "github.com/go-git/go-git/v5" "github.com/spf13/cobra" ) // unregisterCmd represents the unregister command var unregisterCmd = &cobra.Command{ Use: "unregister", - Short: "remove the current repo from the config", - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("unregister called") + Short: "add current path to list of repos", + Run: func(_ *cobra.Command, args []string) { + conf := GetConfig() + path, err := os.Getwd() + if err != nil { + log.Println(err) + os.Exit(1) + } + if len(args) == 1 { + path = args[0] + err = conf.DelRepo(path) + if err != nil { + log.Println(err) + os.Exit(1) + } + return + } else if len(args) > 1 { + log.Println("too many arguments") + os.Exit(1) + } + r, err := git.PlainOpenWithOptions(path, &(git.PlainOpenOptions{DetectDotGit: true})) + if err != nil { + log.Println(err) + os.Exit(1) + } + newPath, err := r.Worktree() + if err != nil { + log.Println(err) + os.Exit(1) + } + path = newPath.Filesystem.Root() + err = conf.DelRepo(path) + if err != nil { + log.Println(err) + os.Exit(1) + } + err = conf.Save() + if err != nil { + log.Println(err) + os.Exit(1) + } }, } diff --git a/parse/mgconf.go b/parse/mgconf.go index d24eb2a..4a3cedb 100644 --- a/parse/mgconf.go +++ b/parse/mgconf.go @@ -7,6 +7,8 @@ import ( "path/filepath" ) +var errAlreadyRegistered = os.ErrExist + // MGConfig is the struct that represents the mgconfig file // It contains a slice of Repo structs and a map of aliases // The aliases map is a map of strings to strings, where the key is the alias @@ -27,8 +29,25 @@ func (m MGConfig) GetRepoPaths() []string { return paths } -func (m *MGConfig) AddRepo(path, remote string) { +func (m *MGConfig) DelRepo(path string) error { + for i, v := range m.Repos { + if v.Path == path { + m.Repos = append(m.Repos[:i], m.Repos[i+1:]...) + return nil + } + } + return os.ErrNotExist +} + +func (m *MGConfig) AddRepo(path, remote string) error { + for _, v := range m.Repos { + if v.Path == path { + return errAlreadyRegistered + } + } + m.Repos = append(m.Repos, Repo{Path: path, Remote: remote}) + return nil } // LoadMGConfig loads the mgconfig file from the XDG_CONFIG_HOME directory