/
coauthors_add.go
97 lines (82 loc) · 2.4 KB
/
coauthors_add.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package cmd
import (
"fmt"
"github.com/davidalpert/go-git-mob/internal/authors"
"github.com/davidalpert/go-git-mob/internal/gitConfig"
"github.com/davidalpert/go-printers/v1"
"github.com/spf13/cobra"
"net/mail"
"strings"
)
type CoauthorsAddOptions struct {
*printers.PrinterOptions
AllCoAuthorsByInitials map[string]authors.Author
Author authors.Author
AuthorInitials string
}
func NewCoauthorsAddOptions(s printers.IOStreams) *CoauthorsAddOptions {
return &CoauthorsAddOptions{
PrinterOptions: printers.NewPrinterOptions().WithStreams(s).WithDefaultTableWriter().WithDefaultOutput("text"),
}
}
func NewCmdCoauthorsAdd(s printers.IOStreams) *cobra.Command {
o := NewCoauthorsAddOptions(s)
var cmd = &cobra.Command{
Use: "add <initials> <name> <email_address>",
Short: "add a new co-authors to the list of co-authors available to git-mob",
Args: cobra.ExactArgs(3),
RunE: func(cmd *cobra.Command, args []string) error {
if err := o.Complete(cmd, args); err != nil {
return err
}
if err := o.Validate(); err != nil {
return err
}
return o.Run()
},
}
o.AddPrinterFlags(cmd.Flags())
return cmd
}
// Complete the options
func (o *CoauthorsAddOptions) Complete(cmd *cobra.Command, args []string) error {
o.AuthorInitials = args[0]
o.Author = authors.Author{
Name: args[1],
Email: args[2],
}
if allCoAuthorsByInitials, err := gitConfig.ReadAllCoAuthorsFromFile(); err != nil {
return err
} else {
o.AllCoAuthorsByInitials = allCoAuthorsByInitials
}
return nil
}
// Validate the options
func (o *CoauthorsAddOptions) Validate() error {
if _, err := mail.ParseAddress(o.Author.Email); err != nil {
return fmt.Errorf("invalid email address: %v", err)
}
var foundExisting = ""
var foundAs = ""
for ii, a := range o.AllCoAuthorsByInitials {
if strings.EqualFold(o.Author.Email, a.Email) {
foundExisting = a.Email
foundAs = ii
} else if strings.EqualFold(o.AuthorInitials, ii) {
foundExisting = ii
foundAs = a.Email
}
}
if foundExisting != "" {
return fmt.Errorf("coauthor '%s' already exists in '~/.git-coauthors' as '%s'", foundExisting, foundAs)
}
return o.PrinterOptions.Validate()
}
// Run the command
func (o *CoauthorsAddOptions) Run() error {
o.AllCoAuthorsByInitials[o.AuthorInitials] = o.Author
return authors.WriteCoauthorsContent(authors.CoAuthorsFileContent{
CoAuthorsByInitial: o.AllCoAuthorsByInitials,
})
}