Skip to content

Commit 794060c

Browse files
author
Pandademic
committedMay 27, 2022
diffrent , more sensible implementation of #1.
How? by having args as a slice that the CLI can acess , so an unlimetd number of arguments can be passed.[WIP]
1 parent 4e9aba9 commit 794060c

File tree

1 file changed

+37
-31
lines changed

1 file changed

+37
-31
lines changed
 

‎main.go

+37-31
Original file line numberDiff line numberDiff line change
@@ -3,24 +3,26 @@ package raspberry
33
import "os"
44
import "fmt"
55

6-
type Cli struct{
6+
type Cli struct {
77
AcceptedCommands []string
8-
HelpMsg string
9-
Version float64
8+
HelpMsg string
9+
Version float64
1010
}
11-
var(
12-
Command string
13-
FirstArg string
14-
SecondArg string
11+
12+
var (
13+
Command string
1514
argLength int
15+
Args []string
1616
)
17+
1718
type fn func()
18-
func (c *Cli) SetHandler(cmd string,fun fn) {
19+
20+
func (c *Cli) SetHandler(cmd string, fun fn) {
1921
if Command == cmd {
2022
fun()
21-
}
23+
}
2224
}
23-
func contains(str string,s []string) bool {
25+
func contains(str string, s []string) bool {
2426
for _, v := range s {
2527
if v == str {
2628
return true
@@ -29,29 +31,33 @@ func contains(str string,s []string) bool {
2931

3032
return false
3133
}
32-
func (c *Cli) PrintHelp(){
34+
func (c *Cli) PrintHelp() {
3335
fmt.Println(c.HelpMsg)
3436
}
35-
func (c *Cli) PrintVersion(){
37+
func (c *Cli) PrintVersion() {
3638
fmt.Println(c.Version)
3739
}
38-
func (c *Cli) Setup(){
39-
argLength = len(os.Args)
40-
if argLength > 1 {
41-
if(contains(os.Args[1],c.AcceptedCommands)){
42-
Command = os.Args[1]
43-
FirstArg = os.Args[2]
44-
SecondArg = os.Args[3]
45-
}else{
46-
fmt.Println("Command not found: ",os.Args[1])
47-
}
48-
}else{
49-
fmt.Println("Not enough arguments")
50-
os.Exit(1)
51-
}
52-
// set default cmd's
53-
c.SetHandler("-v",c.PrintVersion)
54-
c.SetHandler("version",c.PrintVersion)
55-
c.SetHandler("-h",c.PrintHelp)
56-
c.SetHandler("help",c.PrintHelp)
40+
func shiftArgsDownward(arr []string) []string {
41+
arr = arr[2:]
42+
return arr
43+
}
44+
func (c *Cli) Setup() {
45+
argLength = len(os.Args)
46+
if argLength > 1 {
47+
if contains(os.Args[1], c.AcceptedCommands) {
48+
Command = os.Args[1]
49+
Args = os.Args
50+
shiftArgsDownward(Args)
51+
} else {
52+
fmt.Println("Command not found: ", os.Args[1])
53+
}
54+
} else {
55+
fmt.Println("Not enough arguments")
56+
os.Exit(1)
57+
}
58+
// set default cmd's
59+
c.SetHandler("-v", c.PrintVersion)
60+
c.SetHandler("version", c.PrintVersion)
61+
c.SetHandler("-h", c.PrintHelp)
62+
c.SetHandler("help", c.PrintHelp)
5763
}

0 commit comments

Comments
 (0)
Please sign in to comment.