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

Method download

script/ghmock/schemafiles.go:108–159  ·  view source on GitHub ↗

download fetches the file to path. It checks the file and writes it to a temporary file first, so a failed download never replaces a good copy.

(path string, progress io.Writer)

Source from the content-addressed store, hash-verified

106// download fetches the file to path. It checks the file and writes it to a
107// temporary file first, so a failed download never replaces a good copy.
108func (s schemaSource) download(path string, progress io.Writer) error {
109 dir := filepath.Dir(path)
110 if err := os.MkdirAll(dir, 0o755); err != nil {
111 return err
112 }
113 fmt.Fprintf(progress, "ghmock: downloading GitHub's %s to %s\n", s.label, path)
114
115 req, err := http.NewRequest(http.MethodGet, s.url, nil)
116 if err != nil {
117 return err
118 }
119 req.Header.Set("User-Agent", "ghmock")
120 resp, err := downloadClient.Do(req)
121 if err != nil {
122 return s.downloadError(err)
123 }
124 defer resp.Body.Close()
125 if resp.StatusCode != http.StatusOK {
126 return s.downloadError(fmt.Errorf("HTTP %d", resp.StatusCode))
127 }
128 data, err := io.ReadAll(io.LimitReader(resp.Body, maxSchemaSize+1))
129 switch {
130 case err != nil:
131 return s.downloadError(err)
132 case len(data) > maxSchemaSize:
133 return s.downloadError(fmt.Errorf("file is larger than %d MB", maxSchemaSize>>20))
134 case len(data) == 0:
135 return s.downloadError(errors.New("file is empty"))
136 }
137 if err := s.validate(data); err != nil {
138 return s.downloadError(fmt.Errorf("not a usable %s: %w", s.label, err))
139 }
140
141 tmp, err := os.CreateTemp(dir, filepath.Base(path)+".*.tmp")
142 if err != nil {
143 return err
144 }
145 defer os.Remove(tmp.Name())
146 _, err = tmp.Write(data)
147 if err == nil {
148 // CreateTemp makes files only their owner can read. A sandboxed
149 // agent may run as another user.
150 err = tmp.Chmod(0o644)
151 }
152 if closeErr := tmp.Close(); err == nil {
153 err = closeErr
154 }
155 if err != nil {
156 return err
157 }
158 return os.Rename(tmp.Name(), path)
159}
160
161func (s schemaSource) downloadError(err error) error {
162 return fmt.Errorf("downloading GitHub's %s from %s: %w (without network access, set %s to a local copy)",

Callers 2

locateMethod · 0.95
cmdSchemasFunction · 0.80

Calls 11

downloadErrorMethod · 0.95
MkdirAllMethod · 0.80
validateMethod · 0.80
BaseMethod · 0.80
SetMethod · 0.65
DoMethod · 0.65
CloseMethod · 0.65
ErrorfMethod · 0.65
RemoveMethod · 0.65
NameMethod · 0.65
WriteMethod · 0.65

Tested by

no test coverage detected