@@ -2,7 +2,6 @@ package main
22
33import (
44 "bufio"
5- "flag"
65 "fmt"
76 "github.com/devlights/try-golang/lib"
87 "log"
@@ -11,9 +10,16 @@ import (
1110 "strings"
1211)
1312
14- var mapping = make (lib.SampleMapping )
13+ var (
14+ args * Args
15+ mapping lib.SampleMapping
16+ )
1517
1618func init () {
19+ args = NewArgs ()
20+ args .Parse ()
21+
22+ mapping = lib .NewSampleMapping ()
1723 mapping .MakeMapping ()
1824}
1925
@@ -34,15 +40,30 @@ func printAllExampleNames() {
3440 }
3541}
3642
37- func main () {
38- var (
39- onetime = flag .Bool ("onetime" , false , "run only one time" )
40- showNames = flag .Bool ("list" , false , "show all example names" )
41- )
43+ func makeCandidates (userInput string ) []string {
44+ candidates := make ([]string , 0 , len (mapping ))
45+ for k := range mapping {
46+ if strings .Contains (k , userInput ) {
47+ candidates = append (candidates , k )
48+ }
49+ }
4250
43- flag .Parse ()
51+ return candidates
52+ }
4453
45- if * showNames {
54+ func exec (target string ) error {
55+ if v , ok := mapping [target ]; ok {
56+ fmt .Printf ("[Name] %q\n " , target )
57+ if err := v (); err != nil {
58+ return err
59+ }
60+ }
61+
62+ return nil
63+ }
64+
65+ func main () {
66+ if args .ShowNames {
4667 printAllExampleNames ()
4768 return
4869 }
@@ -66,37 +87,43 @@ func main() {
6687 break
6788 }
6889
69- candidates = make ([]string , 0 , len (mapping ))
70- for k := range mapping {
71- if strings .Contains (k , userInput ) {
72- candidates = append (candidates , k )
73- }
74- }
75-
90+ candidates = makeCandidates (userInput )
7691 numberOfCandidate = len (candidates )
92+
7793 switch {
7894 case numberOfCandidate == 0 :
7995 fmt .Printf ("Not found...Try Again" )
8096 goto nextinput
8197 case numberOfCandidate == 1 :
8298 userInput = candidates [0 ]
83- if v , ok := mapping [userInput ]; ok {
84- fmt .Printf ("[Name] %q\n " , userInput )
85- if err := v (); err != nil {
86- log .Fatal (err )
87- }
99+ if err := exec (userInput ); err != nil {
100+ log .Fatal (err )
88101 }
89102 case 1 < numberOfCandidate :
90- fmt .Printf ("There's %d candidates found\n " , len (candidates ))
91-
92- for _ , item := range candidates {
93- fmt .Printf ("\t %s\n " , item )
103+ isPerfectMatchFound := false
104+ for _ , c := range candidates {
105+ if c == userInput {
106+ if err := exec (userInput ); err != nil {
107+ log .Fatal (err )
108+ }
109+
110+ isPerfectMatchFound = true
111+ break
112+ }
94113 }
95114
96- goto nextinput
115+ if ! isPerfectMatchFound {
116+ fmt .Printf ("There's %d candidates found\n " , len (candidates ))
117+
118+ for _ , item := range candidates {
119+ fmt .Printf ("\t %s\n " , item )
120+ }
121+
122+ goto nextinput
123+ }
97124 }
98125
99- if * onetime {
126+ if args . OneTime {
100127 break
101128 }
102129
0 commit comments