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

Method postAsset

internal/attachments/client.go:105–151  ·  view source on GitHub ↗

postAsset does the request and reads the asset URL back. It takes the file rather than the UserAsset, because nothing about sending the bytes depends on how they render. It is separate so every way it can fail picks up the same explanation on the way out.

(ctx context.Context, a asset)

Source from the content-addressed store, hash-verified

103// how they render. It is separate so every way it can fail picks up the same
104// explanation on the way out.
105func (u *Uploader) postAsset(ctx context.Context, a asset) (string, error) {
106 url, err := safeurl.JoinPathWithHostPrefix(ghinstance.UserAssetUploadPrefix(u.host), "user-attachments", "assets")
107 if err != nil {
108 return "", err
109 }
110 url.SetQuery("name", filepath.Base(a.path))
111 url.SetQuery("content_type", a.contentType)
112 url.SetQuery("repository_id", strconv.FormatInt(u.targetRepository, 10))
113
114 open := func() (io.ReadCloser, error) { return openFile(a.path) }
115
116 f, err := open()
117 if err != nil {
118 return "", err
119 }
120 defer f.Close()
121
122 req, err := http.NewRequestWithContext(ctx, "POST", url.String(), f)
123 if err != nil {
124 return "", err
125 }
126 req.ContentLength = a.info.Size()
127 req.Header.Set("Content-Type", "application/octet-stream")
128 req.Header.Set("Accept", "application/vnd.github+json")
129 // Without GetBody a redirect re-reads an exhausted reader.
130 req.GetBody = open
131
132 // The request is hand-built and sent with DoRequest rather than Request so
133 // it can set ContentLength and GetBody, which Request cannot express.
134 resp, err := u.client.DoRequest(req)
135 if err != nil {
136 return "", err
137 }
138 defer resp.Body.Close()
139
140 var asset struct {
141 URL string `json:"url"`
142 }
143 if err := json.NewDecoder(resp.Body).Decode(&asset); err != nil {
144 return "", err
145 }
146 if asset.URL == "" {
147 return "", errors.New("the server returned no asset URL")
148 }
149
150 return asset.URL, nil
151}
152
153// newUploadError captures the status code so the message can name what the
154// endpoint refused.

Callers 1

uploadMethod · 0.95

Calls 10

JoinPathWithHostPrefixFunction · 0.92
UserAssetUploadPrefixFunction · 0.92
openFunction · 0.85
SetQueryMethod · 0.80
BaseMethod · 0.80
DoRequestMethod · 0.80
CloseMethod · 0.65
StringMethod · 0.65
SizeMethod · 0.65
SetMethod · 0.65

Tested by

no test coverage detected