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)
| 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. |
| 108 | func (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 | |
| 161 | func (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)", |