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

Function gpgKeyUpload

pkg/cmd/gpg-key/add/http.go:19–73  ·  view source on GitHub ↗
(httpClient *http.Client, hostname string, keyFile io.Reader, title string)

Source from the content-addressed store, hash-verified

17var errWrongFormat = errors.New("key in wrong format")
18
19func gpgKeyUpload(httpClient *http.Client, hostname string, keyFile io.Reader, title string) error {
20 u, err := safeurl.JoinPathWithHostPrefix(ghinstance.RESTPrefix(hostname), "user", "gpg_keys")
21 if err != nil {
22 return err
23 }
24
25 keyBytes, err := io.ReadAll(keyFile)
26 if err != nil {
27 return err
28 }
29
30 payload := map[string]string{
31 "armored_public_key": string(keyBytes),
32 }
33 if title != "" {
34 payload["name"] = title
35 }
36
37 payloadBytes, err := json.Marshal(payload)
38 if err != nil {
39 return err
40 }
41
42 req, err := http.NewRequest("POST", u.String(), bytes.NewBuffer(payloadBytes))
43 if err != nil {
44 return err
45 }
46
47 resp, err := httpClient.Do(req)
48 if err != nil {
49 return err
50 }
51 defer resp.Body.Close()
52
53 if resp.StatusCode == 404 {
54 return errScopesMissing
55 } else if resp.StatusCode > 299 {
56 err := api.HandleHTTPError(resp)
57 var httpError api.HTTPError
58 if errors.As(err, &httpError) {
59 for _, e := range httpError.Errors {
60 if resp.StatusCode == 422 && e.Field == "key_id" && e.Message == "key_id already exists" {
61 return errDuplicateKey
62 }
63 }
64 }
65 if resp.StatusCode == 422 && !isGpgKeyArmored(keyBytes) {
66 return errWrongFormat
67 }
68 return err
69 }
70
71 _, _ = io.Copy(io.Discard, resp.Body)
72 return nil
73}
74
75func isGpgKeyArmored(keyBytes []byte) bool {
76 return bytes.Contains(keyBytes, []byte("-----BEGIN "))

Callers 1

runAddFunction · 0.85

Calls 8

JoinPathWithHostPrefixFunction · 0.92
RESTPrefixFunction · 0.92
HandleHTTPErrorFunction · 0.92
isGpgKeyArmoredFunction · 0.85
StringMethod · 0.65
DoMethod · 0.65
CloseMethod · 0.65
CopyMethod · 0.45

Tested by

no test coverage detected