-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
128 lines (116 loc) · 2.29 KB
/
context.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 (
"encoding/json"
"io"
"io/ioutil"
"os"
"github.com/mitchellh/go-homedir"
)
type Context struct {
Option Option
Users Users
}
type nullIO struct{}
// Write io.Writer
func (nullIO) Write(p []byte) (n int, err error) {
return 0, nil
}
// NewContext init context
func NewContext() *Context {
return &Context{
Option: Option{
Show: ShowOption{},
Set: SetOption{
Args: SetArgs{},
},
Delete: DeleteOption{
Args: DeleteArgs{},
},
Local: LocalOption{},
List: ListOption{},
Sync: SyncOption{},
Print: PrintOption{},
},
}
}
// LoadConfig load config from json
func (c *Context) LoadConfig() error {
path, err := c.configPath()
if err != nil {
return err
}
if _, statErr := os.Stat(path); os.IsNotExist(statErr) {
return nil
} else {
bytes, err := ioutil.ReadFile(path)
if err != nil {
return err
}
return json.Unmarshal(bytes, &c.Users)
}
}
// SaveConfig save config to json
func (c *Context) SaveConfig() error {
path, err := c.configPath()
if err != nil {
return err
}
bytes, err := json.Marshal(&c.Users)
if err != nil {
return err
}
return ioutil.WriteFile(path, bytes, 0644)
}
// Execute execute action
func (c *Context) Execute(command string) error {
if err := c.LoadConfig(); err != nil {
return err
}
switch command {
case "show":
a := &Action{
printer: NewPrinter(c.Option.Show.printFlag(), os.Stdout),
}
return a.ShowUser(c)
case "set":
a := &Action{
printer: NewPrinter(PrintDefault, os.Stdout),
}
return a.SetUser(c)
case "delete":
a := &Action{
printer: NewPrinter(PrintDefault, os.Stdout),
}
return a.DeleteUser(c)
case "local":
a := &Action{
printer: NewPrinter(c.Option.Local.printFlag(), os.Stdout),
}
return a.ShowLocalUser(c)
case "list":
a := &Action{
printer: NewPrinter(c.Option.List.printFlag(), os.Stdout),
}
return a.ListUsers(c)
case "sync":
var writer io.Writer
if c.Option.Sync.Quiet {
writer = &nullIO{}
} else {
writer = os.Stdout
}
a := &Action{
printer: NewPrinter(PrintDefault, writer),
}
return a.SyncGitUserToLocal(c)
case "print":
a := &Action{
printer: NewPrinter(PrintDefault, os.Stdout),
}
return a.Print(c)
}
return nil
}
func (c Context) configPath() (string, error) {
return homedir.Expand(c.Option.Config)
}