1package commands
2
3import (
4 "github.com/spf13/cobra"
5
6 "github.com/MichaelMure/git-bug/cache"
7 "github.com/MichaelMure/git-bug/commands/select"
8 "github.com/MichaelMure/git-bug/input"
9 "github.com/MichaelMure/git-bug/util/interrupt"
10)
11
12type commentAddOptions struct {
13 messageFile string
14 message string
15}
16
17func newCommentAddCommand() *cobra.Command {
18 env := newEnv()
19 options := commentAddOptions{}
20
21 cmd := &cobra.Command{
22 Use: "add [<id>]",
23 Short: "Add a new comment to a bug.",
24 PreRunE: loadRepoEnsureUser(env),
25 RunE: func(cmd *cobra.Command, args []string) error {
26 return runCommentAdd(env, options, args)
27 },
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
39 return cmd
40}
41
42func runCommentAdd(env *Env, opts commentAddOptions, args []string) error {
43 backend, err := cache.NewRepoCache(env.repo)
44 if err != nil {
45 return err
46 }
47 defer backend.Close()
48 interrupt.RegisterCleaner(backend.Close)
49
50 b, args, err := _select.ResolveBug(backend, args)
51 if err != nil {
52 return err
53 }
54
55 if opts.messageFile != "" && opts.message == "" {
56 opts.message, err = input.BugCommentFileInput(opts.messageFile)
57 if err != nil {
58 return err
59 }
60 }
61
62 if opts.messageFile == "" && opts.message == "" {
63 opts.message, err = input.BugCommentEditorInput(backend, "")
64 if err == input.ErrEmptyMessage {
65 env.err.Println("Empty message, aborting.")
66 return nil
67 }
68 if err != nil {
69 return err
70 }
71 }
72
73 _, err = b.AddComment(opts.message)
74 if err != nil {
75 return err
76 }
77
78 return b.Commit()
79}