-
Notifications
You must be signed in to change notification settings - Fork 6
/
name.go
63 lines (50 loc) · 1.21 KB
/
name.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
package question
import (
"context"
"fmt"
"path"
"regexp"
"strings"
"github.com/AlecAivazis/survey/v2"
"github.com/platformsh/platformify/internal/question/models"
)
type Name struct{}
var (
invalidChars = regexp.MustCompile("[^a-z0-9_-]")
consecutiveDashes = regexp.MustCompile("-+")
)
func (q *Name) Ask(ctx context.Context) error {
answers, ok := models.FromContext(ctx)
if !ok {
return nil
}
if answers.Name != "" {
// Skip the step
return nil
}
question := &survey.Input{
Message: "Tell us your project's application name:", Default: slugify(path.Base(answers.WorkingDirectory)),
}
var name string
err := survey.AskOne(question, &name, survey.WithValidator(survey.Required), survey.WithValidator(validSlug))
if err != nil {
return err
}
answers.Name = name
return nil
}
func slugify(s string) string {
return consecutiveDashes.ReplaceAllLiteralString(
invalidChars.ReplaceAllLiteralString(strings.ToLower(
strings.TrimSpace(s),
), "-"), "-")
}
func validSlug(val interface{}) error {
if val.(string) != slugify(val.(string)) {
return fmt.Errorf(
"%s: the name can only contain lowercase alphanumeric characters, dashes, or underscores",
val.(string),
)
}
return nil
}