/
edit.go
190 lines (158 loc) · 4.97 KB
/
edit.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
package cli
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"
"os/exec"
"strings"
"github.com/danielgtaylor/shorthand/v2"
"github.com/google/shlex"
"github.com/hexops/gotextdiff"
"github.com/hexops/gotextdiff/myers"
"github.com/hexops/gotextdiff/span"
"github.com/mattn/go-isatty"
"github.com/spf13/viper"
)
func panicOnErr(err error) {
if err != nil {
panic(err)
}
}
// getEditor tries to find the system default text editor command.
func getEditor() string {
editor := os.Getenv("VISUAL")
if editor == "" {
editor = os.Getenv("EDITOR")
}
return editor
}
func edit(addr string, args []string, interactive, noPrompt bool, exitFunc func(int), editMarshal func(interface{}) ([]byte, error), editUnmarshal func([]byte, interface{}) error, ext string) {
if !interactive && len(args) == 0 {
fmt.Fprintln(os.Stderr, "No arguments passed to modify the resource. Use `-i` to enable interactive mode.")
exitFunc(1)
return
}
editor := getEditor()
if interactive && editor == "" {
fmt.Fprintln(os.Stderr, `Please set the VISUAL or EDITOR environment variable with your preferred editor. Examples:
export VISUAL="code --wait"
export EDITOR="vim"`)
exitFunc(1)
return
}
req, _ := http.NewRequest(http.MethodGet, fixAddress(addr), nil)
resp, err := GetParsedResponse(req)
panicOnErr(err)
if resp.Status >= 400 {
panicOnErr(Formatter.Format(resp))
exitFunc(1)
return
}
// Convert from CBOR or other formats which might allow map[any]any to the
// constraints of JSON (i.e. map[string]interface{}).
var data interface{} = resp.Map()
data = makeJSONSafe(data)
filter := viper.GetString("rsh-filter")
if filter == "" {
filter = "body"
}
var logger func(format string, a ...interface{})
if enableVerbose {
logger = LogDebug
}
filtered, _, err := shorthand.GetPath(filter, data, shorthand.GetOptions{
DebugLogger: logger,
})
panicOnErr(err)
data = filtered
if _, ok := data.(map[string]interface{}); !ok {
fmt.Fprintln(os.Stderr, "Resource didn't return an object.")
exitFunc(1)
return
}
// Save original representation for comparison later. We use JSON here for
// consistency and to avoid things like YAML encoding e.g. dates and strings
// differently.
orig, _ := json.MarshalIndent(data, "", " ")
// If available, grab any headers that can be used for conditional updates
// so we don't overwrite changes made by other people while we edit.
etag := resp.Headers["Etag"]
lastModified := resp.Headers["Last-Modified"]
// TODO: remove read-only fields? This requires:
// 1. Figure out which operation the URL corresponds to.
// 2. Get and then analyse the response schema for that operation.
// 3. Remove corresponding fields from `data`.
var modified interface{} = data
if len(args) > 0 {
modified, err = shorthand.Unmarshal(strings.Join(args, " "), shorthand.ParseOptions{EnableFileInput: true, EnableObjectDetection: true}, modified)
panicOnErr(err)
}
if interactive {
// Create temp file
tmp, err := os.CreateTemp("", "rsh-edit*"+ext)
panicOnErr(err)
defer os.Remove(tmp.Name())
// TODO: should we try and detect a `describedby` link relation and insert
// that as a `$schema` key into the document before editing? The schema
// itself may not allow the `$schema` key... hmm.
// Write the current body
marshalled, err := editMarshal(modified)
panicOnErr(err)
tmp.Write(marshalled)
tmp.Close()
// Open editor and wait for exit
parts, err := shlex.Split(editor)
panicOnErr(err)
name := parts[0]
args := append(parts[1:], tmp.Name())
cmd := exec.Command(name, args...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
panicOnErr(cmd.Run())
// Read file contents
b, err := os.ReadFile(tmp.Name())
panicOnErr(err)
panicOnErr(editUnmarshal(b, &modified))
}
modified = makeJSONSafe(modified)
mod, err := json.MarshalIndent(modified, "", " ")
panicOnErr(err)
edits := myers.ComputeEdits(span.URIFromPath("original"), string(orig), string(mod))
if len(edits) == 0 {
fmt.Fprintln(os.Stderr, "No changes made.")
exitFunc(0)
return
} else {
diff := fmt.Sprint(gotextdiff.ToUnified("original", "modified", string(orig), edits))
if useColor {
d, _ := Highlight("diff", []byte(diff))
diff = string(d)
}
fmt.Println(diff)
if !noPrompt && isatty.IsTerminal(os.Stdin.Fd()) || isatty.IsCygwinTerminal(os.Stdin.Fd()) {
fmt.Printf("Continue? [Y/n] ")
tmp := []byte{0}
os.Stdin.Read(tmp)
if tmp[0] == 'n' {
exitFunc(0)
return
}
}
}
// TODO: support different submission formats, e.g. based on any given
// `Content-Type` header?
// TODO: content-encoding for large bodies?
// TODO: determine if a PATCH could be used instead?
b, _ := json.Marshal(modified)
req, _ = http.NewRequest(http.MethodPut, fixAddress(addr), bytes.NewReader(b))
req.Header.Set("Content-Type", "application/json")
if etag != "" {
req.Header.Set("If-Match", etag)
} else if lastModified != "" {
req.Header.Set("If-Unmodified-Since", lastModified)
}
MakeRequestAndFormat(req)
}