feat: finish users import and improve error printing
License: MIT Signed-off-by: Henrique Dias <hacdias@gmail.com>
This commit is contained in:
parent
ac12619d20
commit
f9b18d88d7
@ -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)))
|
||||
}
|
||||
|
||||
@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user