1+ package src
2+
3+ import (
4+ "flag"
5+ "fmt"
6+ "os"
7+ )
8+
9+ const (
10+ FLAG_F = iota // -f, --force
11+ FLAG_I // -i
12+ FLAG_R // -r, -R, --recursive
13+ FLAG_D // -d, --dir
14+ FLAG_V // -v, --verbose
15+ FLAG_HELP // --help, -h
16+ )
17+
18+ type Input struct {
19+ Files []string
20+ Flags []uint8 // tiny for less mem
21+ }
22+
23+
24+ type InputParser interface {
25+ HasFlag (uint8 ) bool
26+ }
27+
28+
29+ // NewInput creates a new Input struct and parses the command line arguments.
30+ // It returns the Input struct and an error if there is one.
31+ func NewInput () (* Input , error ) {
32+ args := os .Args [1 :]
33+
34+ if len (args ) == 0 {
35+ return nil , fmt .Errorf ("no arguments" )
36+ }
37+
38+ input := & Input {
39+ Files : make ([]string , 0 ),
40+ Flags : make ([]uint8 , 0 ),
41+ }
42+
43+ // set flag usage
44+ flag .Usage = Usage
45+
46+ var help = flag .Bool ("help" , false , "" )
47+ var version = flag .Bool ("version" , false , "" )
48+ var force = flag .Bool ("f" , false , "" )
49+ var forceShort = flag .Bool ("force" , false , "" )
50+ var recursive = flag .Bool ("recursive" , false , "" )
51+ var recursiveShort = flag .Bool ("r" , false , "" )
52+ var dir = flag .Bool ("dir" , false , "dir" )
53+ var dirShort = flag .Bool ("d" , false , "dir" )
54+ var verbose = flag .Bool ("verbose" , false , "" )
55+ var verboseShort = flag .Bool ("v" , false , "" )
56+ var i = flag .Bool ("i" , false , "i" )
57+
58+ flag .Parse ()
59+
60+ if * help {
61+ input .Flags = append (input .Flags , FLAG_HELP )
62+ return input , nil
63+ }
64+
65+ if * version {
66+ input .Flags = append (input .Flags , FLAG_V )
67+ return input , nil
68+ }
69+
70+ if * force || * forceShort {
71+ input .Flags = append (input .Flags , FLAG_F )
72+ }
73+
74+ if * recursive || * recursiveShort {
75+ input .Flags = append (input .Flags , FLAG_R )
76+ }
77+
78+ if * dir || * dirShort {
79+ input .Flags = append (input .Flags , FLAG_D )
80+ }
81+
82+ if * verbose || * verboseShort {
83+ input .Flags = append (input .Flags , FLAG_V )
84+ }
85+
86+ if * i {
87+ input .Flags = append (input .Flags , FLAG_I )
88+ }
89+
90+ input .Files = flag .Args ()
91+
92+ return input , nil
93+ }
94+
95+ // HasFlag returns true if the input has the flag.
96+ func (i * Input ) HasFlag (flag uint8 ) bool {
97+ for _ , f := range i .Flags {
98+ if f == flag {
99+ return true
100+ }
101+ }
102+ return false
103+ }
0 commit comments