MCPcopy Create free account
hub / github.com/cli/cli / applySet

Function applySet

script/ghmock/set.go:300–365  ·  view source on GitHub ↗

applySet changes one stored response and returns its position.

(responses responseSet, opts setOptions)

Source from the content-addressed store, hash-verified

298
299// applySet changes one stored response and returns its position.
300func applySet(responses responseSet, opts setOptions) (int, error) {
301 list := responses[opts.name]
302 var pos int
303 if opts.appendNew || (len(list) == 0 && opts.index <= 1) {
304 list = append(list, response{})
305 pos = len(list) - 1
306 } else {
307 pos = max(opts.index, 1) - 1
308 if pos >= len(list) {
309 return 0, fmt.Errorf("%s has %d response(s); use --append to add another", opts.name, len(list))
310 }
311 }
312
313 r := list[pos]
314 if opts.status != 0 {
315 r.Status = opts.status
316 }
317 if len(opts.headers) > 0 {
318 headers := make(map[string]string, len(r.Headers)+len(opts.headers))
319 for k, v := range r.Headers {
320 headers[http.CanonicalHeaderKey(k)] = v
321 }
322 for _, h := range opts.headers {
323 name, value, _ := strings.Cut(h, ":")
324 name, value = http.CanonicalHeaderKey(strings.TrimSpace(name)), strings.TrimSpace(value)
325 if value == "" {
326 delete(headers, name)
327 } else {
328 headers[name] = value
329 }
330 }
331 if len(headers) == 0 {
332 headers = nil
333 }
334 r.Headers = headers
335 }
336 if opts.bodySet {
337 body := bytes.TrimSpace([]byte(opts.body))
338 if len(body) > 0 && !json.Valid(body) {
339 return 0, fmt.Errorf("body is not valid JSON")
340 }
341 if len(body) == 0 {
342 body = nil
343 }
344 r.Body = body
345 r.RawBody = nil
346 }
347 if opts.rawBody != nil {
348 r.Body = nil
349 r.RawBody = opts.rawBody
350 }
351 if opts.at != "" {
352 if r.RawBody != nil {
353 return 0, fmt.Errorf("cannot use --at on a raw body; replace it with --body or --body-file first")
354 }
355 body, err := setAtPath(r.Body, opts.at, opts.value)
356 if err != nil {
357 return 0, err

Callers 2

cmdSetFunction · 0.85
TestApplySetFunction · 0.85

Calls 3

setAtPathFunction · 0.85
ValidMethod · 0.80
ErrorfMethod · 0.65

Tested by 1

TestApplySetFunction · 0.68