From 084e11eed35696abb8256300eafc9375ba8be3dd Mon Sep 17 00:00:00 2001 From: Stephen Zhou Date: Thu, 11 Apr 2024 16:51:38 +0800 Subject: [PATCH] feat: packageSortOrder option --- lib/__snapshots__/index.test.js.snap | 43 ++++++++++++++++++++++++++++ lib/index.cjs | 21 +++++++++++++- lib/index.test.js | 11 +++++++ 3 files changed, 74 insertions(+), 1 deletion(-) diff --git a/lib/__snapshots__/index.test.js.snap b/lib/__snapshots__/index.test.js.snap index ea848fd..fa56e1c 100644 --- a/lib/__snapshots__/index.test.js.snap +++ b/lib/__snapshots__/index.test.js.snap @@ -42,3 +42,46 @@ exports[`format should be correct 1`] = ` } " `; + +exports[`format should follow custom order 1`] = ` +"{ + "version": "", + "name": "", + "description": "", + "keywords": [ + "C", + "B", + "A" + ], + "license": "", + "author": "", + "scripts": { + "prebuild": "", + "build": "", + "postbuild": "", + "dev": "", + "lint": "", + "start": "", + "pretest": "", + "test": "", + "posttest": "" + }, + "dependencies": { + "A": "*", + "B": "*" + }, + "devDependencies": { + "A": "*", + "B": "*" + }, + "peerDependencies": { + "A": "*", + "B": "*" + }, + "optionalDependencies": { + "A": "*", + "B": "*" + } +} +" +`; diff --git a/lib/index.cjs b/lib/index.cjs index a47f231..7e8b116 100644 --- a/lib/index.cjs +++ b/lib/index.cjs @@ -22,8 +22,27 @@ exports.parsers = { if (parser.preprocess) { text = parser.preprocess(text, options) } + const sortPackageJsonOptions = + options.packageSortOrder.length !== 0 + ? { + sortOrder: options.packageSortOrder, + } + : undefined - return testPath(options.filepath) ? sortPackageJson.default(text) : text + return testPath(options.filepath) + ? sortPackageJson.default(text, sortPackageJsonOptions) + : text }, }, } + +/** @type {import('prettier').Plugin['options']} */ +exports.options = { + packageSortOrder: { + category: 'Global', + type: 'string', + array: true, + default: [{ value: [] }], + description: 'Custom ordering array', + }, +} diff --git a/lib/index.test.js b/lib/index.test.js index 65b3010..32688ad 100644 --- a/lib/index.test.js +++ b/lib/index.test.js @@ -71,4 +71,15 @@ describe('format', () => { delete parsers['json-stringify'].preprocess }) + + it('should follow custom order', () => + expect( + Promise.resolve( + prettier.format(uglyJson, { + filepath: 'package.json', + plugins: ['./lib/index.cjs'], + packageSortOrder: ['version', 'name'], + }), + ), + ).resolves.toMatchSnapshot()) })