/
range.ts
538 lines (507 loc) · 14.6 KB
/
range.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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
import { gte, lt, lte, satisfies } from '@renovatebot/pep440';
import { parse as parseRange } from '@renovatebot/pep440/lib/specifier.js';
import { parse as parseVersion } from '@renovatebot/pep440/lib/version.js';
import { logger } from '../../../logger';
import { regEx } from '../../../util/regex';
import type { NewValueConfig } from '../types';
const UserPolicy = {
Major: 0,
Minor: 1,
Micro: 2,
Bug: 3,
0: 'Major',
1: 'Minor',
2: 'Micro',
3: 'Bug',
None: Infinity,
} as const;
type UserPolicy = typeof UserPolicy[keyof typeof UserPolicy];
/**
* Calculate current update range precision.
* @param ranges A {@link Range} consists of current range
* @returns A {@link UserPolicy}
*/
function getRangePrecision(ranges: Range[]): UserPolicy {
const bound: number[] =
parseVersion((ranges[1] || ranges[0]).version)?.release ?? [];
let rangePrecision = -1;
// range is defined by a single bound.
// ie. <1.2.2.3,
// >=7
if (ranges.length === 1) {
rangePrecision = bound.length - 1;
}
// Range is defined by both upper and lower bounds.
if (ranges.length === 2) {
const lowerBound: number[] = parseVersion(ranges[0].version)?.release ?? [];
rangePrecision = bound.findIndex((el, index) => el > lowerBound[index]);
}
// Tune down Major precision if followed by a zero
if (
rangePrecision === UserPolicy.Major &&
rangePrecision + 1 < bound.length &&
bound[rangePrecision + 1] === 0
) {
rangePrecision++;
}
// Could not calculate user precision
// Default to the smallest possible
// istanbul ignore next
if (rangePrecision === -1) {
rangePrecision = bound.length - 1;
}
const key = UserPolicy[rangePrecision as keyof typeof UserPolicy];
return UserPolicy[key as keyof typeof UserPolicy];
}
/**
* @param policy Required range precision
* @param newVersion The newly accepted version
* @param baseVersion Optional Current upper bound
* @returns A string represents a future version upper bound.
*/
function getFutureVersion(
policy: UserPolicy,
newVersion: string,
baseVersion?: string
): number[] {
const toRelease: number[] = parseVersion(newVersion)?.release ?? [];
const baseRelease: number[] =
parseVersion(baseVersion ?? newVersion)?.release ?? [];
return baseRelease.map((_, index) => {
const toPart: number = toRelease[index] ?? 0;
if (index < policy) {
return toPart;
}
if (index === policy) {
return toPart + (baseVersion === undefined ? 0 : 1);
}
return 0;
});
}
interface Range {
operator: string;
prefix?: string;
version: string;
}
export function getNewValue({
currentValue,
rangeStrategy,
currentVersion,
newVersion,
isReplacement,
}: NewValueConfig): string | null {
let ranges: Range[];
let updatedRange: (string | null)[];
if (rangeStrategy === 'pin' && !isReplacement) {
return '==' + newVersion;
}
// no symbol: accept only that specific version specified
if (currentValue === currentVersion || isReplacement) {
return newVersion;
}
try {
ranges = parseCurrentRange(currentValue);
if (!ranges.length) {
// an empty string is an allowed value for PEP440 range
// it means get any version
logger.warn('Empty currentValue: ' + currentValue);
return currentValue;
}
} catch (err) {
logger.warn({ currentValue, err }, 'Unexpected range error');
return null;
}
switch (rangeStrategy) {
case 'auto':
case 'replace':
updatedRange = handleReplaceStrategy(
{
currentValue,
rangeStrategy,
currentVersion,
newVersion,
},
ranges
);
break;
case 'widen':
updatedRange = handleWidenStrategy(
{
currentValue,
rangeStrategy,
currentVersion,
newVersion,
},
ranges
);
break;
case 'bump':
updatedRange = handleBumpStrategy(
{
currentValue,
rangeStrategy,
currentVersion,
newVersion,
},
ranges
);
break;
default:
// Unsupported rangeStrategy
// Valid rangeStrategy values are: bump, extend, pin, replace.
// https://docs.renovatebot.com/modules/versioning/#pep440-versioning
logger.debug(
'Unsupported rangeStrategy: ' +
rangeStrategy +
'. Using "replace" instead.'
);
return getNewValue({
currentValue,
rangeStrategy: 'replace',
currentVersion,
newVersion,
});
}
let result = updatedRange.filter(Boolean).join(', ');
if (result.includes(', ') && !currentValue.includes(', ')) {
result = result.replace(regEx(/, /g), ',');
}
const checkedResult = checkRangeAndRemoveUnnecessaryRangeLimit(
result,
newVersion
);
if (!satisfies(newVersion, checkedResult)) {
// we failed at creating the range
logger.warn(
{ result, newVersion, currentValue },
'pep440: failed to calculate newValue'
);
return null;
}
return checkedResult;
}
export function isLessThanRange(input: string, range: string): boolean {
try {
let invertResult = true;
const results = range
.split(',')
.map((x) =>
x
.replace(regEx(/\s*/g), '')
.split(regEx(/(~=|==|!=|<=|>=|<|>|===)/))
.slice(1)
)
.map(([op, version]) => {
if (['!=', '<=', '<'].includes(op)) {
return true;
}
invertResult = false;
if (['~=', '==', '>=', '==='].includes(op)) {
return lt(input, version);
}
if (op === '>') {
return lte(input, version);
}
// istanbul ignore next
return false;
});
const result = results.every((res) => res === true);
return invertResult ? !result : result;
} catch (err) /* istanbul ignore next */ {
return false;
}
}
function parseCurrentRange(currentValue: string): Range[] {
const ranges: Range[] = parseRange(currentValue);
if (!ranges) {
throw new TypeError('Invalid pep440 currentValue');
}
if (ranges.some((range) => range.operator === '===')) {
// the operator "===" is used for legacy non PEP440 versions
throw new TypeError('PEP440 arbitrary equality (===) not supported');
}
return ranges;
}
function handleLowerBound(range: Range, newVersion: string): string | null {
// used to mark minimum supported version
// lower the bound if the new version is lower than current range
if (['>', '>='].includes(range.operator)) {
if (lte(newVersion, range.version)) {
// this looks like a rollback
return '>=' + newVersion;
}
// otherwise, treat it same as exclude
return range.operator + range.version;
}
// istanbul ignore next
return null;
}
function handleUpperBound(range: Range, newVersion: string): string | null {
// this is used to exclude future versions
if (range.operator === '<') {
// if newVersion is that future version
if (gte(newVersion, range.version)) {
// now here things get tricky
// we calculate the new future version
const precision = getRangePrecision([range]);
const futureVersion = getFutureVersion(
precision,
newVersion,
range.version
);
return range.operator + futureVersion.join('.');
}
// newVersion is in range, for other than "replace" strategies
return range.operator + range.version;
}
// istanbul ignore next
return null;
}
function updateRangeValue(
{ currentValue, rangeStrategy, currentVersion, newVersion }: NewValueConfig,
range: Range
): string | null {
// used to exclude versions,
// we assume that's for a good reason
if (range.operator === '!=') {
return range.operator + range.version;
}
// keep the .* suffix
if (range.prefix) {
const futureVersion = getFutureVersion(
UserPolicy.None,
newVersion,
range.version
).join('.');
return range.operator + futureVersion + '.*';
}
if (range.operator === '~=') {
const baseVersion = parseVersion(range.version)?.release ?? [];
const futureVersion = parseVersion(newVersion)?.release ?? [];
const baseLen = baseVersion.length;
const newVerLen = futureVersion.length;
// trim redundant trailing version specifiers
if (baseLen < newVerLen) {
return (
range.operator + futureVersion.slice(0, baseVersion.length).join('.')
);
}
// pad with specifiers
if (baseLen > newVerLen) {
for (let i = baseLen - newVerLen - 1; i >= 0; i--) {
futureVersion.push(0);
}
return range.operator + futureVersion.join('.');
}
return range.operator + newVersion;
}
if (['==', '<='].includes(range.operator)) {
if (lte(newVersion, range.version)) {
return range.operator + range.version;
}
return range.operator + newVersion;
}
let output = handleUpperBound(range, newVersion);
if (output) {
// manged to update upperbound
// no need to try anything else
return output;
}
output = handleLowerBound(range, newVersion);
if (output) {
return output;
}
// unless PEP440 changes, this won't happen
// istanbul ignore next
logger.error(
{ newVersion, currentValue, range },
'pep440: failed to process range'
);
// istanbul ignore next
return null;
}
/**
* Checks for zero specifiers.
* returns true if one of the bounds' length is < 3.
* @param ranges A {@link Range} array.
* @returns A boolean value
* Used mainly for cosmetics for the rez versioning syntax.
*/
function hasZeroSpecifier(ranges: Range[]): boolean {
return ranges.some((range) => {
const release = parseVersion(range.version)?.release;
return release && release.length < 3;
});
}
function trimTrailingZeros(numbers: number[]): number[] {
let i = numbers.length - 1;
while (numbers[i] === 0) {
i--;
}
return numbers.slice(0, i + 1);
}
function divideCompatibleReleaseRange(currentRange: Range): Range[] {
const currentVersionUpperBound = currentRange.version
.split('.')
.map((num) => parseInt(num));
if (currentVersionUpperBound.length > 1) {
currentVersionUpperBound.splice(-1);
}
currentVersionUpperBound[currentVersionUpperBound.length - 1] += 1;
return [
{ operator: '>=', version: currentRange.version },
{
operator: '<',
version: currentVersionUpperBound.join('.'),
},
];
}
function handleWidenStrategy(
{ currentValue, rangeStrategy, currentVersion, newVersion }: NewValueConfig,
ranges: Range[]
): (string | null)[] {
// newVersion is within range
if (satisfies(newVersion, currentValue)) {
return [currentValue];
}
let rangePrecision = getRangePrecision(ranges);
const trimZeros = hasZeroSpecifier(ranges);
let newRanges: Range[] = [];
if (ranges.length === 1 && ranges[0].operator === '~=') {
// If range operator is '~=', divide the range into its logical equivalent.
// Example: ~=1.0 --> >=1.0,<2
newRanges = divideCompatibleReleaseRange(ranges[0]);
} else {
newRanges = ranges;
}
return newRanges.map((range) => {
// newVersion is over the upper bound
if (range.operator === '<' && gte(newVersion, range.version)) {
const upperBound = parseVersion(range.version)?.release ?? [];
const len = upperBound.length;
// Match the precision of the smallest specifier if other than 0
if (upperBound[len - 1] !== 0) {
const key = UserPolicy[(len - 1) as keyof typeof UserPolicy];
rangePrecision = UserPolicy[key as keyof typeof UserPolicy];
}
let futureVersion = getFutureVersion(
rangePrecision,
newVersion,
range.version
);
if (trimZeros) {
futureVersion = trimTrailingZeros(futureVersion);
}
return range.operator + futureVersion.join('.');
}
// default
return updateRangeValue(
{
currentValue,
rangeStrategy,
currentVersion,
newVersion,
},
range
);
});
}
function handleReplaceStrategy(
{ currentValue, rangeStrategy, currentVersion, newVersion }: NewValueConfig,
ranges: Range[]
): (string | null)[] {
// newVersion is within range
if (satisfies(newVersion, currentValue)) {
return [currentValue];
}
const trimZeros = hasZeroSpecifier(ranges);
return ranges.map((range) => {
// newVersion is over the upper bound
if (range.operator === '<' && gte(newVersion, range.version)) {
const rangePrecision = getRangePrecision(ranges);
let futureVersion = getFutureVersion(
rangePrecision,
newVersion,
range.version
);
if (trimZeros) {
futureVersion = trimTrailingZeros(futureVersion);
}
return range.operator + futureVersion.join('.');
}
// handle lower bound
if (['>', '>='].includes(range.operator)) {
if (lte(newVersion, range.version)) {
// this looks like a rollback
return '>=' + newVersion;
}
// update the lower bound to reflect the accepted new version
const lowerBound = parseVersion(range.version)?.release ?? [];
const rangePrecision = lowerBound.length - 1;
let newBase = getFutureVersion(rangePrecision, newVersion);
if (trimZeros) {
newBase = trimTrailingZeros(newBase);
}
// trim last element of the newBase when new accepted version is out of range.
// example: let new bound be >8.2.5 & newVersion be 8.2.5
// return value will be: >8.2
if (range.operator === '>') {
if (newVersion === newBase.join('.') && newBase.length > 1) {
newBase.pop();
}
}
return range.operator + newBase.join('.');
}
// default
return updateRangeValue(
{
currentValue,
rangeStrategy,
currentVersion,
newVersion,
},
range
);
});
}
function handleBumpStrategy(
{ currentValue, rangeStrategy, currentVersion, newVersion }: NewValueConfig,
ranges: Range[]
): (string | null)[] {
return ranges.map((range) => {
// bump lower bound to current new version
if (range.operator === '>=') {
return range.operator + newVersion;
}
return updateRangeValue(
{
currentValue,
rangeStrategy,
currentVersion,
newVersion,
},
range
);
});
}
export function checkRangeAndRemoveUnnecessaryRangeLimit(
rangeInput: string,
newVersion: string
): string {
let newRange: string = rangeInput;
if (rangeInput.includes(',')) {
const newRes = rangeInput.split(',');
if (
newRes[0].includes('.*') &&
newRes[0].includes('==') &&
newRes[1].includes('>=')
) {
if (satisfies(newVersion, newRes[0])) {
newRange = newRes[0];
}
}
} else {
return rangeInput;
}
return newRange;
}