-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
index.ts
290 lines (253 loc) · 8.42 KB
/
index.ts
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
import is from '@sindresorhus/is';
import { DateTime } from 'luxon';
import type { XmlDocument } from 'xmldoc';
import { GlobalConfig } from '../../../config/global';
import { logger } from '../../../logger';
import * as packageCache from '../../../util/cache/package';
import { cache } from '../../../util/cache/package/decorator';
import { newlineRegex, regEx } from '../../../util/regex';
import { ensureTrailingSlash } from '../../../util/url';
import mavenVersion from '../../versioning/maven';
import * as mavenVersioning from '../../versioning/maven';
import { compare } from '../../versioning/maven/compare';
import { Datasource } from '../datasource';
import type {
GetReleasesConfig,
PostprocessReleaseConfig,
PostprocessReleaseResult,
RegistryStrategy,
Release,
ReleaseResult,
} from '../types';
import { MAVEN_REPO } from './common';
import type { MavenDependency, ReleaseMap } from './types';
import {
checkResource,
createUrlForDependencyPom,
downloadHttpProtocol,
downloadMavenXml,
getDependencyInfo,
getDependencyParts,
getMavenUrl,
} from './util';
function getLatestSuitableVersion(releases: Release[]): string | null {
// istanbul ignore if
if (!releases?.length) {
return null;
}
const allVersions = releases.map(({ version }) => version);
const stableVersions = allVersions.filter((x) => mavenVersion.isStable(x));
const versions = stableVersions.length ? stableVersions : allVersions;
return versions.reduce((latestVersion, version) =>
compare(version, latestVersion) === 1
? version
: /* istanbul ignore next: hard to test */ latestVersion,
);
}
function extractVersions(metadata: XmlDocument): string[] {
const versions = metadata.descendantWithPath('versioning.versions');
const elements = versions?.childrenNamed('version');
if (!elements) {
return [];
}
return elements.map((el) => el.val);
}
const mavenCentralHtmlVersionRegex = regEx(
'^<a href="(?<version>[^"]+)/" title="(?:[^"]+)/">(?:[^"]+)/</a>\\s+(?<releaseTimestamp>\\d\\d\\d\\d-\\d\\d-\\d\\d \\d\\d:\\d\\d)\\s+-$',
'i',
);
export const defaultRegistryUrls = [MAVEN_REPO];
export class MavenDatasource extends Datasource {
static id = 'maven';
override readonly caching = true;
override readonly defaultRegistryUrls = defaultRegistryUrls;
override readonly defaultVersioning: string = mavenVersioning.id;
override readonly registryStrategy: RegistryStrategy = 'merge';
override readonly releaseTimestampSupport = true;
override readonly releaseTimestampNote =
'The release timestamp is determined from the `Last-Modified` header or the `lastModified` field in the results.';
override readonly sourceUrlSupport = 'package';
override readonly sourceUrlNote =
'The source URL is determined from the `scm` tags in the results.';
constructor(id = MavenDatasource.id) {
super(id);
}
async fetchReleasesFromMetadata(
dependency: MavenDependency,
repoUrl: string,
): Promise<ReleaseMap> {
const metadataUrl = getMavenUrl(dependency, repoUrl, 'maven-metadata.xml');
const cacheNamespace = 'datasource-maven:metadata-xml';
const cacheKey = metadataUrl.toString();
const cachedVersions = await packageCache.get<ReleaseMap>(
cacheNamespace,
cacheKey,
);
/* istanbul ignore if */
if (cachedVersions) {
return cachedVersions;
}
const { isCacheable, xml: mavenMetadata } = await downloadMavenXml(
this.http,
metadataUrl,
);
if (!mavenMetadata) {
return {};
}
const versions = extractVersions(mavenMetadata);
const releaseMap = versions.reduce(
(acc, version) => ({ ...acc, [version]: null }),
{},
);
const cachePrivatePackages = GlobalConfig.get(
'cachePrivatePackages',
false,
);
if (cachePrivatePackages || isCacheable) {
await packageCache.set(cacheNamespace, cacheKey, releaseMap, 30);
}
return releaseMap;
}
async addReleasesFromIndexPage(
inputReleaseMap: ReleaseMap,
dependency: MavenDependency,
repoUrl: string,
): Promise<ReleaseMap> {
if (!repoUrl.startsWith(MAVEN_REPO)) {
return inputReleaseMap;
}
const cacheNs = 'datasource-maven:index-html-releases';
const cacheKey = `${repoUrl}${dependency.dependencyUrl}`;
let workingReleaseMap = await packageCache.get<ReleaseMap>(
cacheNs,
cacheKey,
);
if (!workingReleaseMap) {
workingReleaseMap = {};
let retryEarlier = false;
try {
const indexUrl = getMavenUrl(dependency, repoUrl, 'index.html');
const res = await downloadHttpProtocol(this.http, indexUrl);
if (res) {
for (const line of res.body.split(newlineRegex)) {
const match = line.trim().match(mavenCentralHtmlVersionRegex);
if (match) {
const { version, releaseTimestamp: timestamp } =
match?.groups ?? /* istanbul ignore next: hard to test */ {};
if (version && timestamp) {
const date = DateTime.fromFormat(
timestamp,
'yyyy-MM-dd HH:mm',
{
zone: 'UTC',
},
);
if (date.isValid) {
const releaseTimestamp = date.toISO();
workingReleaseMap[version] = { version, releaseTimestamp };
}
}
}
}
}
} catch (err) /* istanbul ignore next */ {
retryEarlier = true;
logger.debug(
{ dependency, err },
'Failed to get releases from index.html',
);
}
const cacheTTL = retryEarlier
? /* istanbul ignore next: hard to test */ 60
: 24 * 60;
await packageCache.set(cacheNs, cacheKey, workingReleaseMap, cacheTTL);
}
const releaseMap = { ...inputReleaseMap };
for (const version of Object.keys(releaseMap)) {
releaseMap[version] ||= workingReleaseMap[version] ?? null;
}
return releaseMap;
}
getReleasesFromMap(releaseMap: ReleaseMap): Release[] {
const releases = Object.values(releaseMap).filter(is.truthy);
if (releases.length) {
return releases;
}
return Object.keys(releaseMap).map((version) => ({ version }));
}
async getReleases({
packageName,
registryUrl,
}: GetReleasesConfig): Promise<ReleaseResult | null> {
// istanbul ignore if
if (!registryUrl) {
return null;
}
const dependency = getDependencyParts(packageName);
const repoUrl = ensureTrailingSlash(registryUrl);
logger.debug(`Looking up ${dependency.display} in repository ${repoUrl}`);
let releaseMap = await this.fetchReleasesFromMetadata(dependency, repoUrl);
releaseMap = await this.addReleasesFromIndexPage(
releaseMap,
dependency,
repoUrl,
);
const releases = this.getReleasesFromMap(releaseMap);
if (!releases?.length) {
return null;
}
logger.debug(
`Found ${releases.length} new releases for ${dependency.display} in repository ${repoUrl}`,
);
const latestSuitableVersion = getLatestSuitableVersion(releases);
const dependencyInfo =
latestSuitableVersion &&
(await getDependencyInfo(
this.http,
dependency,
repoUrl,
latestSuitableVersion,
));
const result: ReleaseResult = {
...dependency,
...dependencyInfo,
releases,
};
if (!this.defaultRegistryUrls.includes(registryUrl)) {
result.isPrivate = true;
}
return result;
}
@cache({
namespace: `datasource-maven`,
key: (
{ registryUrl, packageName }: PostprocessReleaseConfig,
{ version }: Release,
) => `postprocessRelease:${registryUrl}:${packageName}:${version}`,
ttlMinutes: 24 * 60,
})
override async postprocessRelease(
{ packageName, registryUrl }: PostprocessReleaseConfig,
release: Release,
): Promise<PostprocessReleaseResult> {
if (!packageName || !registryUrl) {
return release;
}
const dependency = getDependencyParts(packageName);
const pomUrl = await createUrlForDependencyPom(
this.http,
release.version,
dependency,
registryUrl,
);
const artifactUrl = getMavenUrl(dependency, registryUrl, pomUrl);
const res = await checkResource(this.http, artifactUrl);
if (res === 'not-found' || res === 'error') {
return 'reject';
}
if (is.date(res)) {
release.releaseTimestamp = res.toISOString();
}
return release;
}
}