-
Notifications
You must be signed in to change notification settings - Fork 51
/
pypi.go
87 lines (75 loc) · 2.53 KB
/
pypi.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package pkgmanager
import (
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"github.com/ossf/package-analysis/internal/utils"
"github.com/ossf/package-analysis/pkg/api/pkgecosystem"
)
// pypiPackageInfoJSON represents relevant JSON data from the PyPI web API response
// when package information is requested. The differences in response format between
// (valid) requests made with a specific package version and with no package version
// are not significant in our case.
// (In particular, if the request contains a valid version, Urls contains a single entry
// holding information for that package version. If the version is unspecified, Urls contains
// an entry corresponding to each version of the package available on PyPI.)
// See https://warehouse.pypa.io/api-reference/json.html and https://peps.python.org/pep-0691
type pypiPackageInfoJSON struct {
Info struct {
Version string `json:"version"`
} `json:"info"`
URLs []struct {
PackageType string `json:"packagetype"`
URL string `json:"url"`
} `json:"urls"`
}
func getPyPILatest(pkg string) (string, error) {
resp, err := http.Get(fmt.Sprintf("https://pypi.org/pypi/%s/json", pkg))
if err != nil {
return "", err
}
defer resp.Body.Close()
decoder := json.NewDecoder(resp.Body)
var details pypiPackageInfoJSON
err = decoder.Decode(&details)
if err != nil {
return "", err
}
return details.Info.Version, nil
}
func getPyPIArchiveURL(pkgName, version string) (string, error) {
resp, err := http.Get(fmt.Sprintf("https://pypi.org/pypi/%s/%s/json", pkgName, version))
if err != nil {
return "", err
}
defer resp.Body.Close()
responseBytes, err := io.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("error reading HTTP response: %w", err)
}
responseString := string(responseBytes)
decoder := json.NewDecoder(strings.NewReader(responseString))
var packageInfo pypiPackageInfoJSON
err = decoder.Decode(&packageInfo)
if err != nil {
// invalid version, non-existent package, etc. Details in responseString
return "", fmt.Errorf("%w. PyPI response: %s", err, responseString)
}
// Need to find the archive with PackageType == "sdist"
for _, url := range packageInfo.URLs {
if url.PackageType == "sdist" {
return url.URL, nil
}
}
// Return an empty string and no error if we can't find an archive URL.
return "", nil
}
var pypiPkgManager = PkgManager{
ecosystem: pkgecosystem.PyPI,
latestVersion: getPyPILatest,
archiveURL: getPyPIArchiveURL,
archiveFilename: defaultArchiveFilename,
extractArchive: utils.ExtractArchiveFile,
}