From f9b18d88d7608c291b0d80dfcec06368a467aa1a Mon Sep 17 00:00:00 2001 From: Henrique Dias Date: Mon, 7 Jan 2019 23:04:56 +0000 Subject: [PATCH] feat: finish users import and improve error printing License: MIT Signed-off-by: Henrique Dias --- cmd/users_import.go | 36 +++++++++++++++++++++++++++++------- cmd/utils.go | 4 +++- 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/cmd/users_import.go b/cmd/users_import.go index 6b08952a..82af8389 100644 --- a/cmd/users_import.go +++ b/cmd/users_import.go @@ -12,7 +12,7 @@ import ( func init() { usersCmd.AddCommand(usersImportCmd) - usersImportCmd.Flags().Bool("overwrite", false, "overwrite existing users,") + usersImportCmd.Flags().Bool("overwrite", false, "overwrite users with the same id/username combo") } var usersImportCmd = &cobra.Command{ @@ -24,22 +24,44 @@ var usersImportCmd = &cobra.Command{ checkErr(err) defer fd.Close() - list := []users.User{} + list := []*users.User{} err = json.NewDecoder(fd).Decode(&list) checkErr(err) + for _, user := range list { + err = user.Clean("") + checkErr(err) + } + overwrite := mustGetBool(cmd, "overwrite") for _, user := range list { - // TODO: check for ID/Username conflicts too. - _, err := d.store.Users.Get("", user.ID) - if err == nil && !overwrite { - checkErr(errors.New("user " + strconv.Itoa(int(user.ID)) + " is already registred")) + old, err := d.store.Users.Get("", user.ID) + + // User exists in DB. + if err == nil { + if !overwrite { + checkErr(errors.New("user " + strconv.Itoa(int(user.ID)) + " is already registred")) + } + + // If the usernames mismatch, check if there is another one in the DB + // with the new username. If there is, print an error and cancel the + // operation + if user.Username != old.Username { + conflictuous, err := d.store.Users.Get("", user.Username) + if err == nil { + checkErr(usernameConflictError(user.Username, conflictuous.ID, user.ID)) + } + } } - err = d.store.Users.Save(&user) + err = d.store.Users.Save(user) checkErr(err) } }, pythonConfig{}), } + +func usernameConflictError(username string, original, new uint) error { + return errors.New("can't import user with ID " + strconv.Itoa(int(new)) + " and username \"" + username + "\" because the username is already registred with the user " + strconv.Itoa(int(original))) +} diff --git a/cmd/utils.go b/cmd/utils.go index 8eac6407..b1c4c25e 100644 --- a/cmd/utils.go +++ b/cmd/utils.go @@ -2,6 +2,7 @@ package cmd import ( "crypto/rand" + "fmt" "log" "os" @@ -39,7 +40,8 @@ func vadd(f *pflag.FlagSet, k string, i interface{}, u string) { func checkErr(err error) { if err != nil { - panic(err) + fmt.Println(err) + os.Exit(1) } }