Skip to content

Commit f934db6

Browse files
authored
Maintain range type when fixing to local package version (#355)
1 parent 86dce73 commit f934db6

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

lib/dependency-versions.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -287,6 +287,14 @@ export function fixMismatchingVersions(
287287
continue;
288288
}
289289

290+
if (localPackage && localPackage.packageJson.version === fixedVersion) {
291+
// When fixing to the version of a local package, don't just use the bare package version, but include the highest range type we have seen.
292+
const highestRangeTypeSeen = getHighestRangeType(
293+
versions.map((versionRange) => versionRangeToRange(versionRange))
294+
);
295+
fixedVersion = `${highestRangeTypeSeen}${semver.coerce(fixedVersion)}`;
296+
}
297+
290298
// Update the dependency version in each package.json.
291299
let isFixed = false;
292300
for (const package_ of packages) {
@@ -390,3 +398,9 @@ export function getLatestVersion(versions: string[]): string {
390398
const sortedVersions = versions.sort(compareVersionRanges);
391399
return sortedVersions[sortedVersions.length - 1]; // Latest version will be sorted to end of list.
392400
}
401+
402+
// Example input: ['~', '^'], output: '^'
403+
export function getHighestRangeType(ranges: string[]): string {
404+
const sorted = ranges.sort(compareRanges);
405+
return sorted[sorted.length - 1]; // Range with highest precedence will be sorted to end of list.
406+
}

test/lib/dependency-versions-test.ts

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
compareRanges,
99
versionRangeToRange,
1010
getLatestVersion,
11+
getHighestRangeType,
1112
} from '../../lib/dependency-versions.js';
1213
import { getPackages } from '../../lib/workspace.js';
1314
import {
@@ -632,7 +633,7 @@ describe('Utils | dependency-versions', function () {
632633

633634
expect(
634635
packageJson1.dependencies && packageJson1.dependencies['package2']
635-
).toStrictEqual('2.0.0');
636+
).toStrictEqual('^2.0.0');
636637

637638
expect(
638639
packageJson2.dependencies && packageJson2.dependencies['package1']
@@ -785,4 +786,14 @@ describe('Utils | dependency-versions', function () {
785786
).toThrowErrorMatchingInlineSnapshot('"Invalid Version: foo"');
786787
});
787788
});
789+
790+
describe('#getHighestRangeType', function () {
791+
it('behaves correctly', function () {
792+
expect(getHighestRangeType(['', ''])).toStrictEqual('');
793+
expect(getHighestRangeType(['^', ''])).toStrictEqual('^');
794+
expect(getHighestRangeType(['~', ''])).toStrictEqual('~');
795+
expect(getHighestRangeType(['~', '^'])).toStrictEqual('^');
796+
expect(getHighestRangeType(['^', '~'])).toStrictEqual('^');
797+
});
798+
});
788799
});

0 commit comments

Comments
 (0)