diff --git a/.changeset/grumpy-insects-flow.md b/.changeset/grumpy-insects-flow.md new file mode 100644 index 000000000000..cac8f1a6a1e5 --- /dev/null +++ b/.changeset/grumpy-insects-flow.md @@ -0,0 +1,5 @@ +--- +'svelte-migrate': patch +--- + +chore: insert package at sorted position diff --git a/packages/migrate/utils.js b/packages/migrate/utils.js index 7549bf5b908e..a01be4bde3f6 100644 --- a/packages/migrate/utils.js +++ b/packages/migrate/utils.js @@ -1,10 +1,10 @@ -import fs from 'node:fs'; -import path from 'node:path'; import colors from 'kleur'; -import ts from 'typescript'; import MagicString from 'magic-string'; import { execFileSync, execSync } from 'node:child_process'; +import fs from 'node:fs'; +import path from 'node:path'; import semver from 'semver'; +import ts from 'typescript'; /** @param {string} message */ export function bail(message) { @@ -235,7 +235,15 @@ export function update_pkg(content, updates) { if (insert && !pkg[insert]?.[name]) { if (!pkg[insert]) pkg[insert] = {}; - pkg[insert][name] = version; + + // Insert the property in sorted position without adjusting other positions so diffs are easier to read + const sorted_keys = Object.keys(pkg[insert]).sort(); + const index = sorted_keys.findIndex((key) => name.localeCompare(key) === -1); + const insert_index = index !== -1 ? index : sorted_keys.length; + const new_properties = Object.entries(pkg[insert]); + new_properties.splice(insert_index, 0, [name, version]); + pkg[insert] = Object.fromEntries(new_properties); + log_migration(`Added ${name} version ${version} ${additional}`); } } diff --git a/packages/migrate/utils.spec.js b/packages/migrate/utils.spec.js new file mode 100644 index 000000000000..cd9437e2968f --- /dev/null +++ b/packages/migrate/utils.spec.js @@ -0,0 +1,73 @@ +import { assert, test } from 'vitest'; +import { update_pkg } from './utils.js'; + +test('Inserts package at correct position (1)', () => { + const result = update_pkg( + `{ + "dependencies": { + "a": "1", + "z": "3", + "c": "4" + } +}`, + [['b', '2', '', 'dependencies']] + ); + + assert.equal( + result, + `{ + "dependencies": { + "a": "1", + "b": "2", + "z": "3", + "c": "4" + } +}` + ); +}); + +test('Inserts package at correct position (2)', () => { + const result = update_pkg( + `{ + "dependencies": { + "a": "1", + "b": "2" + } +}`, + [['c', '3', '', 'dependencies']] + ); + + assert.equal( + result, + `{ + "dependencies": { + "a": "1", + "b": "2", + "c": "3" + } +}` + ); +}); + +test('Inserts package at correct position (3)', () => { + const result = update_pkg( + `{ + "dependencies": { + "b": "2", + "c": "3" + } +}`, + [['a', '1', '', 'dependencies']] + ); + + assert.equal( + result, + `{ + "dependencies": { + "a": "1", + "b": "2", + "c": "3" + } +}` + ); +});