-
Notifications
You must be signed in to change notification settings - Fork 6
/
action.php
199 lines (169 loc) · 6.05 KB
/
action.php
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
<?php declare(strict_types=1);
use GuzzleHttp\{
Client,
Exception\ClientException,
};
require 'vendor/autoload.php';
/**
* Get an env var as a string
*
* @param string $name
* @return string
*/
function env(string $name) : string {
return trim((string) getenv($name));
}
/**
* Fail the script with a message
*
* @param string $message
* @return void
*/
function fail(string $message) : void {
halt($message, 1);
}
/**
* Halt the script with a message
*
* @param string $message
* @param int $code
* @return void
*/
function halt(string $message, int $code = 0) : void {
echo trim($message) . PHP_EOL;
exit($code);
}
/**
* Output a debug message
*
* @param string $message
* @return void
*/
function debug(string $message) : void {
echo trim($message) . PHP_EOL;
}
/**
* Check if a version is semantic or not
*
* @see https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string
* @param string $version
* @return bool
*/
function isSemanticVersion(string $version) : bool {
return 0 < preg_match('/^(?P<major>0|[1-9]\d*)\.(?P<minor>0|[1-9]\d*)\.(?P<patch>0|[1-9]\d*)(?:-(?P<prerelease>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+(?P<buildmetadata>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/', $version);
}
$token = env('GITHUB_TOKEN');
$keepVersions = (int) env('INPUT_KEEP_VERSIONS') ?: 5;
$keepLatest = 'true' === env('INPUT_KEEP_LATEST');
$removeSemver = 'true' === env('INPUT_REMOVE_SEMVER');
$repoNameWithOwner = env('GITHUB_REPOSITORY');
$clientId = 'navikt/remove-package-versions';
if (empty($token)) {
fail('Missing GITHUB_TOKEN');
} else if (empty($repoNameWithOwner)) {
fail('Missing GITHUB_REPOSITORY');
} else if (false === strpos($repoNameWithOwner, '/')) {
fail('Invalid GITHUB_REPOSITORY value');
}
[$owner, $repositoryName] = explode('/', $repoNameWithOwner, 2);
$client = new Client([
'base_uri' => 'https://api.github.com/',
'headers' => [
'Accept' => 'application/vnd.github.packages-preview+json', // Required header for the packages query
'Authorization' => sprintf('Bearer %s', $token),
],
]);
$packagesLimit = 100;
$versionsLimit = 100;
$getPackageVersions = <<<GET
query {
repository(owner: "%s" name: "%s") {
isPrivate
packages(first: %d orderBy:{field: CREATED_AT direction: DESC}) {
nodes {
name
versions(first: %d orderBy: {field: CREATED_AT direction: DESC}) {
totalCount
nodes {
id
version
}
}
}
}
}
}
GET;
$deletePackageVersion = <<<DELETE
mutation {
deletePackageVersion(input:{ clientMutationId: "%s" packageVersionId: "%s" }) {
success
}
}
DELETE;
try {
$response = $client->post('graphql', [
'json' => [
'query' => sprintf($getPackageVersions, $owner, $repositoryName, $packagesLimit, $versionsLimit)
],
]);
} catch (ClientException $e) {
fail(sprintf('[%s] Request for packages failed: %s', $repoNameWithOwner, $e->getResponse()->getBody()->getContents()));
}
$repository = json_decode($response->getBody()->getContents(), true)['data']['repository'] ?? null;
if (null === $repository) {
fail(sprintf('[%s] Repository not found', $repoNameWithOwner));
} else if (!$repository['isPrivate']) {
fail(sprintf('[%s] Repository is public, unable to remove package versions', $repoNameWithOwner));
}
$packageNodes = $repository['packages']['nodes'] ?? [];
if (empty($packageNodes)) {
halt(sprintf('[%s] Repository has no packages', $repoNameWithOwner));
}
$removedPackages = [];
// List of versions to always keep
$keepVersions = [
// Removing this specific version of a Docker package triggers a bug in GitHub
// Packages. Keep this safeguard until the bug has been resolved.
'docker-base-layer'
];
if ($keepLatest) {
$keepVersions[] = 'latest';
}
foreach ($packageNodes as $packageNode) {
$packageName = $packageNode['name'];
$versionNodes = $packageNode['versions']['nodes'];
$numVersions = min($versionsLimit, $packageNode['versions']['totalCount']);
if ($numVersions <= $keepVersions) {
debug(sprintf('[%s] [%s] Package has fewer than %d versions, no need for removal', $repoNameWithOwner, $packageName, $keepVersions));
continue;
}
for ($i = $keepVersions; $i < $numVersions; $i++) {
$packageVersionId = $versionNodes[$i]['id'];
$packageVersion = $versionNodes[$i]['version'];
$packageNameWithVersion = sprintf('%s:%s', $packageName, $packageVersion);
if (in_array($packageVersion, $keepVersions)) {
continue;
} else if (!$removeSemver && isSemanticVersion($packageVersion)) {
debug(sprintf('[%s] [%s] Semantic versions will not be removed unless remove-semver is set to true', $repoNameWithOwner, $packageNameWithVersion));
continue;
}
debug(sprintf('[%s] [%s] Remove package version', $repoNameWithOwner, $packageNameWithVersion));
try {
$client->post('graphql', [
'headers' => [
'Accept' => 'application/vnd.github.package-deletes-preview+json', // Header required for the deletePackageVersion mutation to be available
],
'json' => [
'query' => sprintf($deletePackageVersion, $clientId, $packageVersionId)
],
]);
} catch (ClientException $e) {
fail(sprintf('[%s] [%s] Remove package version failed: %s', $repoNameWithOwner, $packageNameWithVersion, $e->getResponse()->getBody()->getContents()));
}
$removedPackages[] = $packageNameWithVersion;
}
}
echo sprintf('::set-output name=removed_package_versions::%s', json_encode(array_map(function(string $version) use ($repoNameWithOwner) : string {
return sprintf('%s/%s', $repoNameWithOwner, $version);
}, $removedPackages))) . PHP_EOL;