forked from mkideal/onepw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
command.go
439 lines (383 loc) · 9.91 KB
/
command.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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
package main
import (
"fmt"
"github.com/mkideal/onepw/data"
"os"
"path/filepath"
"strings"
"github.com/labstack/gommon/color"
"github.com/mkideal/cli"
"github.com/mkideal/onepw/core"
"github.com/mkideal/pkg/build"
"github.com/mkideal/pkg/debug"
"github.com/mkideal/pkg/prompt"
"github.com/mkideal/pkg/textutil"
)
func init() {
rootCommand = cli.Root(rootCommand,
cli.Tree(helpCommand),
cli.Tree(initCommand),
cli.Tree(setCommand),
cli.Tree(importCommand),
cli.Tree(removeCommand),
cli.Tree(listCommand),
cli.Tree(findCommand),
cli.Tree(upgradeCommand),
cli.Tree(infoCommand),
)
}
//--------
// Config
//--------
// Configure ...
type Configure interface {
Filename() string
MasterPassword() string
Debug() bool
}
// Config implements Configure interface, represents onepw config
type Config struct {
Master string `pw:"master" usage:"Your master password" dft:"$ONEPW_MASTER" prompt:"Type the master password"`
EnableDebug bool `cli:"debug" usage:"Enable debug mode" dft:"false"`
}
// Filename returns password data filename
func (cfg Config) Filename() string {
filename := os.Getenv("ONEPW_FILE")
if filename == "" {
filename = "password.data"
}
return filename
}
// MasterPassword returns master password
func (cfg Config) MasterPassword() string {
return cfg.Master
}
// Debug returns debug mode
func (cfg Config) Debug() bool {
return cfg.EnableDebug
}
var box *core.Box
//--------------
// root command
//--------------
type rootCommandT struct {
cli.Helper2
Version bool `cli:"!v,version" usage:"Display version information"`
}
var rootCommand = &cli.Command{
Name: os.Args[0],
Desc: textutil.Tpl("{{.onepw}} is a command line tool for managing passwords, open-source on {{.repo}}", map[string]string{
"onepw": color.Bold("onepw"),
"repo": color.Blue("https://github.com/mkideal/onepw"),
}),
Text: textutil.Tpl(`{{.usage}}: {{.onepw}} <COMMAND> [OPTIONS]`, map[string]string{
"onepw": color.Bold("onepw"),
"usage": color.Bold("Usage"),
}),
Argv: func() interface{} { return new(rootCommandT) },
NumArg: cli.AtLeast(1),
OnBefore: func(ctx *cli.Context) error {
argv := ctx.Argv().(*rootCommandT)
if argv.Version {
ctx.String("%s\n", build.String("onepw"))
return cli.ExitError
}
return nil
},
OnRootBefore: func(ctx *cli.Context) error {
if argv := ctx.Argv(); argv != nil {
if t, ok := argv.(Configure); ok {
debug.Switch(t.Debug())
repo := core.NewFileRepository(t.Filename())
box = core.NewBox(repo)
if t.MasterPassword() != "" {
return box.Init(t.MasterPassword())
}
return nil
}
}
return fmt.Errorf("box is nil")
},
Fn: func(ctx *cli.Context) error {
return nil
},
}
//--------------
// help command
//--------------
var helpCommand = cli.HelpCommand("Display help information")
//--------------
// init command
//--------------
type initCommandT struct {
cli.Helper2
Config
Update bool `cli:"u,update" usage:"Whether to update the master password" dft:"false"`
}
func (argv *initCommandT) Validate(ctx *cli.Context) error {
if argv.Filename() == "" {
return fmt.Errorf("FILE is empty")
}
return nil
}
var initCommand = &cli.Command{
Name: "init",
Desc: "Init password box or change the master password",
Argv: func() interface{} { return new(initCommandT) },
OnBefore: func(ctx *cli.Context) error {
argv := ctx.Argv().(*initCommandT)
if argv.Update {
return nil
}
cpw, err := prompt.Password("Repeat the master password: ")
if err != nil {
return err
}
if argv.Master != string(cpw) {
return fmt.Errorf(ctx.Color().Red("master password mismatched"))
}
if _, err := os.Lstat(argv.Filename()); err != nil {
if os.IsNotExist(err) {
dir, _ := filepath.Split(argv.Filename())
if dir != "" && dir != "." {
if err := os.MkdirAll(dir, 0755); err != nil {
return err
}
}
file, err := os.Create(argv.Filename())
if err != nil {
return err
}
file.Close()
}
}
return nil
},
Fn: func(ctx *cli.Context) error {
argv := ctx.Argv().(*initCommandT)
if argv.Update {
pw, err := prompt.Password("Type a new master password: ")
if err != nil {
return err
}
cpw, err := prompt.Password("Repeat the new master password: ")
if err != nil {
return err
}
if string(pw) != string(cpw) {
return fmt.Errorf(ctx.Color().Red("new master password mismatched"))
}
return box.Update(string(pw))
}
return nil
},
}
//-------------
// set command
//-------------
type setCommandT struct {
cli.Helper2
Config
core.Password
Pw string `pw:"p,password" usage:"The password you decided to use" name:"PASSWORD" prompt:"Type the password"`
Cpw string `pw:"C,confirm" usage:"Confirm password which must be same as PASSWORD" prompt:"Repeat the password"`
}
func (argv *setCommandT) Validate(ctx *cli.Context) error {
if argv.Pw != argv.Cpw {
return fmt.Errorf("passwords mismatched")
}
return core.CheckPassword(argv.Pw)
}
var setCommand = &cli.Command{
Name: "set",
Desc: "Set password (add a new password or update the old password)",
Aliases: []string{"add"},
Argv: func() interface{} {
argv := new(setCommandT)
argv.Password = *core.NewEmptyPassword()
return argv
},
Fn: func(ctx *cli.Context) error {
argv := ctx.Argv().(*setCommandT)
argv.Password.PlainPassword = argv.Pw
id, new, err := box.Add(&argv.Password)
if err != nil {
return err
}
if new {
ctx.String("password %s added\n", ctx.Color().Cyan(id))
} else {
ctx.String("password %s updated\n", ctx.Color().Cyan(id))
}
return nil
},
}
//--------
// import
//--------
type importCommandT struct {
cli.Helper2
Config
NotesPath string `cli:"n,notes" usage:"need import notes path" dft:"notes.xlsx"`
}
func (argv *importCommandT) Validate(ctx *cli.Context) error {
if argv.NotesPath == "" {
return fmt.Errorf("notes path is empty")
}
return nil
}
var importCommand = &cli.Command{
Name: "import",
Desc: "import notes.xlsx to onepw password data",
Argv: func() interface{} {
return new(importCommandT)
},
Fn: func(ctx *cli.Context) error {
argv := ctx.Argv().(*importCommandT)
passwordItems, err := data.GetData(argv.NotesPath)
if err != nil {
return err
}
failed := make([]string, 0)
// for loop add password item
for i := 0; i < len(passwordItems); i++ {
item := passwordItems[i]
newPassword := core.NewPassword(item.Category, item.Account, item.Password, item.Site)
_, _, err = box.Add(newPassword)
if err != nil {
fmt.Fprintf(ctx, "add password item: %+v err: %+v", item, err)
failed = append(failed, item.Account)
continue
}
}
if len(failed) > 0 {
fmt.Fprintf(ctx, "add password item failed len: %+v", len(failed))
}
return nil
},
}
//--------
// remove
//--------
type removeCommandT struct {
cli.Helper2
Config
All bool `cli:"a,all" usage:"Remove all found passwords" dft:"false"`
}
var removeCommand = &cli.Command{
Name: "remove",
Aliases: []string{"rm", "del", "delete"},
Desc: "Remove passwords by IDs or (category,account)",
Text: "Usage: onepw rm [IDs...] [OPTIONS]",
Argv: func() interface{} { return new(removeCommandT) },
CanSubRoute: true,
Fn: func(ctx *cli.Context) error {
var (
argv = ctx.Argv().(*removeCommandT)
deletedIds []string
err error
ids = ctx.Args()
)
if len(ids) > 0 {
deletedIds, err = box.Remove(ids, argv.All)
} else if argv.All {
deletedIds, err = box.Clear()
}
if err != nil {
return err
}
ctx.String("deleted passwords:\n")
ctx.String(ctx.Color().Cyan(strings.Join(deletedIds, "\n")))
ctx.String("\n")
return nil
},
}
//------
// list
//------
type listCommandT struct {
cli.Helper2
Config
NoHeader bool `cli:"no-header" usage:"Don't print header line" dft:"false"`
ShowHidden bool `cli:"H,hidden" usage:"Whether to list hidden passwords"`
}
var listCommand = &cli.Command{
Name: "list",
Aliases: []string{"ls"},
Desc: "List all passwords",
Argv: func() interface{} { return new(listCommandT) },
Fn: func(ctx *cli.Context) error {
argv := ctx.Argv().(*listCommandT)
return box.List(ctx, argv.NoHeader, argv.ShowHidden)
},
}
//--------------
// find command
//--------------
type findCommandT struct {
cli.Helper2
Config
JustPassword bool `cli:"p,just-password" usage:"Just show password" dft:"false"`
JustFirst bool `cli:"f,just-first" usage:"Just show first result" dft:"false"`
}
var findCommand = &cli.Command{
Name: "find",
Desc: "Find password by ID,category,account,tag or site and so on",
Text: "Usage: onepw find <WORD>",
Argv: func() interface{} { return new(findCommandT) },
CanSubRoute: true,
OnBefore: func(ctx *cli.Context) error {
if len(ctx.Args()) != 1 {
ctx.WriteUsage()
return cli.ExitError
}
return nil
},
Fn: func(ctx *cli.Context) error {
argv := ctx.Argv().(*findCommandT)
box.Find(ctx, ctx.Args()[0], argv.JustPassword, argv.JustFirst)
return nil
},
}
//-----------------
// upgrade command
//-----------------
type upgradeCommandT struct {
cli.Helper2
Config
}
var upgradeCommand = &cli.Command{
Name: "upgrade",
Aliases: []string{"up"},
Desc: "Upgrade to newest version",
Argv: func() interface{} { return new(upgradeCommandT) },
Fn: func(ctx *cli.Context) error {
from, to, err := box.Upgrade()
if err != nil {
return err
}
ctx.String("upgrade from %d to %d!\n", from, to)
return nil
},
}
//--------------
// info command
//--------------
type infoCommandT struct {
cli.Helper2
Config
All bool `cli:"a,all" usage:"show all found passwords"`
}
var infoCommand = &cli.Command{
Name: "show",
Aliases: []string{"info"},
Desc: "Show low-level information of password",
Text: "Usage: onepw show <IDs...>",
Argv: func() interface{} { return new(infoCommandT) },
CanSubRoute: true,
NumArg: cli.AtLeast(1),
Fn: func(ctx *cli.Context) error {
argv := ctx.Argv().(*infoCommandT)
return box.Inspect(ctx, ctx.Args(), argv.All)
},
}