diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c3e226..fc4e628 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased ๐Ÿ› Bugfixes +* Setting `sortArrays` now sorts arrays with mixed item types deterministically: numbers (numerically), booleans and strings first, mappings and nested lists keep their order at the end. Before, such arrays were left in an arbitrary order +* Setting `sortOrderReverse` now also applies to the default sort and to the keys following the keywords of a custom sort. Before, it only worked with `useCustomSortRecursively` +* (closes [#53](https://github.com/pascalre/vscode-yaml-sort/issues/53)) Sort an indented selection, e.g. a part of a list or the children of a nested key, without having to unindent it first. The selection keeps its indentation +* Custom sort no longer removes number, boolean and empty mapping values of custom sort keywords (`apiVersion: 3` became `apiVersion: `), and also orders keywords whose value is `0`, `false`, `null` or an empty string. Documents containing only comments can be sorted now * (closes [#180](https://github.com/pascalre/vscode-yaml-sort/issues/180)) "Format Document" and format on save no longer apply their changes twice. The formatter now only returns its edits to VS Code and always processes the whole document it was asked to format, instead of the active editor or its selection * Abort sorting when one of several yaml documents cannot be sorted. Previously the failing document was silently dropped, and a selection that could not be sorted (e.g. an indented section, refs [#53](https://github.com/pascalre/vscode-yaml-sort/issues/53)) was replaced with nothing. The success message is now only shown after the edits were applied * Keep octal values such as `0755` when the same digits appear earlier in the document. Previously the first occurrence was substituted instead of the matched value, so `z: 0755` became `z: 755` @@ -15,6 +19,9 @@ โœจ Feature * (closes [#204](https://github.com/pascalre/vscode-yaml-sort/issues/204)) Add setting `nullStyle` to define how null values are printed (`null`, `Null`, `NULL`, `~` or empty) +๐Ÿ“ฆ Dependencies +* Move `@types/js-yaml` and `@vscode/test-electron` to `devDependencies`, so they are no longer shipped with the extension + # 6.6.4 - Feb 9, 2026 ๐Ÿ“ฆ Dependencies * Update dependencies to latest versions diff --git a/package-lock.json b/package-lock.json index 7a4e345..029f0db 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,20 +9,20 @@ "version": "6.6.4", "license": "MIT", "dependencies": { - "@types/js-yaml": "^4.0.6", "@types/vscode": "^1.98.0", - "@vscode/test-electron": "^2.1.5", "cloudformation-js-yaml-schema": "^0.4.2", "glob": "^14.0.3", "homeassistant-js-yaml-schema": "^1.1.0", "js-yaml": "^4.3.2" }, "devDependencies": { + "@types/js-yaml": "^4.0.6", "@types/mocha": "^10.0.4", "@types/node": "^22.13.10", "@types/sinon": "^17.0.3", "@typescript-eslint/eslint-plugin": "^7.2.0", "@typescript-eslint/parser": "^7.2.0", + "@vscode/test-electron": "^2.1.5", "coveralls": "3.1.1", "dependency-cruiser": "^17.0.1", "eslint": "^8.57.0", @@ -843,6 +843,7 @@ "version": "4.0.9", "resolved": "https://registry.npmjs.org/@types/js-yaml/-/js-yaml-4.0.9.tgz", "integrity": "sha512-k4MGaQl5TGo/iipqb2UDG2UwjXziSWkh0uysQelTlJpX1qGlpUZYm8PnO4DxG1qBomtJUdYJ6qR6xdIah10JLg==", + "dev": true, "license": "MIT" }, "node_modules/@types/json5": { @@ -1390,6 +1391,7 @@ "version": "2.5.2", "resolved": "https://registry.npmjs.org/@vscode/test-electron/-/test-electron-2.5.2.tgz", "integrity": "sha512-8ukpxv4wYe0iWMRQU18jhzJOHkeGKbnw7xWRX3Zw1WJA4cEKbHcmmLPdPrPtL6rhDcrlCZN+xKRpv09n4gRHYg==", + "dev": true, "license": "MIT", "dependencies": { "http-proxy-agent": "^7.0.2", @@ -1472,6 +1474,7 @@ "version": "7.1.4", "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "dev": true, "license": "MIT", "engines": { "node": ">= 14" @@ -2212,6 +2215,7 @@ "version": "5.0.0", "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-5.0.0.tgz", "integrity": "sha512-aCj4O5wKyszjMmDT4tZj93kxyydN/K5zPWSCe6/0AV/AA1pqe5ZBIw0a2ZfPQV7lL5/yb5HsUreJ6UFAF1tEQw==", + "dev": true, "license": "MIT", "dependencies": { "restore-cursor": "^5.0.0" @@ -2227,6 +2231,7 @@ "version": "2.9.2", "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-2.9.2.tgz", "integrity": "sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg==", + "dev": true, "license": "MIT", "engines": { "node": ">=6" @@ -2334,6 +2339,7 @@ "version": "1.0.3", "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", + "dev": true, "license": "MIT" }, "node_modules/coveralls": { @@ -2473,6 +2479,7 @@ "version": "4.4.3", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, "license": "MIT", "dependencies": { "ms": "^2.1.3" @@ -2686,6 +2693,7 @@ "version": "10.6.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz", "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==", + "dev": true, "license": "MIT" }, "node_modules/enhanced-resolve": { @@ -3674,6 +3682,7 @@ "version": "1.4.0", "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.4.0.tgz", "integrity": "sha512-QZjmEOC+IT1uk6Rx0sX22V6uHWVwbdbxf1faPqJ1QhLdGgsRGCZoyaQBm/piRdJy/D2um6hM1UP7ZEeQ4EkP+Q==", + "dev": true, "license": "MIT", "engines": { "node": ">=18" @@ -4112,6 +4121,7 @@ "version": "7.0.2", "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", + "dev": true, "license": "MIT", "dependencies": { "agent-base": "^7.1.0", @@ -4141,6 +4151,7 @@ "version": "7.0.6", "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "dev": true, "license": "MIT", "dependencies": { "agent-base": "^7.1.2", @@ -4164,6 +4175,7 @@ "version": "3.0.6", "resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz", "integrity": "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==", + "dev": true, "license": "MIT" }, "node_modules/import-fresh": { @@ -4219,6 +4231,7 @@ "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true, "license": "ISC" }, "node_modules/ini": { @@ -4504,6 +4517,7 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/is-interactive/-/is-interactive-2.0.0.tgz", "integrity": "sha512-qP1vozQRI+BMOPcjFzrjXuQvdak2pHNUMZoeG2eRbiSqyvbEf/wQtEOTOX1guk6E3t36RkaqiSt8A/6YElNxLQ==", + "dev": true, "license": "MIT", "engines": { "node": ">=12" @@ -4767,6 +4781,7 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", + "dev": true, "license": "MIT" }, "node_modules/isexe": { @@ -5087,6 +5102,7 @@ "version": "3.10.1", "resolved": "https://registry.npmjs.org/jszip/-/jszip-3.10.1.tgz", "integrity": "sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g==", + "dev": true, "license": "(MIT OR GPL-3.0-or-later)", "dependencies": { "lie": "~3.3.0", @@ -5153,6 +5169,7 @@ "version": "3.3.0", "resolved": "https://registry.npmjs.org/lie/-/lie-3.3.0.tgz", "integrity": "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==", + "dev": true, "license": "MIT", "dependencies": { "immediate": "~3.0.5" @@ -5401,6 +5418,7 @@ "version": "5.0.1", "resolved": "https://registry.npmjs.org/mimic-function/-/mimic-function-5.0.1.tgz", "integrity": "sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA==", + "dev": true, "license": "MIT", "engines": { "node": ">=18" @@ -5658,6 +5676,7 @@ "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, "license": "MIT" }, "node_modules/napi-postinstall": { @@ -6201,6 +6220,7 @@ "version": "7.0.0", "resolved": "https://registry.npmjs.org/onetime/-/onetime-7.0.0.tgz", "integrity": "sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ==", + "dev": true, "license": "MIT", "dependencies": { "mimic-function": "^5.0.0" @@ -6234,6 +6254,7 @@ "version": "8.2.0", "resolved": "https://registry.npmjs.org/ora/-/ora-8.2.0.tgz", "integrity": "sha512-weP+BZ8MVNnlCm8c0Qdc1WSWq4Qn7I+9CJGm7Qali6g44e/PUzbjNqJX5NJ9ljlNMosfJvg1fKEGILklK9cwnw==", + "dev": true, "license": "MIT", "dependencies": { "chalk": "^5.3.0", @@ -6257,6 +6278,7 @@ "version": "6.2.2", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", + "dev": true, "license": "MIT", "engines": { "node": ">=12" @@ -6269,6 +6291,7 @@ "version": "5.6.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", + "dev": true, "license": "MIT", "engines": { "node": "^12.17.0 || ^14.13 || >=16.0.0" @@ -6281,6 +6304,7 @@ "version": "2.1.0", "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-2.1.0.tgz", "integrity": "sha512-mE00Gnza5EEB3Ds0HfMyllZzbBrmLOX3vfWoj9A9PEnTfratQ/BcaJOuMhnkhjXvb2+FkY3VuHqtAGpTPmglFQ==", + "dev": true, "license": "MIT", "engines": { "node": ">=18" @@ -6293,6 +6317,7 @@ "version": "6.0.0", "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-6.0.0.tgz", "integrity": "sha512-i24m8rpwhmPIS4zscNzK6MSEhk0DUWa/8iYQWxhffV8jkI4Phvs3F+quL5xvS0gdQR0FyTCMMH33Y78dDTzzIw==", + "dev": true, "license": "MIT", "dependencies": { "chalk": "^5.3.0", @@ -6309,6 +6334,7 @@ "version": "1.3.0", "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-1.3.0.tgz", "integrity": "sha512-43r2mRvz+8JRIKnWJ+3j8JtjRKZ6GmjzfaE/qiBJnikNnYv/6bagRJ1kUhNk8R5EX/GkobD+r+sfxCPJsiKBLQ==", + "dev": true, "license": "MIT", "engines": { "node": ">=12" @@ -6321,6 +6347,7 @@ "version": "7.1.2", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.2.tgz", "integrity": "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==", + "dev": true, "license": "MIT", "dependencies": { "ansi-regex": "^6.0.1" @@ -6432,6 +6459,7 @@ "version": "1.0.11", "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz", "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==", + "dev": true, "license": "(MIT AND Zlib)" }, "node_modules/parent-module": { @@ -6639,6 +6667,7 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", + "dev": true, "license": "MIT" }, "node_modules/process-on-spawn": { @@ -6756,6 +6785,7 @@ "version": "2.3.8", "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "dev": true, "license": "MIT", "dependencies": { "core-util-is": "~1.0.0", @@ -6977,6 +7007,7 @@ "version": "5.1.0", "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-5.1.0.tgz", "integrity": "sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA==", + "dev": true, "license": "MIT", "dependencies": { "onetime": "^7.0.0", @@ -7118,6 +7149,7 @@ "version": "5.1.2", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "dev": true, "license": "MIT" }, "node_modules/safe-push-apply": { @@ -7183,6 +7215,7 @@ "version": "7.7.4", "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", + "dev": true, "license": "ISC", "bin": { "semver": "bin/semver.js" @@ -7261,6 +7294,7 @@ "version": "1.0.5", "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz", "integrity": "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==", + "dev": true, "license": "MIT" }, "node_modules/shebang-command": { @@ -7366,6 +7400,7 @@ "version": "4.1.0", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "dev": true, "license": "ISC", "engines": { "node": ">=14" @@ -7593,6 +7628,7 @@ "version": "0.2.2", "resolved": "https://registry.npmjs.org/stdin-discarder/-/stdin-discarder-0.2.2.tgz", "integrity": "sha512-UhDfHmA92YAlNnCfhmq0VeNL5bDbiZGg7sZ2IvPsXubGkiNa9EC+tUTsjBRsYUAz87btI6/1wf4XoVvQ3uRnmQ==", + "dev": true, "license": "MIT", "engines": { "node": ">=18" @@ -7631,6 +7667,7 @@ "version": "1.1.1", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dev": true, "license": "MIT", "dependencies": { "safe-buffer": "~5.1.0" @@ -7640,6 +7677,7 @@ "version": "7.2.0", "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "dev": true, "license": "MIT", "dependencies": { "emoji-regex": "^10.3.0", @@ -7657,6 +7695,7 @@ "version": "6.2.2", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", + "dev": true, "license": "MIT", "engines": { "node": ">=12" @@ -7669,6 +7708,7 @@ "version": "7.1.2", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.2.tgz", "integrity": "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==", + "dev": true, "license": "MIT", "dependencies": { "ansi-regex": "^6.0.1" @@ -8463,6 +8503,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "dev": true, "license": "MIT" }, "node_modules/v8-compile-cache-lib": { diff --git a/package.json b/package.json index 420990d..6c1f6f7 100644 --- a/package.json +++ b/package.json @@ -281,11 +281,13 @@ "watch": "tsc -watch -p ./" }, "devDependencies": { + "@types/js-yaml": "^4.0.6", "@types/mocha": "^10.0.4", "@types/node": "^22.13.10", "@types/sinon": "^17.0.3", "@typescript-eslint/eslint-plugin": "^7.2.0", "@typescript-eslint/parser": "^7.2.0", + "@vscode/test-electron": "^2.1.5", "coveralls": "3.1.1", "dependency-cruiser": "^17.0.1", "eslint": "^8.57.0", @@ -301,9 +303,7 @@ "typescript-require": "0.3.0" }, "dependencies": { - "@types/js-yaml": "^4.0.6", "@types/vscode": "^1.98.0", - "@vscode/test-electron": "^2.1.5", "cloudformation-js-yaml-schema": "^0.4.2", "glob": "^14.0.3", "homeassistant-js-yaml-schema": "^1.1.0", diff --git a/src/adapter/js-yaml-adapter.ts b/src/adapter/js-yaml-adapter.ts index a238c46..25be6f0 100644 --- a/src/adapter/js-yaml-adapter.ts +++ b/src/adapter/js-yaml-adapter.ts @@ -2,7 +2,7 @@ import { dump, load } from "js-yaml" import { Settings } from "../settings" import { SortUtil } from "../util/sort-util" -import { removeTrailingCharacters, splitYaml } from "../util/yaml-util" +import { removeTrailingCharacters, splitYaml } from "../util/yaml-text" export class JsYamlAdapter { settings: Settings @@ -32,19 +32,30 @@ export class JsYamlAdapter { } /** - * Dumps a yaml with the user specific settings. - * @param {object} text Loaded yaml document which should be dumped. - * @param {boolean} sortKeys If set to true, the function will sort the keys in the document. Defaults to true. - * @returns {string} Clean yaml document. + * Dumps a whole yaml document with the user specific settings. + * An empty document (no content or only comments) is dumped as an empty string. + * @param text Loaded yaml document which should be dumped. + * @param sortKeys If set to true, the function will sort the keys in the document. + * @param custom 0 for the default sort, 1 to 3 for the custom sort keywords. + * @returns Clean yaml document. */ - dumpYaml(text: object, sortKeys: boolean, custom: number): string { - if (Object.keys(text).length === 0) { + dumpYaml(text: unknown, sortKeys: boolean, custom: number): string { + // js-yaml loads an empty document or one with only comments as null or undefined + if (text === undefined || text === null || isEmptyMapping(text)) { return "" } + return this.dumpValue(text, sortKeys, custom) + } - const sort = new SortUtil(this.settings, custom) - - let yaml = dump(text, { + /** + * Dumps any yaml value, including scalars, `null` and empty collections, with the user specific settings. + * @param value Value which should be dumped. + * @param sortKeys If set to true, the function will sort the keys of mappings. + * @param custom 0 for the default sort, 1 to 3 for the custom sort keywords. + * @returns The dumped value without trailing line break. + */ + dumpValue(value: unknown, sortKeys: boolean, custom: number): string { + let yaml = dump(value, { indent: this.settings.indent, forceQuotes: this.settings.forceQuotes, lineWidth: this.settings.lineWidth, @@ -53,9 +64,7 @@ export class JsYamlAdapter { quotingType: this.settings.getQuotingType(), schema: this.settings.getSchema(), styles: { "!!null": this.settings.getNullStyle() }, - sortKeys: (!(custom > 0 && this.settings.useCustomSortRecursively) ? sortKeys : (a: string, b: string) => { - return sort.customSort(a, b) - }) + sortKeys: this.getKeyComparator(sortKeys, custom) }) // this is neccesary to avoid linebreaks in a selection sort @@ -63,4 +72,28 @@ export class JsYamlAdapter { return yaml } + /** + * @param sortKeys If set to false, keys keep their order. + * @param custom 0 for the default sort, 1 to 3 for the custom sort keywords. + * @returns The value for js-yaml's `sortKeys` option. + */ + getKeyComparator(sortKeys: boolean, custom: number): boolean | ((a: string, b: string) => number) { + if (custom > 0 && this.settings.useCustomSortRecursively) { + const sort = new SortUtil(this.settings, custom) + return (a: string, b: string) => sort.customSort(a, b) + } + if (sortKeys && this.settings.sortOrderReverse) { + // mirror js-yaml's default order, which compares by code point + return (a: string, b: string) => SortUtil.compare(b, a) + } + return sortKeys + } + } + +/** + * @param value Any loaded yaml value. + * @returns True for a mapping without keys, e.g. an empty document. + */ +const isEmptyMapping = (value: unknown): boolean => + typeof value === "object" && value !== null && !Array.isArray(value) && Object.keys(value).length === 0 diff --git a/src/controller/document-transformer.ts b/src/controller/document-transformer.ts index 04e7a52..6d344a5 100644 --- a/src/controller/document-transformer.ts +++ b/src/controller/document-transformer.ts @@ -1,6 +1,7 @@ import { JsYamlAdapter } from "../adapter/js-yaml-adapter" -import { prependWhitespacesOnEachLine, removeLeadingLineBreakOfFirstElement } from "../lib" -import { YamlUtil, splitYaml, validateTextRange } from "../util/yaml-util" +import { prependWhitespacesOnEachLine, removeLeadingLineBreakOfFirstElement, removeLeadingSpacesOnEachLine } from "../lib" +import { splitYaml, validateTextRange } from "../util/yaml-text" +import { YamlUtil } from "../util/yaml-util" /** * The parts of YamlUtil a transformation depends on. Kept narrow so tests can pass a stub. @@ -54,17 +55,14 @@ export const sortDocuments = (text: string, options: SortOptions, yaml: YamlOper const prepared = removeDirectives(text, yaml.getDelimiters(text, !options.isSelection)) let newText = "" for (const unsortedYaml of splitYaml(prepared.text)) { - let sortedYaml = yaml.sortYaml(unsortedYaml, options.customSort) + // an indented selection is sorted like a top-level document and indented again afterwards (see #53) + const indentation = options.isSelection ? YamlUtil.getNumberOfLeadingSpaces(unsortedYaml) : 0 + const sortedYaml = yaml.sortYaml(removeLeadingSpacesOnEachLine(unsortedYaml, indentation), options.customSort) if (!sortedYaml) { // never return a partial result: it would drop documents or empty the selection return null } - if (options.isSelection) { - // the leading whitespaces of the selection are used for indentation - const indentation = YamlUtil.getNumberOfLeadingSpaces(unsortedYaml) - sortedYaml = prependWhitespacesOnEachLine(sortedYaml, indentation) - } - newText += (prepared.delimiters.shift() ?? "") + sortedYaml + newText += (prepared.delimiters.shift() ?? "") + prependWhitespacesOnEachLine(sortedYaml, indentation) } return options.isSelection ? newText : yaml.setLeadingDashes(newText) } diff --git a/src/lib.ts b/src/lib.ts index 7bd5a1e..fc86265 100644 --- a/src/lib.ts +++ b/src/lib.ts @@ -28,3 +28,17 @@ export function removeLeadingLineBreakOfFirstElement(delimiters: RegExpMatchArra return delimiters } + +/** + * Removes up to a given count of leading spaces from every single line in a text. + * The counterpart of prependWhitespacesOnEachLine(). + * @param text Text whose lines should lose their leading spaces. + * @param count The maximum number of spaces to remove from each line. + * @returns Input text without the leading spaces. + */ +export const removeLeadingSpacesOnEachLine = (text: string, count: number): string => { + if (count <= 0) { + return text + } + return text.replace(new RegExp(`^ {1,${count}}`, "gm"), "") +} diff --git a/src/test/suite/controller/document-transformer.test.ts b/src/test/suite/controller/document-transformer.test.ts index 26eb126..a28c3c9 100644 --- a/src/test/suite/controller/document-transformer.test.ts +++ b/src/test/suite/controller/document-transformer.test.ts @@ -46,6 +46,33 @@ suite("Test DocumentTransformer - sortDocuments() when a document cannot be sort }) }) +suite("Test DocumentTransformer - sortDocuments() with an indented selection (#53)", () => { + test("should sort an indented selection and keep its indentation", () => { + equal(sortDocuments(" b: 1\n a: 2", { customSort: 0, isSelection: true }), " a: 2\n b: 1") + }) + + test("should sort an indented selection with nested keys", () => { + const text = " b:\n y: 1\n x: 2\n a: 3" + + equal(sortDocuments(text, { customSort: 0, isSelection: true }), " a: 3\n b:\n x: 2\n 'y': 1") + }) + + test("should sort the keys of indented list items", () => { + const text = " - type: angular\n style: powerline\n - type: aws\n background: orange" + + equal( + sortDocuments(text, { customSort: 0, isSelection: true }), + " - style: powerline\n type: angular\n - background: orange\n type: aws" + ) + }) + + test("should keep a comment of an indented selection above its key", () => { + const text = " b: 1\n # about a\n a: 2" + + equal(sortDocuments(text, { customSort: 0, isSelection: true }), " # about a\n a: 2\n b: 1") + }) +}) + suite("Test DocumentTransformer - formatDocuments()", () => { test("should format every document and keep the delimiters", () => { equal(formatDocuments("---\nkey1: value\n---\nkey2: value"), "---\nkey1: value\n---\nkey2: value") diff --git a/src/test/suite/extension.test.ts b/src/test/suite/extension.test.ts index 3654112..3ce18d8 100644 --- a/src/test/suite/extension.test.ts +++ b/src/test/suite/extension.test.ts @@ -5,7 +5,7 @@ import { Position, Range, Selection, Uri, commands, window, workspace } from "vs import { Controller } from "../../controller/controller" import { Settings } from "../../settings" -import { splitYaml } from "../../util/yaml-util" +import { splitYaml } from "../../util/yaml-text" suite("Test getCustomSortKeywords", () => { test("should return values of `vscode-yaml-sort.customSortKeywords_1`", () => { diff --git a/src/test/suite/lib.test.ts b/src/test/suite/lib.test.ts index 77966e0..6d7e3d3 100644 --- a/src/test/suite/lib.test.ts +++ b/src/test/suite/lib.test.ts @@ -1,9 +1,10 @@ import { equal, throws} from "assert" import { - prependWhitespacesOnEachLine + prependWhitespacesOnEachLine, + removeLeadingSpacesOnEachLine } from "../../lib" -import { removeTrailingCharacters } from "../../util/yaml-util" +import { removeTrailingCharacters } from "../../util/yaml-text" suite("Test removeTrailingCharacters", () => { const actual = "text" @@ -51,3 +52,16 @@ suite("Test prependWhitespacesOnEachLine", () => { }) }) +suite("Test removeLeadingSpacesOnEachLine", () => { + test("should remove the given count of spaces from every line", () => { + equal(removeLeadingSpacesOnEachLine(" a:\n b: 1\n c: 2", 2), "a:\n b: 1\nc: 2") + }) + + test("should not remove more spaces than a line has", () => { + equal(removeLeadingSpacesOnEachLine(" a: 1\nb: 2\n\n c: 3", 2), "a: 1\nb: 2\n\nc: 3") + }) + + test("should return the text unchanged for a count of 0", () => { + equal(removeLeadingSpacesOnEachLine(" a: 1", 0), " a: 1") + }) +}) diff --git a/src/test/suite/util/sort-util.test.ts b/src/test/suite/util/sort-util.test.ts index 35181cc..bc36801 100644 --- a/src/test/suite/util/sort-util.test.ts +++ b/src/test/suite/util/sort-util.test.ts @@ -1,7 +1,7 @@ -import { equal } from "assert" +import { deepEqual, equal } from "assert" import { Settings } from "../../../settings" -import { SortUtil } from "../../../util/sort-util" +import { SortUtil, sortArraysRecursively } from "../../../util/sort-util" suite("Test Sort - localeSort()", () => { test("when `locale` is `sv` and a is `รค` and b is `z` should return 1", () => { @@ -53,4 +53,29 @@ suite("Test Sort - customSort()", () => { sort.custom = 1 sort.settings.sortOrderReverse = false -}) \ No newline at end of file +}) +suite("Test sortArraysRecursively()", () => { + test("should sort numbers numerically, then booleans, then strings", () => { + const value = ["c", 10, true, "b", 2, false] + + sortArraysRecursively(value) + + deepEqual(value, [2, 10, false, true, "b", "c"]) + }) + + test("should keep mappings and nested lists after the scalars in their original order", () => { + const value = [{ name: "b" }, "z", { name: "a" }, ["y", "x"]] + + sortArraysRecursively(value) + + deepEqual(value, ["z", { name: "b" }, { name: "a" }, ["x", "y"]]) + }) + + test("should sort arrays nested in mappings", () => { + const value = { a: { b: [3, 1, 2] }, c: null } + + sortArraysRecursively(value) + + deepEqual(value, { a: { b: [1, 2, 3] }, c: null }) + }) +}) diff --git a/src/test/suite/util/yaml-util.test.ts b/src/test/suite/util/yaml-util.test.ts index abb6656..8836606 100644 --- a/src/test/suite/util/yaml-util.test.ts +++ b/src/test/suite/util/yaml-util.test.ts @@ -592,3 +592,43 @@ suite("Test YamlUtil - sortYaml() keeps substituted values intact", () => { equal(yamlutil.sortYaml(text), text) }) }) + +suite("Test YamlUtil - sortYaml() with custom sort and scalar values", () => { + const yamlutil = new YamlUtil() + + test("should keep number and boolean values of custom sort keywords", () => { + equal(yamlutil.sortYaml("spec: x\nkind: true\napiVersion: 3", 1), "apiVersion: 3\nkind: true\nspec: x\n") + }) + + test("should keep an empty mapping as value of a custom sort keyword", () => { + equal(yamlutil.sortYaml("spec: x\nmetadata: {}", 1), "metadata: {}\nspec: x\n") + }) + + test("should order custom sort keywords even if their values are falsy", () => { + const text = "spec: x\nmetadata: null\nkind: false\napiVersion: 0" + + equal(yamlutil.sortYaml(text, 1), "apiVersion: 0\nkind: false\nmetadata: null\nspec: x\n") + }) + + test("should not add a value to a document containing only a comment", () => { + equal(yamlutil.sortYaml("# only a comment"), "\n# only a comment") + }) + + test("should keep a document containing only a scalar", () => { + equal(yamlutil.sortYaml("42"), "42") + }) +}) + +suite("Test YamlUtil - sortYaml() with sortOrderReverse", () => { + const settings = new Settings() + settings.sortOrderReverse = true + const yamlutil = new YamlUtil(settings) + + test("should sort keys in reverse order on every level", () => { + equal(yamlutil.sortYaml("a: 1\nc:\n x: 1\n z: 2\nb: 2"), "c:\n z: 2\n x: 1\nb: 2\na: 1") + }) + + test("should sort the remaining keys of a custom sort in reverse order", () => { + equal(yamlutil.sortYaml("a: 1\nkind: x\nb: 2", 1), "kind: x\nb: 2\na: 1") + }) +}) diff --git a/src/util/sort-util.ts b/src/util/sort-util.ts index fd5d19a..a061447 100644 --- a/src/util/sort-util.ts +++ b/src/util/sort-util.ts @@ -30,7 +30,7 @@ export class SortUtil { return this.localeSort(a, b) } - static compare(a: number, b: number) { + static compare(a: T, b: T): number { if (a > b) { return 1 } @@ -46,3 +46,49 @@ export class SortUtil { return a.localeCompare(b, this.settings.locale) } } + +/** + * Rank of a yaml value inside a sorted array: numbers, booleans and strings are sorted, + * everything else (mappings, nested lists, null) keeps its relative order at the end. + */ +const rankOf = (value: unknown): number => { + switch (typeof value) { + case "number": + return 0 + case "boolean": + return 1 + case "string": + return 2 + default: + return 3 + } +} + +/** + * Consistent comparison for array items of mixed types, see rankOf(). + */ +const compareArrayItems = (a: unknown, b: unknown): number => { + const rankDifference = rankOf(a) - rankOf(b) + if (rankDifference !== 0) { + return rankDifference + } + if (rankOf(a) === 3) { + // Array.prototype.sort is stable, so these items keep their order + return 0 + } + return SortUtil.compare(a as number | string, b as number | string) +} + +/** + * Sorts every array inside a loaded yaml value in place, including nested ones. + * @param value Loaded yaml value. + */ +export const sortArraysRecursively = (value: unknown): void => { + if (value === null || typeof value !== "object") { + return + } + if (Array.isArray(value)) { + value.sort(compareArrayItems) + } + Object.values(value).forEach(sortArraysRecursively) +} diff --git a/src/util/yaml-text.ts b/src/util/yaml-text.ts new file mode 100644 index 0000000..13ee034 --- /dev/null +++ b/src/util/yaml-text.ts @@ -0,0 +1,36 @@ +/* + * Text level operations on yaml documents. They work on plain strings and + * do not depend on js-yaml, VS Code or the user settings. + */ + +/** + * Removes a given count of characters from a string. + * @param {string} text String for processing. + * @param {number} count The number of characters to remove from the end of the returned string. + * @returns {string} Input text with removed trailing characters. + */ +export function removeTrailingCharacters(text: string, count = 1): string { + if (count >= 0 && count <= text.length) { + return text.substring(0, text.length - count) + } else { + throw new Error("The count parameter is not in a valid range") + } +} + +export function validateTextRange(textRange: string) { + // remove trailing whitespaces, to check for things like 'text: ' + const text = textRange.trim() + const notValidEndingCharacters = [":", "|", ">"] + if (notValidEndingCharacters.includes(text.charAt(text.length - 1))) { + throw new Error("YAML selection is invalid. Check the ending of your selection.") + } +} + +/** + * Splits a string, which contains multiple yaml documents. + * @param {string} multipleYamls String which contains multiple yaml documents. + * @returns {[string]} Array of yaml documents. + */ +export function splitYaml(multipleYamls: string): [string] { + return multipleYamls.split(/^---.*/m).filter((obj) => obj) as [string] +} diff --git a/src/util/yaml-util.ts b/src/util/yaml-util.ts index db7a03a..54c33ba 100644 --- a/src/util/yaml-util.ts +++ b/src/util/yaml-util.ts @@ -4,33 +4,8 @@ import { Severity, VsCodeAdapter } from "../adapter/vs-code-adapter" import { ProcessorController } from "../controller/processor-controller" import { prependWhitespacesOnEachLine } from "../lib" import { Settings } from "../settings" - -const sortArrays = (obj: unknown) => { - if (!obj || typeof obj !== "object") { - return - } else if (Array.isArray(obj)) { - obj.sort((a, b) => compareObjects(a, b)) - } - Object.keys(obj).forEach(key => { - const object = obj[key as keyof unknown] - if (typeof object === "object") { - if (Array.isArray(object)) { - Object.entries(object).sort((a, b) => compareObjects(a, b)) - } - sortArrays(object) - } - }) -} - -export function compareObjects(a: object, b: object) { - if (a > b) { - return 1 - } - if (a < b) { - return -1 - } - return 0 -} +import { sortArraysRecursively } from "./sort-util" +import { removeTrailingCharacters } from "./yaml-text" export class YamlUtil { settings: Settings @@ -79,7 +54,7 @@ export class YamlUtil { const doc = this.jsyamladapter.load(unsortedYamlWithoutTabs) as any if (this.settings.sortArrays) { - sortArrays(doc) + sortArraysRecursively(doc) } let sortedYaml = "" @@ -87,8 +62,9 @@ export class YamlUtil { const keywords = this.settings.getCustomSortKeywords(customSort) keywords.forEach(key => { - if (doc[key]) { - let sortedSubYaml = this.jsyamladapter.dumpYaml(doc[key], true, customSort) + // check for the key itself, values like 0, false or null must be ordered too + if (Object.prototype.hasOwnProperty.call(doc, key)) { + let sortedSubYaml = this.jsyamladapter.dumpValue(doc[key], true, customSort) if (YamlUtil.isValueMultiline(sortedSubYaml)) { sortedSubYaml = this.transformMultilineValue(sortedSubYaml) sortedYaml += `${key}:\n${sortedSubYaml}\n` @@ -123,7 +99,7 @@ export class YamlUtil { try { const processor = new ProcessorController(yaml) processor.preprocess() - let doc = new JsYamlAdapter().dumpYaml(this.jsyamladapter.load(processor.text) as object, false, 0) + let doc = new JsYamlAdapter().dumpYaml(this.jsyamladapter.load(processor.text), false, 0) processor.text = doc processor.postprocess() doc = processor.text @@ -183,35 +159,3 @@ export class YamlUtil { return delimiters } } - -/** - * Removes a given count of characters from a string. - * @param {string} text String for processing. - * @param {number} count The number of characters to remove from the end of the returned string. - * @returns {string} Input text with removed trailing characters. - */ -export function removeTrailingCharacters(text: string, count = 1): string { - if (count >= 0 && count <= text.length) { - return text.substring(0, text.length - count) - } else { - throw new Error("The count parameter is not in a valid range") - } -} - -export function validateTextRange(textRange: string) { - // remove trailing whitespaces, to check for things like 'text: ' - const text = textRange.trim() - const notValidEndingCharacters = [":", "|", ">"] - if (notValidEndingCharacters.includes(text.charAt(text.length - 1))) { - throw new Error("YAML selection is invalid. Check the ending of your selection.") - } -} - -/** - * Splits a string, which contains multiple yaml documents. - * @param {string} multipleYamls String which contains multiple yaml documents. - * @returns {[string]} Array of yaml documents. - */ -export function splitYaml(multipleYamls: string): [string] { - return multipleYamls.split(/^---.*/m).filter((obj) => obj) as [string] -}