1package commands
 2
 3import (
 4	"github.com/spf13/cobra"
 5
 6	"github.com/MichaelMure/git-bug/input"
 7)
 8
 9type addOptions struct {
10	title       string
11	message     string
12	messageFile string
13}
14
15func newAddCommand() *cobra.Command {
16	env := newEnv()
17	options := addOptions{}
18
19	cmd := &cobra.Command{
20		Use:      "add",
21		Short:    "Create a new bug.",
22		PreRunE:  loadBackendEnsureUser(env),
23		PostRunE: closeBackend(env),
24		RunE: func(cmd *cobra.Command, args []string) error {
25			return runAdd(env, options)
26		},
27	}
28
29	flags := cmd.Flags()
30	flags.SortFlags = false
31
32	flags.StringVarP(&options.title, "title", "t", "",
33		"Provide a title to describe the issue")
34	flags.StringVarP(&options.message, "message", "m", "",
35		"Provide a message to describe the issue")
36	flags.StringVarP(&options.messageFile, "file", "F", "",
37		"Take the message from the given file. Use - to read the message from the standard input")
38
39	return cmd
40}
41
42func runAdd(env *Env, opts addOptions) error {
43	var err error
44	if opts.messageFile != "" && opts.message == "" {
45		opts.title, opts.message, err = input.BugCreateFileInput(opts.messageFile)
46		if err != nil {
47			return err
48		}
49	}
50
51	if opts.messageFile == "" && (opts.message == "" || opts.title == "") {
52		opts.title, opts.message, err = input.BugCreateEditorInput(env.backend, opts.title, opts.message)
53
54		if err == input.ErrEmptyTitle {
55			env.out.Println("Empty title, aborting.")
56			return nil
57		}
58		if err != nil {
59			return err
60		}
61	}
62
63	b, _, err := env.backend.NewBug(opts.title, opts.message)
64	if err != nil {
65		return err
66	}
67
68	env.out.Printf("%s created\n", b.Id().Human())
69
70	return nil
71}