Skip to content

Commit

Permalink
feat(sort-package-json): sort dependencies (#267)
Browse files Browse the repository at this point in the history
  • Loading branch information
hi-ogawa authored Aug 25, 2024
1 parent cffbe0b commit e90b5e8
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 10 deletions.
1 change: 1 addition & 0 deletions packages/sort-package-json/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"bin": "./bin/cli.js",
"files": ["dist", "bin"],
"scripts": {
"dev": "tsup --watch",
"build": "tsup",
"cli": "node ./bin/cli.js",
"cli-dev": "tsx ./src/cli.ts",
Expand Down
44 changes: 36 additions & 8 deletions packages/sort-package-json/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ Usage:
sort-package-json [package.json files...]
Examples:
# Sort package.json files in pnpm workspace
# Sort all package.json files in pnpm workspace
sort-package-json $(pnpm ls --filter '*' --depth -1 --json | jq -r '.[] | .path' | xargs -I '{}' echo '{}/package.json')
`;

Expand All @@ -36,19 +36,47 @@ function main() {

function sortPackageJson(infile: string): boolean {
const original = JSON.parse(fs.readFileSync(infile, "utf-8"));

// sort top level keys
const sorted = Object.fromEntries(
Object.entries(original).sort(
([k1], [k2]) => (RULE_MAP[k1] ?? 1e8) - (RULE_MAP[k2] ?? 1e8)
)
);
if (
JSON.stringify(Object.keys(original)) ===
JSON.stringify(Object.keys(sorted))
) {
return false;
let changed = !isEqual(Object.keys(original), Object.keys(sorted));

// sort dependencies
for (const depKey of [
"dependencies",
"devDependencies",
"dependenciesMeta",
"peerDependencies",
"peerDependenciesMeta",
"optionalDependencies",
"bundledDependencies",
"bundleDependencies",
]) {
const deps = sorted[depKey];
if (deps && typeof deps === "object") {
sorted[depKey] = Object.fromEntries(
Object.entries(deps).sort(([k1], [k2]) => k1.localeCompare(k2))
);
changed ||= !isEqual(
Object.keys(deps),
Object.keys(sorted[depKey] as any)
);
}
}
fs.writeFileSync(infile, JSON.stringify(sorted, null, 2) + "\n");
return true;

// write if changed
if (changed) {
fs.writeFileSync(infile, JSON.stringify(sorted, null, 2) + "\n");
}
return changed;
}

function isEqual(x: object, y: object) {
return JSON.stringify(x) === JSON.stringify(y);
}

main();
4 changes: 2 additions & 2 deletions packages/tiny-refresh/examples/react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@
"@hiogawa/utils": "workspace:*",
"@types/react": "^18.2.14",
"@types/react-dom": "^18.2.7",
"esbuild-loader": "^4.2.0",
"html-webpack-plugin": "^5.6.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"vite": "^5.1.3",
"esbuild-loader": "^4.2.0",
"html-webpack-plugin": "^5.6.0",
"webpack": "^5.92.0",
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^5.0.4"
Expand Down

0 comments on commit e90b5e8

Please sign in to comment.