bug_comment_add.go

 1package bugcmd
 2
 3import (
 4	"github.com/spf13/cobra"
 5
 6	buginput "github.com/MichaelMure/git-bug/commands/bug/input"
 7	"github.com/MichaelMure/git-bug/commands/execenv"
 8	"github.com/MichaelMure/git-bug/util/text"
 9)
10
11type bugCommentNewOptions struct {
12	messageFile    string
13	message        string
14	nonInteractive bool
15}
16
17func newBugCommentNewCommand(env *execenv.Env) *cobra.Command {
18	options := bugCommentNewOptions{}
19
20	cmd := &cobra.Command{
21		Use:     "new [BUG_ID]",
22		Short:   "Add a new comment to a bug",
23		PreRunE: execenv.LoadBackendEnsureUser(env),
24		RunE: execenv.CloseBackend(env, func(cmd *cobra.Command, args []string) error {
25			return runBugCommentNew(env, options, args)
26		}),
27		ValidArgsFunction: BugCompletion(env),
28	}
29
30	flags := cmd.Flags()
31	flags.SortFlags = false
32
33	flags.StringVarP(&options.messageFile, "file", "F", "",
34		"Take the message from the given file. Use - to read the message from the standard input")
35
36	flags.StringVarP(&options.message, "message", "m", "",
37		"Provide the new message from the command line")
38	flags.BoolVar(&options.nonInteractive, "non-interactive", false, "Do not ask for user input")
39
40	return cmd
41}
42
43func runBugCommentNew(env *execenv.Env, opts bugCommentNewOptions, args []string) error {
44	b, args, err := ResolveSelected(env.Backend, args)
45	if err != nil {
46		return err
47	}
48
49	if opts.messageFile != "" && opts.message == "" {
50		opts.message, err = buginput.BugCommentFileInput(opts.messageFile)
51		if err != nil {
52			return err
53		}
54	}
55
56	if opts.messageFile == "" && opts.message == "" {
57		if opts.nonInteractive {
58			env.Err.Println("No message given. Use -m or -F option to specify a message. Aborting.")
59			return nil
60		}
61		opts.message, err = buginput.BugCommentEditorInput(env.Backend, "")
62		if err == buginput.ErrEmptyMessage {
63			env.Err.Println("Empty message, aborting.")
64			return nil
65		}
66		if err != nil {
67			return err
68		}
69	}
70
71	_, _, err = b.AddComment(text.Cleanup(opts.message))
72	if err != nil {
73		return err
74	}
75
76	return b.Commit()
77}