aboutsummaryrefslogtreecommitdiffstats
path: root/input/prompt.go
blob: 2093695f667838e5d959fc95d5fa55e9df2a365b (plain) (blame)
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
package input

import (
	"bufio"
	"errors"
	"fmt"
	"net/url"
	"os"
	"sort"
	"strconv"
	"strings"
	"syscall"
	"time"

	"golang.org/x/crypto/ssh/terminal"

	"github.com/MichaelMure/git-bug/bridge/core/auth"
	"github.com/MichaelMure/git-bug/util/colors"
	"github.com/MichaelMure/git-bug/util/interrupt"
)

// PromptValidator is a validator for a user entry
// If complaint is "", value is considered valid, otherwise it's the error reported to the user
// If err != nil, a terminal error happened
type PromptValidator func(name string, value string) (complaint string, err error)

// Required is a validator preventing a "" value
func Required(name string, value string) (string, error) {
	if value == "" {
		return fmt.Sprintf("%s is empty", name), nil
	}
	return "", nil
}

// IsURL is a validator checking that the value is a fully formed URL
func IsURL(name string, value string) (string, error) {
	u, err := url.Parse(value)
	if err != nil {
		return fmt.Sprintf("%s is invalid: %v", name, err), nil
	}
	if u.Scheme == "" {
		return fmt.Sprintf("%s is missing a scheme", name), nil
	}
	if u.Host == "" {
		return fmt.Sprintf("%s is missing a host", name), nil
	}
	return "", nil
}

func Prompt(prompt, name string, validators ...PromptValidator) (string, error) {
	return PromptDefault(prompt, name, "", validators...)
}

func PromptDefault(prompt, name, preValue string, validators ...PromptValidator) (string, error) {
loop:
	for {
		if preValue != "" {
			_, _ = fmt.Fprintf(os.Stderr, "%s [%s]: ", prompt, preValue)
		} else {
			_, _ = fmt.Fprintf(os.Stderr, "%s: ", prompt)
		}

		line, err := bufio.NewReader(os.Stdin).ReadString('\n')
		if err != nil {
			return "", err
		}

		line = strings.TrimSpace(line)

		if preValue != "" && line == "" {
			line = preValue
		}

		for _, validator := range validators {
			complaint, err := validator(name, line)
			if err != nil {
				return "", err
			}
			if complaint != "" {
				_, _ = fmt.Fprintln(os.Stderr, complaint)
				continue loop
			}
		}

		return line, nil
	}
}

func PromptPassword(prompt, name string, validators ...PromptValidator) (string, error) {
	termState, err := terminal.GetState(syscall.Stdin)
	if err != nil {
		return "", err
	}

	cancel := interrupt.RegisterCleaner(func() error {
		return terminal.Restore(syscall.Stdin, termState)
	})
	defer cancel()

loop:
	for {
		_, _ = fmt.Fprintf(os.Stderr, "%s: ", prompt)

		bytePassword, err := terminal.ReadPassword(syscall.Stdin)
		// new line for coherent formatting, ReadPassword clip the normal new line
		// entered by the user
		fmt.Println()

		if err != nil {
			return "", err
		}

		pass := string(bytePassword)

		for _, validator := range validators {
			complaint, err := validator(name, pass)
			if err != nil {
				return "", err
			}
			if complaint != "" {
				_, _ = fmt.Fprintln(os.Stderr, complaint)
				continue loop
			}
		}

		return pass, nil
	}
}

func PromptChoice(prompt string, choices []string) (int, error) {
	for {
		for i, choice := range choices {
			_, _ = fmt.Fprintf(os.Stderr, "[%d]: %s\n", i+1, choice)
		}
		_, _ = fmt.Fprintf(os.Stderr, "%s: ", prompt)

		line, err := bufio.NewReader(os.Stdin).ReadString('\n')
		fmt.Println()
		if err != nil {
			return 0, err
		}

		line = strings.TrimSpace(line)

		index, err := strconv.Atoi(line)
		if err != nil || index < 1 || index > len(choices) {
			_, _ = fmt.Fprintf(os.Stderr, "invalid input")
			continue
		}

		return index, nil
	}
}

func PromptURLWithRemote(prompt, name string, validRemotes []string, validators ...PromptValidator) (string, error) {
	if len(validRemotes) == 0 {
		return Prompt(prompt, name, validators...)
	}

	sort.Strings(validRemotes)

	for {
		_, _ = fmt.Fprintln(os.Stderr, "\nDetected projects:")

		for i, remote := range validRemotes {
			_, _ = fmt.Fprintf(os.Stderr, "[%d]: %v\n", i+1, remote)
		}

		_, _ = fmt.Fprintf(os.Stderr, "\n[0]: Another project\n\n")
		_, _ = fmt.Fprintf(os.Stderr, "Select option: ")

		line, err := bufio.NewReader(os.Stdin).ReadString('\n')
		if err != nil {
			return "", err
		}

		line = strings.TrimSpace(line)

		index, err := strconv.Atoi(line)
		if err != nil || index < 0 || index > len(validRemotes) {
			_, _ = fmt.Fprintf(os.Stderr, "invalid input")
			continue
		}

		// if user want to enter another project url break this loop
		if index == 0 {
			break
		}

		return validRemotes[index-1], nil
	}

	return Prompt(prompt, name, validators...)
}

var ErrDirectPrompt = errors.New("direct prompt selected")
var ErrInteractiveCreation = errors.New("interactive creation selected")

func PromptCredential(target, name string, credentials []auth.Credential) (auth.Credential, error) {
	if len(credentials) == 0 {
		return nil, nil
	}

	sort.Sort(auth.ById(credentials))

	for {
		_, _ = fmt.Fprintf(os.Stderr, "[1]: enter my %s\n", name)

		_, _ = fmt.Fprintln(os.Stderr)
		_, _ = fmt.Fprintf(os.Stderr, "Existing %s for %s:", name, target)

		for i, cred := range credentials {
			meta := make([]string, 0, len(cred.Metadata()))
			for k, v := range cred.Metadata() {
				meta = append(meta, k+":"+v)
			}
			sort.Strings(meta)
			metaFmt := strings.Join(meta, ",")

			fmt.Printf("[%d]: %s => (%s) (%s)\n",
				i+2,
				colors.Cyan(cred.ID().Human()),
				metaFmt,
				cred.CreateTime().Format(time.RFC822),
			)
		}

		_, _ = fmt.Fprintln(os.Stderr)
		_, _ = fmt.Fprintf(os.Stderr, "Select option: ")

		line, err := bufio.NewReader(os.Stdin).ReadString('\n')
		_, _ = fmt.Fprintln(os.Stderr)
		if err != nil {
			return nil, err
		}

		line = strings.TrimSpace(line)
		index, err := strconv.Atoi(line)
		if err != nil || index < 1 || index > len(credentials)+1 {
			_, _ = fmt.Fprintln(os.Stderr, "invalid input")
			continue
		}

		switch index {
		case 1:
			return nil, ErrDirectPrompt
		default:
			return credentials[index-2], nil
		}
	}
}

func PromptCredentialWithInteractive(target, name string, credentials []auth.Credential) (auth.Credential, error) {
	sort.Sort(auth.ById(credentials))

	for {
		_, _ = fmt.Fprintf(os.Stderr, "[1]: enter my %s\n", name)
		_, _ = fmt.Fprintf(os.Stderr, "[2]: interactive %s creation\n", name)

		if len(credentials) > 0 {
			_, _ = fmt.Fprintln(os.Stderr)
			_, _ = fmt.Fprintf(os.Stderr, "Existing %s for %s:", name, target)

			for i, cred := range credentials {
				meta := make([]string, 0, len(cred.Metadata()))
				for k, v := range cred.Metadata() {
					meta = append(meta, k+":"+v)
				}
				sort.Strings(meta)
				metaFmt := strings.Join(meta, ",")

				fmt.Printf("[%d]: %s => (%s) (%s)\n",
					i+2,
					colors.Cyan(cred.ID().Human()),
					metaFmt,
					cred.CreateTime().Format(time.RFC822),
				)
			}
		}

		_, _ = fmt.Fprintln(os.Stderr)
		_, _ = fmt.Fprintf(os.Stderr, "Select option: ")

		line, err := bufio.NewReader(os.Stdin).ReadString('\n')
		_, _ = fmt.Fprintln(os.Stderr)
		if err != nil {
			return nil, err
		}

		line = strings.TrimSpace(line)
		index, err := strconv.Atoi(line)
		if err != nil || index < 1 || index > len(credentials)+1 {
			_, _ = fmt.Fprintln(os.Stderr, "invalid input")
			continue
		}

		switch index {
		case 1:
			return nil, ErrDirectPrompt
		case 2:
			return nil, ErrInteractiveCreation
		default:
			return credentials[index-3], nil
		}
	}
}