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