-
Notifications
You must be signed in to change notification settings - Fork 16
/
command.go
64 lines (56 loc) · 1.65 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
package i3
import (
"encoding/json"
"fmt"
)
// CommandResult always contains Success, and command-specific fields where
// appropriate.
type CommandResult struct {
// Success indicates whether the command was run without any errors.
Success bool `json:"success"`
// Error is a human-readable error message, non-empty for unsuccessful
// commands.
Error string `json:"error"`
}
// IsUnsuccessful is a convenience function which can be used to check if an
// error is a CommandUnsuccessfulError.
func IsUnsuccessful(err error) bool {
_, ok := err.(*CommandUnsuccessfulError)
return ok
}
// CommandUnsuccessfulError is returned by RunCommand for unsuccessful
// commands. This type is exported so that you can ignore this error if you
// expect your command(s) to fail.
type CommandUnsuccessfulError struct {
command string
cr CommandResult
}
// Error implements error.
func (e *CommandUnsuccessfulError) Error() string {
return fmt.Sprintf("command %q unsuccessful: %v", e.command, e.cr.Error)
}
// RunCommand makes i3 run the specified command.
//
// Error is non-nil if any CommandResult.Success is not true. See IsUnsuccessful
// if you send commands which are expected to fail.
//
// RunCommand is supported in i3 ≥ v4.0 (2011-07-31).
func RunCommand(command string) ([]CommandResult, error) {
reply, err := roundTrip(messageTypeRunCommand, []byte(command))
if err != nil {
return []CommandResult{}, err
}
var crs []CommandResult
err = json.Unmarshal(reply.Payload, &crs)
if err == nil {
for _, cr := range crs {
if !cr.Success {
return crs, &CommandUnsuccessfulError{
command: command,
cr: cr,
}
}
}
}
return crs, err
}