-
Notifications
You must be signed in to change notification settings - Fork 0
/
author.go
83 lines (69 loc) 路 2 KB
/
author.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
/*
Copyright 漏 2021 Paul Ebose <paulebose@gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package internal
import (
"math/rand"
"strings"
"time"
"unicode"
"github.com/AlecAivazis/survey/v2"
"github.com/docker/docker/pkg/namesgenerator"
)
type Author struct {
ID, Name string
Notes []string
}
// NewAuthor creates and returns a new author.
// It returns an error if any.
func NewAuthor() (Author, error) {
var author Author
prompt := &survey.Input{Message: "Enter Author name:"}
if err := survey.AskOne(prompt, &author.Name); err != nil {
return author, err
}
author.Name = normalize(author.Name)
if author.Name == "" {
rand.Seed(time.Now().UnixNano())
au := strings.Split(namesgenerator.GetRandomName(0), "_")
// capitalize first letters.
au[0] = strings.ToUpper(string(au[0][0])) + au[0][1:]
au[1] = strings.ToUpper(string(au[1][0])) + au[1][1:]
author.Name = strings.Join(au, " ")
}
return author, nil
}
// normalize returns the string with extra spaces
// and non-alphanumeric characters removed.
func normalize(s string) string {
s = strings.TrimSpace(s)
if len(s) == 0 {
return ""
}
buf := make([]rune, 0, len(s))
addSpace := false
// must be alpha numeric.
for _, r := range s {
if unicode.IsLetter(r) || unicode.IsNumber(r) {
buf = append(buf, r)
addSpace = true
continue
}
if addSpace {
buf = append(buf, ' ')
addSpace = false
}
}
s = strings.TrimSpace(string(buf))
return s
}