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