-
Notifications
You must be signed in to change notification settings - Fork 2
/
survey.go
132 lines (110 loc) · 2.58 KB
/
survey.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package create
import (
"os"
"time"
"github.com/AlecAivazis/survey/v2"
"github.com/cli/cli/v2/pkg/surveyext"
"github.com/valeriobelli/gh-milestone/internal/pkg/domain/github"
)
type SurveyAnswers struct {
Confirm bool
Description string
DueDate time.Time
Title string
}
func (sa SurveyAnswers) getTime() *time.Time {
if sa.DueDate.IsZero() {
return nil
}
return &sa.DueDate
}
type Flags struct {
Description string
DueDate *time.Time
Title string
}
func (f Flags) getDueDate() time.Time {
if f.DueDate == nil {
return time.Time{}
}
return *f.DueDate
}
type Survey struct {
answers *SurveyAnswers
questions []*survey.Question
}
func NewSurvey(flags Flags) *Survey {
var questions = []*survey.Question{}
requiredFieldsAreEmpty := len(flags.Title) == 0
if flags.Title == "" {
questions = append(questions, &survey.Question{
Name: "title",
Prompt: &survey.Input{Message: "Title"},
Validate: survey.Required,
})
}
if flags.Description == "" && requiredFieldsAreEmpty {
questions = append(questions, &survey.Question{
Name: "description",
Prompt: &surveyext.GhEditor{
BlankAllowed: true,
Editor: &survey.Editor{
FileName: "*.md",
Message: "Description",
},
EditorCommand: os.Getenv("EDITOR") + " --wait",
},
})
}
if flags.DueDate == nil && requiredFieldsAreEmpty {
questions = append(questions, &survey.Question{
Name: "dueDate",
Prompt: &survey.Input{Message: "Due date [yyyy-mm-dd]"},
Validate: survey.Validator(func(ans interface{}) error {
switch dueDate := ans.(type) {
case string:
parseDueDate, _ := github.NewDueDate(dueDate)
if parseDueDate == nil {
return nil
}
return nil
default:
return nil
}
}),
Transform: survey.Transformer(func(ans interface{}) (newAns interface{}) {
switch dueDate := ans.(type) {
case string:
parsedDate, err := github.NewDueDate(dueDate)
if err != nil {
return time.Time{}
}
return parsedDate.Time
default:
return nil
}
}),
})
}
if len(questions) > 0 {
questions = append(questions, &survey.Question{
Name: "confirm",
Prompt: &survey.Confirm{
Message: "Do you want create the Milestone?",
},
})
}
return &Survey{
answers: &SurveyAnswers{
Confirm: !requiredFieldsAreEmpty,
Description: flags.Description,
DueDate: flags.getDueDate(),
Title: flags.Title,
},
questions: questions,
}
}
func (s Survey) Ask() (SurveyAnswers, error) {
err := survey.Ask(s.questions, s.answers)
return *s.answers, err
}