-
Notifications
You must be signed in to change notification settings - Fork 0
/
gam.go
128 lines (106 loc) · 1.83 KB
/
gam.go
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
package main
import (
"flag"
"fmt"
"os"
"os/user"
"path/filepath"
"strings"
)
var usr, _ = user.Current()
var aliasFile = filepath.Join(usr.HomeDir, ".gam_aliases")
const usage = `
usage:
gam [options] [...arguments]
options:
-d delete given alias
examples:
create alias. first arg is name of the alias, value is the rest
gam gitlab ssh [email protected]
update alias.
gam gitlab ssh [email protected]
delete alias.
gam -d gitlab
print alias.
gam gitlab
print all aliases.
gam
`
type action int
const (
persist action = iota
del
print
printAll
)
type gam struct {
action action
alias alias
}
func (g gam) execute() error {
switch g.action {
case persist:
if g.alias.name == "" {
return errMissingName
}
if g.alias.value == "" {
return errMissingValue
}
return g.alias.persist()
case del:
return g.alias.remove()
case print:
alias, err := readOne(g.alias.name)
if err != nil {
return err
}
fmt.Println(alias.string())
return nil
case printAll:
aliases, err := readAll()
if err != nil {
return err
}
fmt.Println(strings.Join(aliases.strings(), "\n"))
return nil
default:
return errInvalidAction
}
}
func main() {
delete := flag.String("d", "", "")
help := flag.Bool("h", false, "")
flag.Usage = func() {
fmt.Fprintf(os.Stderr, usage)
}
flag.Parse()
if *help {
flag.Usage()
os.Exit(0)
}
var args = flag.Args()
var action action
var alias alias
if *delete != "" {
action = del
alias.name = *delete
} else if len(args) == 0 {
action = printAll
} else if len(args) == 1 {
action = print
alias.name = args[0]
} else if len(args) > 1 {
action = persist
alias.name = args[0]
alias.value = strings.Join(args[1:], " ")
}
gam := &gam{
action: action,
alias: alias,
}
err := gam.execute()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}