forked from creativeprojects/resticprofile
-
Notifications
You must be signed in to change notification settings - Fork 0
/
own_commands.go
89 lines (78 loc) · 2.43 KB
/
own_commands.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
package main
import (
"fmt"
"io"
"os"
"strings"
)
// commandContext is the context for running a command.
type commandContext struct {
Context
ownCommands *OwnCommands
}
type ownCommand struct {
name string
description string
longDescription string
pre func(*Context) error // pre-command action (for checking the context)
action func(io.Writer, commandContext) error // run command action
needConfiguration bool // true if the action needs a configuration file loaded
hide bool // don't display the command in help and completion
hideInCompletion bool // don't display the command in completion
noProfile bool // true if the command doesn't need a profile name
flags map[string]string // own command flags should be simple enough to be handled manually for now
}
// OwnCommands is a list of resticprofile commands
type OwnCommands struct {
commands []ownCommand
}
func NewOwnCommands() *OwnCommands {
return &OwnCommands{
commands: make([]ownCommand, 0, 20),
}
}
func (o *OwnCommands) Register(commands []ownCommand) {
o.commands = append(o.commands, commands...)
}
func (o *OwnCommands) Exists(command string, configurationLoaded bool) bool {
for _, commandDef := range o.commands {
if commandDef.name == command && commandDef.needConfiguration == configurationLoaded {
return true
}
}
return false
}
func (o *OwnCommands) All() []ownCommand {
ownCommands := make([]ownCommand, len(o.commands))
copy(ownCommands, o.commands)
return ownCommands
}
func (o *OwnCommands) Run(ctx *Context) error {
command := o.find(ctx.request.command)
if command == nil {
return fmt.Errorf("command not found: %v", ctx.request.command)
}
return command.action(os.Stdout, commandContext{
ownCommands: o,
Context: *ctx,
})
}
func (o *OwnCommands) Pre(ctx *Context) error {
command := o.find(ctx.request.command)
if command == nil {
return fmt.Errorf("command not found: %v", ctx.request.command)
}
if command.pre == nil {
return nil
}
return command.pre(ctx)
}
func (o *OwnCommands) find(commandName string) *ownCommand {
commandName = strings.ToLower(commandName)
for _, commandDef := range o.commands {
if commandDef.name == commandName {
return &commandDef
}
}
return nil
}