|
| 1 | +package cli |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + "net/http" |
| 9 | + "os" |
| 10 | + "os/exec" |
| 11 | + "strings" |
| 12 | + |
| 13 | + jmespath "github.com/danielgtaylor/go-jmespath-plus" |
| 14 | + "github.com/danielgtaylor/shorthand" |
| 15 | + "github.com/google/shlex" |
| 16 | + "github.com/hexops/gotextdiff" |
| 17 | + "github.com/hexops/gotextdiff/myers" |
| 18 | + "github.com/hexops/gotextdiff/span" |
| 19 | + "github.com/mattn/go-isatty" |
| 20 | + "github.com/spf13/viper" |
| 21 | +) |
| 22 | + |
| 23 | +// emptyState implements a dummy fmt.State that passes through to a writer. |
| 24 | +type emptyState struct { |
| 25 | + writer io.Writer |
| 26 | +} |
| 27 | + |
| 28 | +func (e *emptyState) Write(b []byte) (n int, err error) { |
| 29 | + return e.writer.Write(b) |
| 30 | +} |
| 31 | + |
| 32 | +func (e *emptyState) Width() (wid int, ok bool) { |
| 33 | + return 0, true |
| 34 | +} |
| 35 | + |
| 36 | +func (e *emptyState) Precision() (prec int, ok bool) { |
| 37 | + return 0, true |
| 38 | +} |
| 39 | + |
| 40 | +func (e *emptyState) Flag(c int) bool { |
| 41 | + return false |
| 42 | +} |
| 43 | + |
| 44 | +func panicOnErr(err error) { |
| 45 | + if err != nil { |
| 46 | + panic(err) |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +// getEditor tries to find the system default text editor command. |
| 51 | +func getEditor() string { |
| 52 | + editor := os.Getenv("VISUAL") |
| 53 | + if editor == "" { |
| 54 | + editor = os.Getenv("EDITOR") |
| 55 | + } |
| 56 | + |
| 57 | + return editor |
| 58 | +} |
| 59 | + |
| 60 | +func edit(addr string, args []string, interactive, noPrompt bool, exitFunc func(int), editMarshal func(interface{}) ([]byte, error), editUnmarshal func([]byte, interface{}) error, ext string) { |
| 61 | + if !interactive && len(args) == 0 { |
| 62 | + fmt.Fprintln(os.Stderr, "No arguments passed to modify the resource. Use `-i` to enable interactive mode.") |
| 63 | + exitFunc(1) |
| 64 | + return |
| 65 | + } |
| 66 | + |
| 67 | + editor := getEditor() |
| 68 | + if interactive && editor == "" { |
| 69 | + fmt.Fprintln(os.Stderr, `Please set the VISUAL or EDITOR environment variable with your preferred editor. Examples: |
| 70 | +
|
| 71 | +export VISUAL="code --wait" |
| 72 | +export EDITOR="vim"`) |
| 73 | + exitFunc(1) |
| 74 | + return |
| 75 | + } |
| 76 | + |
| 77 | + req, _ := http.NewRequest(http.MethodGet, fixAddress(addr), nil) |
| 78 | + resp, err := GetParsedResponse(req) |
| 79 | + panicOnErr(err) |
| 80 | + |
| 81 | + if resp.Status >= 400 { |
| 82 | + panicOnErr(Formatter.Format(resp)) |
| 83 | + exitFunc(1) |
| 84 | + return |
| 85 | + } |
| 86 | + |
| 87 | + // Convert from CBOR or other formats which might allow map[any]any to the |
| 88 | + // constraints of JSON (i.e. map[string]interface{}). |
| 89 | + var data interface{} = resp.Map() |
| 90 | + data = makeJSONSafe(data, false) |
| 91 | + |
| 92 | + filter := viper.GetString("rsh-filter") |
| 93 | + if filter == "" { |
| 94 | + filter = "body" |
| 95 | + } |
| 96 | + filtered, err := jmespath.Search(filter, data) |
| 97 | + panicOnErr(err) |
| 98 | + data = filtered |
| 99 | + |
| 100 | + if _, ok := data.(map[string]interface{}); !ok { |
| 101 | + fmt.Fprintln(os.Stderr, "Resource didn't return an object.") |
| 102 | + exitFunc(1) |
| 103 | + return |
| 104 | + } |
| 105 | + |
| 106 | + // Save original representation for comparison later. We use JSON here for |
| 107 | + // consistency and to avoid things like YAML encoding e.g. dates and strings |
| 108 | + // differently. |
| 109 | + orig, _ := json.MarshalIndent(data, "", " ") |
| 110 | + |
| 111 | + // If available, grab any headers that can be used for conditional updates |
| 112 | + // so we don't overwrite changes made by other people while we edit. |
| 113 | + etag := resp.Headers["Etag"] |
| 114 | + lastModified := resp.Headers["Last-Modified"] |
| 115 | + |
| 116 | + // TODO: remove read-only fields? This requires: |
| 117 | + // 1. Figure out which operation the URL corresponds to. |
| 118 | + // 2. Get and then analyse the response schema for that operation. |
| 119 | + // 3. Remove corresponding fields from `data`. |
| 120 | + |
| 121 | + var modified interface{} = data |
| 122 | + |
| 123 | + if len(args) > 0 { |
| 124 | + modified, err = shorthand.ParseAndBuild(req.URL.Path, strings.Join(args, " "), modified.(map[string]interface{})) |
| 125 | + panicOnErr(err) |
| 126 | + } |
| 127 | + |
| 128 | + if interactive { |
| 129 | + // Create temp file |
| 130 | + tmp, err := os.CreateTemp("", "rsh-edit*"+ext) |
| 131 | + panicOnErr(err) |
| 132 | + defer os.Remove(tmp.Name()) |
| 133 | + |
| 134 | + // TODO: should we try and detect a `describedby` link relation and insert |
| 135 | + // that as a `$schema` key into the document before editing? The schema |
| 136 | + // itself may not allow the `$schema` key... hmm. |
| 137 | + |
| 138 | + // Write the current body |
| 139 | + marshalled, err := editMarshal(modified) |
| 140 | + panicOnErr(err) |
| 141 | + tmp.Write(marshalled) |
| 142 | + tmp.Close() |
| 143 | + |
| 144 | + // Open editor and wait for exit |
| 145 | + parts, err := shlex.Split(editor) |
| 146 | + panicOnErr(err) |
| 147 | + name := parts[0] |
| 148 | + args := append(parts[1:], tmp.Name()) |
| 149 | + |
| 150 | + cmd := exec.Command(name, args...) |
| 151 | + cmd.Stdin = os.Stdin |
| 152 | + cmd.Stdout = os.Stdout |
| 153 | + cmd.Stderr = os.Stderr |
| 154 | + panicOnErr(cmd.Run()) |
| 155 | + |
| 156 | + // Read file contents |
| 157 | + b, err := os.ReadFile(tmp.Name()) |
| 158 | + panicOnErr(err) |
| 159 | + |
| 160 | + panicOnErr(editUnmarshal(b, &modified)) |
| 161 | + } |
| 162 | + |
| 163 | + modified = makeJSONSafe(modified, false) |
| 164 | + mod, err := json.MarshalIndent(modified, "", " ") |
| 165 | + panicOnErr(err) |
| 166 | + edits := myers.ComputeEdits(span.URIFromPath("original"), string(orig), string(mod)) |
| 167 | + |
| 168 | + if len(edits) == 0 { |
| 169 | + fmt.Fprintln(os.Stderr, "No changes made.") |
| 170 | + exitFunc(0) |
| 171 | + return |
| 172 | + } else { |
| 173 | + sb := &strings.Builder{} |
| 174 | + s := &emptyState{writer: sb} |
| 175 | + unified := gotextdiff.ToUnified("original", "modified", string(orig), edits) |
| 176 | + unified.Format(s, ' ') |
| 177 | + diff := sb.String() |
| 178 | + if tty { |
| 179 | + d, _ := Highlight("diff", []byte(diff)) |
| 180 | + diff = string(d) |
| 181 | + } |
| 182 | + fmt.Println(diff) |
| 183 | + |
| 184 | + if !noPrompt && isatty.IsTerminal(os.Stdin.Fd()) || isatty.IsCygwinTerminal(os.Stdin.Fd()) { |
| 185 | + fmt.Printf("Continue? [Y/n] ") |
| 186 | + tmp := []byte{0} |
| 187 | + os.Stdin.Read(tmp) |
| 188 | + if tmp[0] == 'n' { |
| 189 | + exitFunc(0) |
| 190 | + return |
| 191 | + } |
| 192 | + } |
| 193 | + } |
| 194 | + |
| 195 | + // TODO: support different submission formats, e.g. based on any given |
| 196 | + // `Content-Type` header? |
| 197 | + // TODO: content-encoding for large bodies? |
| 198 | + // TODO: determine if a PATCH could be used instead? |
| 199 | + b, _ := json.Marshal(modified) |
| 200 | + req, _ = http.NewRequest(http.MethodPut, fixAddress(addr), bytes.NewReader(b)) |
| 201 | + req.Header.Set("Content-Type", "application/json") |
| 202 | + |
| 203 | + if etag != "" { |
| 204 | + req.Header.Set("If-Match", etag) |
| 205 | + } else if lastModified != "" { |
| 206 | + req.Header.Set("If-Unmodified-Since", lastModified) |
| 207 | + } |
| 208 | + |
| 209 | + MakeRequestAndFormat(req) |
| 210 | +} |
0 commit comments