aboutsummaryrefslogtreecommitdiffstats
path: root/commands/user
diff options
context:
space:
mode:
authorMichael Muré <batolettre@gmail.com>2022-09-10 11:09:19 +0200
committerMichael Muré <batolettre@gmail.com>2022-11-20 17:18:09 +0100
commitacc9a6f3a6df2961c3ae44352216d915cb9b5315 (patch)
treee159372673104ade1f15ddc1a84aa9da93e93552 /commands/user
parenta3fa445a9c76631c4cd16f93e1c1c68a954adef7 (diff)
downloadgit-bug-acc9a6f3a6df2961c3ae44352216d915cb9b5315.tar.gz
commands: reorg into different packages
Diffstat (limited to 'commands/user')
-rw-r--r--commands/user/user.go89
-rw-r--r--commands/user/user_adopt.go43
-rw-r--r--commands/user/user_new.go98
-rw-r--r--commands/user/user_new_test.go14
-rw-r--r--commands/user/user_show.go108
5 files changed, 352 insertions, 0 deletions
diff --git a/commands/user/user.go b/commands/user/user.go
new file mode 100644
index 00000000..191fb828
--- /dev/null
+++ b/commands/user/user.go
@@ -0,0 +1,89 @@
+package usercmd
+
+import (
+ "encoding/json"
+ "fmt"
+
+ "github.com/spf13/cobra"
+
+ json2 "github.com/MichaelMure/git-bug/commands/cmdjson"
+
+ "github.com/MichaelMure/git-bug/cache"
+ "github.com/MichaelMure/git-bug/commands/completion"
+ "github.com/MichaelMure/git-bug/commands/execenv"
+ "github.com/MichaelMure/git-bug/util/colors"
+)
+
+type userOptions struct {
+ format string
+}
+
+func NewUserCommand() *cobra.Command {
+ env := execenv.NewEnv()
+ options := userOptions{}
+
+ cmd := &cobra.Command{
+ Use: "user",
+ Short: "List identities",
+ PreRunE: execenv.LoadBackend(env),
+ RunE: execenv.CloseBackend(env, func(cmd *cobra.Command, args []string) error {
+ return runUser(env, options)
+ }),
+ }
+
+ cmd.AddCommand(newUserNewCommand())
+ cmd.AddCommand(newUserShowCommand())
+ cmd.AddCommand(newUserAdoptCommand())
+
+ flags := cmd.Flags()
+ flags.SortFlags = false
+
+ flags.StringVarP(&options.format, "format", "f", "default",
+ "Select the output formatting style. Valid values are [default,json]")
+ cmd.RegisterFlagCompletionFunc("format", completion.From([]string{"default", "json"}))
+
+ return cmd
+}
+
+func runUser(env *execenv.Env, opts userOptions) error {
+ ids := env.Backend.AllIdentityIds()
+ var users []*cache.IdentityExcerpt
+ for _, id := range ids {
+ user, err := env.Backend.ResolveIdentityExcerpt(id)
+ if err != nil {
+ return err
+ }
+ users = append(users, user)
+ }
+
+ switch opts.format {
+ case "json":
+ return userJsonFormatter(env, users)
+ case "default":
+ return userDefaultFormatter(env, users)
+ default:
+ return fmt.Errorf("unknown format %s", opts.format)
+ }
+}
+
+func userDefaultFormatter(env *execenv.Env, users []*cache.IdentityExcerpt) error {
+ for _, user := range users {
+ env.Out.Printf("%s %s\n",
+ colors.Cyan(user.Id.Human()),
+ user.DisplayName(),
+ )
+ }
+
+ return nil
+}
+
+func userJsonFormatter(env *execenv.Env, users []*cache.IdentityExcerpt) error {
+ jsonUsers := make([]json2.Identity, len(users))
+ for i, user := range users {
+ jsonUsers[i] = json2.NewIdentityFromExcerpt(user)
+ }
+
+ jsonObject, _ := json.MarshalIndent(jsonUsers, "", " ")
+ env.Out.Printf("%s\n", jsonObject)
+ return nil
+}
diff --git a/commands/user/user_adopt.go b/commands/user/user_adopt.go
new file mode 100644
index 00000000..f5944053
--- /dev/null
+++ b/commands/user/user_adopt.go
@@ -0,0 +1,43 @@
+package usercmd
+
+import (
+ "github.com/spf13/cobra"
+
+ "github.com/MichaelMure/git-bug/commands/completion"
+ "github.com/MichaelMure/git-bug/commands/execenv"
+)
+
+func newUserAdoptCommand() *cobra.Command {
+ env := execenv.NewEnv()
+
+ cmd := &cobra.Command{
+ Use: "adopt USER_ID",
+ Short: "Adopt an existing identity as your own",
+ Args: cobra.ExactArgs(1),
+ PreRunE: execenv.LoadBackend(env),
+ RunE: execenv.CloseBackend(env, func(cmd *cobra.Command, args []string) error {
+ return runUserAdopt(env, args)
+ }),
+ ValidArgsFunction: completion.User(env),
+ }
+
+ return cmd
+}
+
+func runUserAdopt(env *execenv.Env, args []string) error {
+ prefix := args[0]
+
+ i, err := env.Backend.ResolveIdentityPrefix(prefix)
+ if err != nil {
+ return err
+ }
+
+ err = env.Backend.SetUserIdentity(i)
+ if err != nil {
+ return err
+ }
+
+ env.Out.Printf("Your identity is now: %s\n", i.DisplayName())
+
+ return nil
+}
diff --git a/commands/user/user_new.go b/commands/user/user_new.go
new file mode 100644
index 00000000..d7224512
--- /dev/null
+++ b/commands/user/user_new.go
@@ -0,0 +1,98 @@
+package usercmd
+
+import (
+ "github.com/spf13/cobra"
+
+ "github.com/MichaelMure/git-bug/commands/execenv"
+ "github.com/MichaelMure/git-bug/commands/input"
+)
+
+type userNewOptions struct {
+ name string
+ email string
+ avatarURL string
+ nonInteractive bool
+}
+
+func newUserNewCommand() *cobra.Command {
+ env := execenv.NewEnv()
+
+ options := userNewOptions{}
+ cmd := &cobra.Command{
+ Use: "new",
+ Short: "Create a new identity",
+ PreRunE: execenv.LoadBackend(env),
+ RunE: execenv.CloseBackend(env, func(cmd *cobra.Command, args []string) error {
+ return runUserNew(env, options)
+ }),
+ }
+
+ flags := cmd.Flags()
+ flags.StringVarP(&options.name, "name", "n", "", "Name to identify the user")
+ flags.StringVarP(&options.email, "email", "e", "", "Email of the user")
+ flags.StringVarP(&options.avatarURL, "avatar", "a", "", "Avatar URL")
+ flags.BoolVar(&options.nonInteractive, "non-interactive", false, "Do not ask for user input")
+
+ return cmd
+}
+
+func runUserNew(env *execenv.Env, opts userNewOptions) error {
+
+ if !opts.nonInteractive && opts.name == "" {
+ preName, err := env.Backend.GetUserName()
+ if err != nil {
+ return err
+ }
+ opts.name, err = input.PromptDefault("Name", "name", preName, input.Required)
+ if err != nil {
+ return err
+ }
+ }
+
+ if !opts.nonInteractive && opts.email == "" {
+ preEmail, err := env.Backend.GetUserEmail()
+ if err != nil {
+ return err
+ }
+
+ opts.email, err = input.PromptDefault("Email", "email", preEmail, input.Required)
+ if err != nil {
+ return err
+ }
+ }
+
+ if !opts.nonInteractive && opts.avatarURL == "" {
+ var err error
+ opts.avatarURL, err = input.Prompt("Avatar URL", "avatar")
+ if err != nil {
+ return err
+ }
+ }
+
+ id, err := env.Backend.NewIdentityRaw(opts.name, opts.email, "", opts.avatarURL, nil, nil)
+ if err != nil {
+ return err
+ }
+
+ err = id.CommitAsNeeded()
+ if err != nil {
+ return err
+ }
+
+ set, err := env.Backend.IsUserIdentitySet()
+ if err != nil {
+ return err
+ }
+
+ if !set {
+ err = env.Backend.SetUserIdentity(id)
+ if err != nil {
+ return err
+ }
+ }
+
+ env.Err.Println()
+ env.Out.Println(id.Id())
+
+ return nil
+}
diff --git a/commands/user/user_new_test.go b/commands/user/user_new_test.go
new file mode 100644
index 00000000..619e5de6
--- /dev/null
+++ b/commands/user/user_new_test.go
@@ -0,0 +1,14 @@
+package usercmd
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/MichaelMure/git-bug/commands/bug/testenv"
+)
+
+func TestUserNewCommand(t *testing.T) {
+ _, userID := testenv.NewTestEnvAndUser(t)
+ require.Regexp(t, "[0-9a-f]{64}", userID)
+}
diff --git a/commands/user/user_show.go b/commands/user/user_show.go
new file mode 100644
index 00000000..36c09e8e
--- /dev/null
+++ b/commands/user/user_show.go
@@ -0,0 +1,108 @@
+package usercmd
+
+import (
+ "errors"
+ "fmt"
+ "strings"
+
+ "github.com/spf13/cobra"
+
+ "github.com/MichaelMure/git-bug/cache"
+ "github.com/MichaelMure/git-bug/commands/completion"
+ "github.com/MichaelMure/git-bug/commands/execenv"
+)
+
+type userShowOptions struct {
+ fields string
+}
+
+func newUserShowCommand() *cobra.Command {
+ env := execenv.NewEnv()
+ options := userShowOptions{}
+
+ cmd := &cobra.Command{
+ Use: "user show [USER_ID]",
+ Short: "Display a user identity",
+ PreRunE: execenv.LoadBackendEnsureUser(env),
+ RunE: execenv.CloseBackend(env, func(cmd *cobra.Command, args []string) error {
+ return runUserShow(env, options, args)
+ }),
+ ValidArgsFunction: completion.User(env),
+ }
+
+ flags := cmd.Flags()
+ flags.SortFlags = false
+
+ fields := []string{"email", "humanId", "id", "lastModification", "lastModificationLamports", "login", "metadata", "name"}
+ flags.StringVarP(&options.fields, "field", "f", "",
+ "Select field to display. Valid values are ["+strings.Join(fields, ",")+"]")
+ cmd.RegisterFlagCompletionFunc("field", completion.From(fields))
+
+ return cmd
+}
+
+func runUserShow(env *execenv.Env, opts userShowOptions, args []string) error {
+ if len(args) > 1 {
+ return errors.New("only one identity can be displayed at a time")
+ }
+
+ var id *cache.IdentityCache
+ var err error
+ if len(args) == 1 {
+ id, err = env.Backend.ResolveIdentityPrefix(args[0])
+ } else {
+ id, err = env.Backend.GetUserIdentity()
+ }
+
+ if err != nil {
+ return err
+ }
+
+ if opts.fields != "" {
+ switch opts.fields {
+ case "email":
+ env.Out.Printf("%s\n", id.Email())
+ case "login":
+ env.Out.Printf("%s\n", id.Login())
+ case "humanId":
+ env.Out.Printf("%s\n", id.Id().Human())
+ case "id":
+ env.Out.Printf("%s\n", id.Id())
+ case "lastModification":
+ env.Out.Printf("%s\n", id.LastModification().
+ Time().Format("Mon Jan 2 15:04:05 2006 +0200"))
+ case "lastModificationLamport":
+ for name, t := range id.LastModificationLamports() {
+ env.Out.Printf("%s\n%d\n", name, t)
+ }
+ case "metadata":
+ for key, value := range id.ImmutableMetadata() {
+ env.Out.Printf("%s\n%s\n", key, value)
+ }
+ case "name":
+ env.Out.Printf("%s\n", id.Name())
+
+ default:
+ return fmt.Errorf("\nUnsupported field: %s\n", opts.fields)
+ }
+
+ return nil
+ }
+
+ env.Out.Printf("Id: %s\n", id.Id())
+ env.Out.Printf("Name: %s\n", id.Name())
+ env.Out.Printf("Email: %s\n", id.Email())
+ env.Out.Printf("Login: %s\n", id.Login())
+ env.Out.Printf("Last modification: %s\n", id.LastModification().Time().Format("Mon Jan 2 15:04:05 2006 +0200"))
+ env.Out.Printf("Last moditication (lamport):\n")
+ for name, t := range id.LastModificationLamports() {
+ env.Out.Printf("\t%s: %d", name, t)
+ }
+ env.Out.Println("Metadata:")
+ for key, value := range id.ImmutableMetadata() {
+ env.Out.Printf(" %s --> %s\n", key, value)
+ }
+ // env.Out.Printf("Protected: %v\n", id.IsProtected())
+
+ return nil
+}