-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathmain.go
More file actions
109 lines (97 loc) · 2.08 KB
/
main.go
File metadata and controls
109 lines (97 loc) · 2.08 KB
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
package main
import (
"bufio"
"errors"
"flag"
"fmt"
"io"
"os"
)
type config struct {
numTimes int
name string
}
var errInvalidPosArgSpecified = errors.New("More than one positional argument specified")
func getName(r io.Reader, w io.Writer) (string, error) {
scanner := bufio.NewScanner(r)
msg := "Your name please? Press the Enter key when done.\n"
fmt.Fprintf(w, msg)
scanner.Scan()
if err := scanner.Err(); err != nil {
return "", err
}
name := scanner.Text()
if len(name) == 0 {
return "", errors.New("You didn't enter your name")
}
return name, nil
}
func greetUser(c config, w io.Writer) {
msg := fmt.Sprintf("Nice to meet you %s\n", c.name)
for i := 0; i < c.numTimes; i++ {
fmt.Fprintf(w, msg)
}
}
func runCmd(r io.Reader, w io.Writer, c config) error {
var err error
if len(c.name) == 0 {
c.name, err = getName(r, w)
if err != nil {
return err
}
}
greetUser(c, w)
return nil
}
func validateArgs(c config) error {
if !(c.numTimes > 0) {
return errors.New("Must specify a number greater than 0")
}
return nil
}
func parseArgs(w io.Writer, args []string) (config, error) {
c := config{}
fs := flag.NewFlagSet("greeter", flag.ContinueOnError)
fs.SetOutput(w)
fs.Usage = func() {
var usageString = `
A greeter application which prints the name you entered a specified number of times.
Usage of %s: <options> [name]`
fmt.Fprintf(w, usageString, fs.Name())
fmt.Fprintln(w)
fmt.Fprintln(w)
fmt.Fprintln(w, "Options: ")
fs.PrintDefaults()
}
fs.IntVar(&c.numTimes, "n", 0, "Number of times to greet")
err := fs.Parse(args)
if err != nil {
return c, err
}
if fs.NArg() > 1 {
return c, errInvalidPosArgSpecified
}
if fs.NArg() == 1 {
c.name = fs.Arg(0)
}
return c, nil
}
func main() {
c, err := parseArgs(os.Stderr, os.Args[1:])
if err != nil {
if errors.Is(err, errInvalidPosArgSpecified) {
fmt.Fprintln(os.Stdout, err)
}
os.Exit(1)
}
err = validateArgs(c)
if err != nil {
fmt.Fprintln(os.Stdout, err)
os.Exit(1)
}
err = runCmd(os.Stdin, os.Stdout, c)
if err != nil {
fmt.Fprintln(os.Stdout, err)
os.Exit(1)
}
}