1package bug
2
3import (
4 "errors"
5 "fmt"
6 "strings"
7
8 "github.com/MichaelMure/git-bug/repository"
9 "github.com/MichaelMure/git-bug/util/text"
10)
11
12type Person struct {
13 Name string `json:"name"`
14 Email string `json:"email"`
15 Login string `json:"login"`
16 AvatarUrl string `json:"avatar_url"`
17}
18
19// GetUser will query the repository for user detail and build the corresponding Person
20func GetUser(repo repository.Repo) (Person, error) {
21 name, err := repo.GetUserName()
22 if err != nil {
23 return Person{}, err
24 }
25 if name == "" {
26 return Person{}, errors.New("User name is not configured in git yet. Please use `git config --global user.name \"John Doe\"`")
27 }
28
29 email, err := repo.GetUserEmail()
30 if err != nil {
31 return Person{}, err
32 }
33 if email == "" {
34 return Person{}, errors.New("User name is not configured in git yet. Please use `git config --global user.email johndoe@example.com`")
35 }
36
37 return Person{Name: name, Email: email}, nil
38}
39
40// Match tell is the Person match the given query string
41func (p Person) Match(query string) bool {
42 query = strings.ToLower(query)
43
44 return strings.Contains(strings.ToLower(p.Name), query) ||
45 strings.Contains(strings.ToLower(p.Login), query)
46}
47
48func (p Person) Validate() error {
49 if text.Empty(p.Name) && text.Empty(p.Login) {
50 return fmt.Errorf("either name or login should be set")
51 }
52
53 if strings.Contains(p.Name, "\n") {
54 return fmt.Errorf("name should be a single line")
55 }
56
57 if !text.Safe(p.Name) {
58 return fmt.Errorf("name is not fully printable")
59 }
60
61 if strings.Contains(p.Login, "\n") {
62 return fmt.Errorf("login should be a single line")
63 }
64
65 if !text.Safe(p.Login) {
66 return fmt.Errorf("login is not fully printable")
67 }
68
69 if strings.Contains(p.Email, "\n") {
70 return fmt.Errorf("email should be a single line")
71 }
72
73 if !text.Safe(p.Email) {
74 return fmt.Errorf("email is not fully printable")
75 }
76
77 if p.AvatarUrl != "" && !text.ValidUrl(p.AvatarUrl) {
78 return fmt.Errorf("avatarUrl is not a valid URL")
79 }
80
81 return nil
82}
83
84func (p Person) DisplayName() string {
85 switch {
86 case p.Name == "" && p.Login != "":
87 return p.Login
88 case p.Name != "" && p.Login == "":
89 return p.Name
90 case p.Name != "" && p.Login != "":
91 return fmt.Sprintf("%s (%s)", p.Name, p.Login)
92 }
93
94 panic("invalid person data")
95}