From 528ab7dcf1eabcbdf3f7b810f6eaa16238c333e2 Mon Sep 17 00:00:00 2001 From: Pascal Reitermann Date: Fri, 20 Nov 2026 07:10:12 +0000 Subject: [PATCH 1/6] ci(coverage): measure only the extension's own code Coverage dropped from 92.4% to 15.8% on 2026-11-05 on two unrelated branches at once (7f7cafa, 8f52445), so the cause was the CI environment, not a code change. nyc instruments every file below the project root that the wrapped processes load, and .vscode-test was not excluded. A newer VS Code version propagates nyc's require hook into its extension host, so the built-in VS Code extensions (e.g. TypeScriptTeam.jsts-chat-features) were counted as well and our code became a small part of the measured lines. Restrict nyc to the compiled extension and its sources. Both patterns are needed: nyc remaps out/*.js to src/*.ts via the source maps and applies include/exclude again afterwards. Tests are excluded. Replace the text-lcov reporter, which dumped the whole lcov file into the CI log, with the per-file text table. Verified locally with a simulated VS Code extension file loaded during the unit tests: 43% before (the foreign file counted), 91% after. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Jdb5is9YsMnteaxHryN26M --- .nycrc | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/.nycrc b/.nycrc index ea3f3db..480b98c 100644 --- a/.nycrc +++ b/.nycrc @@ -1,8 +1,16 @@ { - "reporter": [ - "html", - "text-lcov", - "text-summary", - "lcov" + "include": [ + "out/**/*.js", + "src/**/*.ts" + ], + "exclude": [ + "out/test/**", + "src/test/**" + ], + "reporter": [ + "html", + "text", + "text-summary", + "lcov" ] -} \ No newline at end of file +} From 91072bb9e4bc57a9cd017edea2051ccb4f63a5c9 Mon Sep 17 00:00:00 2001 From: Pascal Reitermann Date: Fri, 20 Nov 2026 07:11:48 +0000 Subject: [PATCH 2/6] refactor(settings): make Settings a snapshot of one configuration Settings mixed two models: most values were read once into fields, but getSchema(), getQuotingType(), getCustomSortKeywords() and getExtensions() read the workspace configuration again on every call. Setting `settings.schema` on an instance therefore had no effect, and the class could not be created for a specific configuration. Read every value once from a configuration passed to the constructor (default: the global and workspace settings) and let the getters return the fields. Remove VsCodeAdapter.getProperty(), a second way into the configuration that only its test used. No behavior change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Jdb5is9YsMnteaxHryN26M --- src/adapter/vs-code-adapter.ts | 5 - src/settings.ts | 188 +++++++++++------- .../suite/adapter/vs-code-adapter.test.ts | 22 -- 3 files changed, 115 insertions(+), 100 deletions(-) diff --git a/src/adapter/vs-code-adapter.ts b/src/adapter/vs-code-adapter.ts index f45d02c..d3fea80 100644 --- a/src/adapter/vs-code-adapter.ts +++ b/src/adapter/vs-code-adapter.ts @@ -7,17 +7,12 @@ export enum Severity { } export class VsCodeAdapter { - section = "vscode-yaml-sort" settings: Settings constructor(settings = new Settings()) { this.settings = settings } - getProperty(property: string) { - return workspace.getConfiguration().get(`${this.section}.${property}`) - } - showMessage(severity: Severity, message: string) { if (severity === Severity.ERROR) { window.showErrorMessage(message) diff --git a/src/settings.ts b/src/settings.ts index 4ffe044..3e5e083 100644 --- a/src/settings.ts +++ b/src/settings.ts @@ -1,89 +1,131 @@ import { CLOUDFORMATION_SCHEMA } from "cloudformation-js-yaml-schema" import { HOMEASSISTANT_SCHEMA } from "homeassistant-js-yaml-schema" import { CORE_SCHEMA, DEFAULT_SCHEMA, FAILSAFE_SCHEMA, JSON_SCHEMA, Schema } from "js-yaml" -import { workspace } from "vscode" +import { WorkspaceConfiguration, workspace } from "vscode" -export class Settings { - filter = "vscode-yaml-sort" - workspace = workspace +type QuotingType = "'" | "\"" - getBoolean(name: string) { - return this.workspace.getConfiguration().get(`${this.filter}.${name}`) as boolean - } +// js-yaml only supports these styles for the !!null tag +const NULL_STYLES = ["lowercase", "uppercase", "camelcase", "canonical", "empty"] - getNumber(name: string) { - return this.workspace.getConfiguration().get(`${this.filter}.${name}`) as number - } +/** + * A snapshot of the extension's settings. + * + * All values are read once, when the snapshot is created. Afterwards they can be changed on the + * instance, e.g. in tests, and every getter reflects the change. + */ +export class Settings { + static readonly SECTION = "vscode-yaml-sort" - getString(name: string) { - return this.workspace.getConfiguration().get(`${this.filter}.${name}`) as string - } + customSortKeywords1: string[] + customSortKeywords2: string[] + customSortKeywords3: string[] + emptyLinesUntilLevel: number + extensions: string[] + forceQuotes: boolean + indent: number + lineWidth: number + locale: string + nullStyle: string + noArrayIndent: boolean + noCompatMode: boolean + notifySuccess: boolean + quotingType: QuotingType + schema: Schema + sortArrays: boolean + sortOnSave: number + sortOrderReverse: boolean + useCustomSortRecursively: boolean + useLeadingDashes: boolean + useArrayProcessor: boolean + useBlockProcessor: boolean + useCommentProcessor: boolean + useHelmProcessor: boolean + useOctalProcessor: boolean + + /** + * @param configuration The extension's configuration section. Defaults to the global and workspace settings. + */ + constructor(configuration: WorkspaceConfiguration = workspace.getConfiguration(Settings.SECTION)) { + const read = (name: string) => configuration.get(name) as T + this.customSortKeywords1 = read("customSortKeywords_1") + this.customSortKeywords2 = read("customSortKeywords_2") + this.customSortKeywords3 = read("customSortKeywords_3") + this.emptyLinesUntilLevel = read("emptyLinesUntilLevel") + this.extensions = read("extensions") + this.forceQuotes = read("forceQuotes") + this.indent = read("indent") + this.lineWidth = read("lineWidth") + this.locale = read("locale") + this.nullStyle = read("nullStyle") + this.noArrayIndent = read("noArrayIndent") + this.noCompatMode = read("noCompatMode") + this.notifySuccess = read("notifySuccess") + this.quotingType = read("quotingType") + this.schema = Settings.getJsYamlSchemaFromString(read("schema")) + this.sortArrays = read("sortArrays") + this.sortOnSave = read("sortOnSave") + this.sortOrderReverse = read("sortOrderReverse") + this.useCustomSortRecursively = read("useCustomSortRecursively") + this.useLeadingDashes = read("useLeadingDashes") + this.useArrayProcessor = read("useArrayProcessor") + this.useBlockProcessor = read("useBlockProcessor") + this.useCommentProcessor = read("useCommentProcessor") + this.useHelmProcessor = read("useHelmProcessor") + this.useOctalProcessor = read("useOctalProcessor") + } - getCustomSortKeywords(index: number): string[] { - if ([1, 2, 3].includes(index)) - return this.workspace.getConfiguration().get(`${this.filter}.customSortKeywords_${index}`) as string[] + /** + * @param index 1, 2 or 3. + * @returns The keywords of the custom sort, or an empty list for any other index. + */ + getCustomSortKeywords(index: number): string[] { + switch (index) { + case 1: + return this.customSortKeywords1 + case 2: + return this.customSortKeywords2 + case 3: + return this.customSortKeywords3 + default: return [] } - getExtensions(): string[] { - return this.workspace.getConfiguration().get(`${this.filter}.extensions`) as string[] - } - getQuotingType(): "'" | "\"" { - return this.workspace.getConfiguration().get(`${this.filter}.quotingType`) as "'" | "\"" - } - getSchema(): Schema { - const schema = this.workspace.getConfiguration().get(`${this.filter}.schema`) as string - return Settings.getJsYamlSchemaFromString(schema) - } + } - getNullStyle(): string { - // js-yaml only supports these styles for the !!null tag - const validStyles = ["lowercase", "uppercase", "camelcase", "canonical", "empty"] - return validStyles.includes(this.nullStyle) ? this.nullStyle : "lowercase" - } + getExtensions(): string[] { + return this.extensions + } - customSortKeywords1 = this.getCustomSortKeywords(1) - customSortKeywords2 = this.getCustomSortKeywords(2) - customSortKeywords3 = this.getCustomSortKeywords(3) - emptyLinesUntilLevel = this.getNumber("emptyLinesUntilLevel") - forceQuotes = this.getBoolean("forceQuotes") - indent = this.getNumber("indent") - lineWidth = this.getNumber("lineWidth") - locale = this.getString("locale") - nullStyle = this.getString("nullStyle") - noArrayIndent = this.getBoolean("noArrayIndent") - noCompatMode = this.getBoolean("noCompatMode") - notifySuccess = this.getBoolean("notifySuccess") - quotingType = this.getQuotingType() - schema = this.getSchema() - sortArrays = this.getBoolean("sortArrays") - sortOnSave = this.getNumber("sortOnSave") - sortOrderReverse = this.getBoolean("sortOrderReverse") - useCustomSortRecursively = this.getBoolean("useCustomSortRecursively") - useLeadingDashes = this.getBoolean("useLeadingDashes") - useArrayProcessor = this.getBoolean("useArrayProcessor") - useBlockProcessor = this.getBoolean("useBlockProcessor") - useCommentProcessor = this.getBoolean("useCommentProcessor") - useHelmProcessor = this.getBoolean("useHelmProcessor") - useOctalProcessor = this.getBoolean("useOctalProcessor") + getQuotingType(): QuotingType { + return this.quotingType + } - static getJsYamlSchemaFromString(schema: string): Schema { - switch (schema) { - case "HOMEASSISTANT_SCHEMA": - return HOMEASSISTANT_SCHEMA as Schema - case "CLOUDFORMATION_SCHEMA": - return CLOUDFORMATION_SCHEMA as Schema - case "CORE_SCHEMA": - return CORE_SCHEMA - case "FAILSAFE_SCHEMA": - return FAILSAFE_SCHEMA - case "JSON_SCHEMA": - return JSON_SCHEMA - default: - return DEFAULT_SCHEMA - } - } + getSchema(): Schema { + return this.schema + } + + getNullStyle(): string { + return NULL_STYLES.includes(this.nullStyle) ? this.nullStyle : "lowercase" + } - doSortOnSave(): boolean { - return (this.sortOnSave >= 0 && this.sortOnSave <= 3) + static getJsYamlSchemaFromString(schema: string): Schema { + switch (schema) { + case "HOMEASSISTANT_SCHEMA": + return HOMEASSISTANT_SCHEMA as Schema + case "CLOUDFORMATION_SCHEMA": + return CLOUDFORMATION_SCHEMA as Schema + case "CORE_SCHEMA": + return CORE_SCHEMA + case "FAILSAFE_SCHEMA": + return FAILSAFE_SCHEMA + case "JSON_SCHEMA": + return JSON_SCHEMA + default: + return DEFAULT_SCHEMA } + } + + doSortOnSave(): boolean { + return (this.sortOnSave >= 0 && this.sortOnSave <= 3) + } } diff --git a/src/test/suite/adapter/vs-code-adapter.test.ts b/src/test/suite/adapter/vs-code-adapter.test.ts index 870d872..264acbd 100644 --- a/src/test/suite/adapter/vs-code-adapter.test.ts +++ b/src/test/suite/adapter/vs-code-adapter.test.ts @@ -6,28 +6,6 @@ import { Uri, window, workspace } from "vscode" import { Severity, VsCodeAdapter } from "../../../adapter/vs-code-adapter" -suite("Test VsCodeAdapter - getProperty()", () => { - const vscodeadapter = new VsCodeAdapter() - - test("when property is locale should return en", () => { - equal(vscodeadapter.getProperty("locale"), "en") - }) -}) -/* -suite("Test VsCodeAdapter - applyEdits()", () => { - const vscodeadapter = new VsCodeAdapter() - const textEditor = window.activeTextEditor - if (textEditor) { - const edits = vscodeadapter.getEdits(textEditor, 'foobar') - window.activeTextEditor = undefined - throws(() => vscodeadapter.applyEdits([edits])) - - test("when property is locale should return en", () => { - strictEqual(vscodeadapter.getProperty("locale"), "en") - }) - } -})*/ - suite("Test VsCodeAdapter - getActiveDocument()", () => { test("when text editor is active should open document", async () => { const uri = Uri.parse(path.resolve("./src/test/files/testGetActiveDocument.yaml")) From 72d3e04561a831825c17440db08348342c971b66 Mon Sep 17 00:00:00 2001 From: Pascal Reitermann Date: Fri, 20 Nov 2026 07:12:33 +0000 Subject: [PATCH 3/6] fix(settings): pass injected settings to every processing step YamlUtil created its ProcessorController without settings, the spacing and tabs-to-spaces processors created their own, formatYaml() dumped with a new JsYamlAdapter and sortDocuments() validated with one. Each of them read the global settings instead of the ones YamlUtil was created with, so e.g. emptyLinesUntilLevel, the processor switches, indent or schema of injected settings were partly ignored. Pass the settings through instead. With the global settings, as used today, the result is the same; this is the precondition for reading the settings per document. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Jdb5is9YsMnteaxHryN26M --- src/controller/document-transformer.ts | 2 +- src/controller/processor-controller.ts | 4 ++-- src/processor/spacing-processor.ts | 5 ++-- src/processor/tabs-to-spaces-processor.ts | 5 ++-- .../controller/document-transformer.test.ts | 10 ++++++++ src/test/suite/util/yaml-util.test.ts | 24 +++++++++++++++++++ src/util/yaml-util.ts | 6 ++--- 7 files changed, 46 insertions(+), 10 deletions(-) diff --git a/src/controller/document-transformer.ts b/src/controller/document-transformer.ts index 8959d75..bf7e9d2 100644 --- a/src/controller/document-transformer.ts +++ b/src/controller/document-transformer.ts @@ -70,7 +70,7 @@ const transformDocuments = (stream: YamlStream, transform: ContentTransformation */ export const sortDocuments = (text: string, options: SortOptions, yaml: YamlOperations = new YamlUtil()): string | null => { validateTextRange(text) - new JsYamlAdapter().validateYaml(text) + new JsYamlAdapter(yaml.settings).validateYaml(text) const sorted = transformDocuments(splitDocuments(text), (content) => { // an indented selection is sorted like a top-level document and indented again afterwards (see #53) diff --git a/src/controller/processor-controller.ts b/src/controller/processor-controller.ts index ebf0f9b..b7fcf94 100644 --- a/src/controller/processor-controller.ts +++ b/src/controller/processor-controller.ts @@ -24,7 +24,7 @@ export class ProcessorController { } preprocess() { - this.tabstospacespreprocessor = new TabsToSpacesProcessor(this.text) + this.tabstospacespreprocessor = new TabsToSpacesProcessor(this.text, this.settings) this.tabstospacespreprocessor.preprocess() this.text = this.tabstospacespreprocessor.text @@ -90,7 +90,7 @@ export class ProcessorController { this.text = this.blockprocessor.text } - this.spacingprocessor = new SpacingProcessor(this.text) + this.spacingprocessor = new SpacingProcessor(this.text, this.settings) this.spacingprocessor.postprocess() this.text = this.spacingprocessor.text } diff --git a/src/processor/spacing-processor.ts b/src/processor/spacing-processor.ts index 0a9d9db..52ca597 100644 --- a/src/processor/spacing-processor.ts +++ b/src/processor/spacing-processor.ts @@ -2,10 +2,11 @@ import { Settings } from "../settings" export class SpacingProcessor { text: string - settings = new Settings() + settings: Settings - constructor(text: string) { + constructor(text: string, settings = new Settings()) { this.text = text + this.settings = settings } postprocess() { diff --git a/src/processor/tabs-to-spaces-processor.ts b/src/processor/tabs-to-spaces-processor.ts index 4bc2a55..4c78918 100644 --- a/src/processor/tabs-to-spaces-processor.ts +++ b/src/processor/tabs-to-spaces-processor.ts @@ -2,10 +2,11 @@ import { Settings } from "../settings" export class TabsToSpacesProcessor { text: string - settings = new Settings() + settings: Settings - constructor(text: string) { + constructor(text: string, settings = new Settings()) { this.text = text + this.settings = settings } preprocess() { diff --git a/src/test/suite/controller/document-transformer.test.ts b/src/test/suite/controller/document-transformer.test.ts index d565ebe..6e23184 100644 --- a/src/test/suite/controller/document-transformer.test.ts +++ b/src/test/suite/controller/document-transformer.test.ts @@ -4,6 +4,7 @@ import { spy } from "sinon" import { window } from "vscode" import { YamlOperations, formatDocuments, sortDocuments } from "../../../controller/document-transformer" +import { Settings } from "../../../settings" import { YamlUtil } from "../../../util/yaml-util" /** @@ -136,3 +137,12 @@ suite("Test DocumentTransformer - formatDocuments()", () => { } }) }) + +suite("Test DocumentTransformer - injected settings", () => { + test("should validate with the schema of the injected settings", () => { + const settings = new Settings() + settings.schema = Settings.getJsYamlSchemaFromString("CLOUDFORMATION_SCHEMA") + + equal(sortDocuments("b: !Ref x\na: 1", { customSort: 0, isSelection: false }, new YamlUtil(settings)), "---\na: 1\nb: !Ref x") + }) +}) diff --git a/src/test/suite/util/yaml-util.test.ts b/src/test/suite/util/yaml-util.test.ts index c799461..6401a85 100644 --- a/src/test/suite/util/yaml-util.test.ts +++ b/src/test/suite/util/yaml-util.test.ts @@ -559,3 +559,27 @@ suite("Test YamlUtil - sortYaml() with sortOrderReverse", () => { equal(yamlutil.sortYaml("a: 1\nkind: x\nb: 2", 1), "kind: x\nb: 2\na: 1") }) }) + +suite("Test YamlUtil - injected settings reach every processing step", () => { + test("should use emptyLinesUntilLevel of the injected settings", () => { + const settings = new Settings() + settings.emptyLinesUntilLevel = 1 + + equal(new YamlUtil(settings).sortYaml("b: 1\na: 2"), "a: 2\n\nb: 1") + }) + + test("should use the processor switches of the injected settings", () => { + const settings = new Settings() + settings.useCommentProcessor = false + + // without the comment processor js-yaml drops the comment + equal(new YamlUtil(settings).sortYaml("b: 1\n# comment\na: 2"), "a: 2\nb: 1") + }) + + test("should format with the indentation of the injected settings", () => { + const settings = new Settings() + settings.indent = 4 + + equal(new YamlUtil(settings).formatYaml("a:\n b: 1", false), "a:\n b: 1") + }) +}) diff --git a/src/util/yaml-util.ts b/src/util/yaml-util.ts index 9ad0ff1..5a155bc 100644 --- a/src/util/yaml-util.ts +++ b/src/util/yaml-util.ts @@ -45,7 +45,7 @@ export class YamlUtil { sortYaml(unsortedYaml: string, customSort = 0): string | null { try { - const processor = new ProcessorController(unsortedYaml) + const processor = new ProcessorController(unsortedYaml, this.settings) processor.preprocess() const unsortedYamlWithoutTabs = processor.text @@ -96,9 +96,9 @@ export class YamlUtil { */ formatYaml(yaml: string, useLeadingDashes: boolean): string | null { try { - const processor = new ProcessorController(yaml) + const processor = new ProcessorController(yaml, this.settings) processor.preprocess() - let doc = new JsYamlAdapter().dumpYaml(this.jsyamladapter.load(processor.text), false, 0) + let doc = this.jsyamladapter.dumpYaml(this.jsyamladapter.load(processor.text), false, 0) processor.text = doc processor.postprocess() doc = processor.text From d8f2593afd8b8368d910402db56e7c5470bf5a16 Mon Sep 17 00:00:00 2001 From: Pascal Reitermann Date: Fri, 20 Nov 2026 07:13:51 +0000 Subject: [PATCH 4/6] feat(settings): read the settings that apply to the processed document The settings were always read without a scope and declared without a `scope`, so VS Code ignored workspace folder settings in a multi-root workspace and language specific settings such as `"[yaml]": { "vscode-yaml-sort.indent": 4 }`. In addition, the controller created separate snapshots for each of its collaborators. Declare the settings as language-overridable (`extensions` as resource, `notifySuccess` stays global) and add Settings.forDocument(). The controller, the formatter and the recursive sort create one snapshot for the processed document, or for each file, and pass it on. With global settings only, nothing changes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Jdb5is9YsMnteaxHryN26M --- CHANGELOG.md | 1 + README.md | 11 +++++++++++ package.json | 24 ++++++++++++++++++++++++ src/controller/controller.ts | 18 +++++++++++------- src/controller/file-sorter.ts | 6 ++++-- src/controller/formatting-provider.ts | 8 +++++--- src/settings.ts | 16 +++++++++++++++- src/test/suite/settings.test.ts | 16 ++++++++++++++++ 8 files changed, 87 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ac18ac0..fd45274 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,7 @@ * (closes [#221](https://github.com/pascalre/vscode-yaml-sort/issues/221)) Keep comments above their anchor while sorting, even when a deeper indented line contains the anchor as a substring ✨ Feature +* Settings can now be set per workspace folder in a multi-root workspace and per language (e.g. `"[yaml]": { "vscode-yaml-sort.indent": 4 }`). Every command and the formatter read the settings that apply to the processed document * (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 diff --git a/README.md b/README.md index d2c8147..6f852f2 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,17 @@ This extension contributes the following settings: | `useHelmProcessor` | When `true`, will activate HelmProcessor. | `true` | | `useOctalProcessor` | When `true`, will activate OctalProcessor. | `true` | +All settings except `notifySuccess` can also be set per workspace folder in a multi-root workspace and, except `extensions`, per language: + +#### **`.vscode/settings.json`** +```json +{ + "[yaml]": { + "vscode-yaml-sort.indent": 4 + } +} +``` + # ❓ FAQ ## How to sort on save? Register this extension as VS Code formatter. Also configure VS Code to format files on save. Caution: This setting will apply for all files. Changes will require a restart of VS Code. If you wish to also sort (not only format) the file on saving, set `sortOnSave` to `0`. Use `1`, `2` or `3` for custom sort. diff --git a/package.json b/package.json index ff88c58..8f02f8e 100644 --- a/package.json +++ b/package.json @@ -51,11 +51,13 @@ "properties": { "vscode-yaml-sort.emptyLinesUntilLevel": { "type": "number", + "scope": "language-overridable", "default": 0, "description": "When bigger than 0, will add a new line before each keyword on level n." }, "vscode-yaml-sort.customSortKeywords_1": { "type": "array", + "scope": "language-overridable", "items": { "type": "string" }, @@ -70,6 +72,7 @@ }, "vscode-yaml-sort.customSortKeywords_2": { "type": "array", + "scope": "language-overridable", "items": { "type": "string" }, @@ -78,6 +81,7 @@ }, "vscode-yaml-sort.customSortKeywords_3": { "type": "array", + "scope": "language-overridable", "items": { "type": "string" }, @@ -86,6 +90,7 @@ }, "vscode-yaml-sort.extensions": { "type": "array", + "scope": "resource", "items": { "type": "string" }, @@ -97,26 +102,31 @@ }, "vscode-yaml-sort.forceQuotes": { "type": "boolean", + "scope": "language-overridable", "default": false, "description": "When true, all non-key strings will be quoted even if they normally don't need to." }, "vscode-yaml-sort.indent": { "type": "integer", + "scope": "language-overridable", "default": 2, "description": "Indentation width in spaces." }, "vscode-yaml-sort.lineWidth": { "type": "integer", + "scope": "language-overridable", "default": 500, "description": "Maximum line width for YAML files." }, "vscode-yaml-sort.locale": { "type": "string", + "scope": "language-overridable", "default": "en", "description": "Language whose sort order should be used." }, "vscode-yaml-sort.nullStyle": { "type": "string", + "scope": "language-overridable", "default": "lowercase", "enum": [ "lowercase", @@ -136,11 +146,13 @@ }, "vscode-yaml-sort.noArrayIndent": { "type": "boolean", + "scope": "language-overridable", "default": false, "description": "When true, will not add an indentation level to array elements." }, "vscode-yaml-sort.noCompatMode": { "type": "boolean", + "scope": "language-overridable", "default": false, "description": "When true, don't try to be compatible with older yaml versions. Currently: don't quote 'yes', 'no' and so on, as required for YAML 1.1" }, @@ -151,6 +163,7 @@ }, "vscode-yaml-sort.quotingType": { "type": "string", + "scope": "language-overridable", "default": "'", "enum": [ "'", @@ -160,6 +173,7 @@ }, "vscode-yaml-sort.schema": { "type": "string", + "scope": "language-overridable", "default": "DEFAULT_SCHEMA", "enum": [ "HOMEASSISTANT_SCHEMA", @@ -173,51 +187,61 @@ }, "vscode-yaml-sort.sortArrays": { "type": "boolean", + "scope": "language-overridable", "default": false, "description": "When `true`, will sort arrays" }, "vscode-yaml-sort.sortOrderReverse": { "type": "boolean", + "scope": "language-overridable", "default": false, "description": "When `true`, will sort in reverse order" }, "vscode-yaml-sort.sortOnSave": { "type": "number", + "scope": "language-overridable", "default": 0, "description": "When `0`, will sort files when saving. When `1`, `2` or `3`, will use customSortKeywords. Set to negative value to disable sortOnSave." }, "vscode-yaml-sort.useCustomSortRecursively": { "type": "boolean", + "scope": "language-overridable", "default": false, "description": "When true, will use the custom sort keywords recursively on a file, when using custom sort" }, "vscode-yaml-sort.useLeadingDashes": { "type": "boolean", + "scope": "language-overridable", "default": true, "description": "Define if sorted YAML files should begin with leading dashes." }, "vscode-yaml-sort.useArrayProcessor": { "type": "boolean", + "scope": "language-overridable", "default": true, "description": "When `true`, will activate ArrayProcessor" }, "vscode-yaml-sort.useBlockProcessor": { "type": "boolean", + "scope": "language-overridable", "default": true, "description": "When `true`, will activate BlockProcessor" }, "vscode-yaml-sort.useCommentProcessor": { "type": "boolean", + "scope": "language-overridable", "default": true, "description": "When `true`, will activate CommentProcessor" }, "vscode-yaml-sort.useHelmProcessor": { "type": "boolean", + "scope": "language-overridable", "default": true, "description": "When `true`, will activate HelmProcessor" }, "vscode-yaml-sort.useOctalProcessor": { "type": "boolean", + "scope": "language-overridable", "default": true, "description": "When `true`, will activate OctalProcessor" } diff --git a/src/controller/controller.ts b/src/controller/controller.ts index 2f82e18..bae3ba5 100644 --- a/src/controller/controller.ts +++ b/src/controller/controller.ts @@ -9,18 +9,22 @@ import { YamlUtil } from "../util/yaml-util" export class Controller { editor: TextEditor - yamlutil = new YamlUtil() - jsyamladapter = new JsYamlAdapter() - vscodeadapter = new VsCodeAdapter() + settings: Settings + yamlutil: YamlUtil + jsyamladapter: JsYamlAdapter + vscodeadapter: VsCodeAdapter errorutil = new ErrorUtil() - settings = new Settings() constructor() { - if (window.activeTextEditor) { - this.editor = window.activeTextEditor - } else { + if (!window.activeTextEditor) { throw new Error("No texteditor is active") } + this.editor = window.activeTextEditor + // one snapshot of the settings that apply to the edited document + this.settings = Settings.forDocument(this.editor.document) + this.yamlutil = new YamlUtil(this.settings) + this.jsyamladapter = new JsYamlAdapter(this.settings) + this.vscodeadapter = new VsCodeAdapter(this.settings) } validateYamlWrapper(): boolean { diff --git a/src/controller/file-sorter.ts b/src/controller/file-sorter.ts index ad72664..406a24b 100644 --- a/src/controller/file-sorter.ts +++ b/src/controller/file-sorter.ts @@ -4,6 +4,7 @@ import { Uri } from "vscode" import { YamlOperations, sortDocuments } from "./document-transformer" import { Severity, VsCodeAdapter } from "../adapter/vs-code-adapter" +import { Settings } from "../settings" import { ErrorUtil } from "../util/error-util" import { FileUtil } from "../util/file-util" import { YamlUtil } from "../util/yaml-util" @@ -38,9 +39,10 @@ export const sortYamlFilesInDirectory = (uri: Uri | undefined): void => { new VsCodeAdapter().showMessage(Severity.ERROR, "Please run this command from the context menu of a folder in the explorer.") return } - for (const file of new FileUtil().getFiles(uri.fsPath)) { + const settingsFor = (resource: Uri) => Settings.forDocument({ uri: resource, languageId: "yaml" }) + for (const file of new FileUtil(settingsFor(uri)).getFiles(uri.fsPath)) { try { - sortFile(file) + sortFile(file, new YamlUtil(settingsFor(Uri.file(file)))) } catch (error) { errorutil.handleError(error) } diff --git a/src/controller/formatting-provider.ts b/src/controller/formatting-provider.ts index e4c885a..757f470 100644 --- a/src/controller/formatting-provider.ts +++ b/src/controller/formatting-provider.ts @@ -3,6 +3,7 @@ import { DocumentFormattingEditProvider, Range, TextDocument, TextEdit } from "v import { formatDocuments, sortDocuments } from "./document-transformer" import { Settings } from "../settings" import { ErrorUtil } from "../util/error-util" +import { YamlUtil } from "../util/yaml-util" /** * Formats (or, depending on `sortOnSave`, sorts) a whole yaml document. @@ -18,13 +19,14 @@ export class YamlFormattingProvider implements DocumentFormattingEditProvider { * @returns One edit replacing the whole document, or no edit if the document cannot be processed. */ provideDocumentFormattingEdits(document: TextDocument): TextEdit[] { - const settings = new Settings() + const settings = Settings.forDocument(document) + const yamlutil = new YamlUtil(settings) const text = document.getText() let newText: string | null try { newText = settings.doSortOnSave() - ? sortDocuments(text, { customSort: settings.sortOnSave, isSelection: false }) - : formatDocuments(text) + ? sortDocuments(text, { customSort: settings.sortOnSave, isSelection: false }, yamlutil) + : formatDocuments(text, yamlutil) } catch (error) { this.errorutil.handleError(error) return [] diff --git a/src/settings.ts b/src/settings.ts index 3e5e083..18dfbea 100644 --- a/src/settings.ts +++ b/src/settings.ts @@ -1,7 +1,7 @@ import { CLOUDFORMATION_SCHEMA } from "cloudformation-js-yaml-schema" import { HOMEASSISTANT_SCHEMA } from "homeassistant-js-yaml-schema" import { CORE_SCHEMA, DEFAULT_SCHEMA, FAILSAFE_SCHEMA, JSON_SCHEMA, Schema } from "js-yaml" -import { WorkspaceConfiguration, workspace } from "vscode" +import { ConfigurationScope, WorkspaceConfiguration, workspace } from "vscode" type QuotingType = "'" | "\"" @@ -75,6 +75,20 @@ export class Settings { this.useOctalProcessor = read("useOctalProcessor") } + /** + * Reads the settings that apply to a document: workspace folder settings in a multi-root + * workspace and language specific settings like `"[yaml]": { "vscode-yaml-sort.indent": 4 }`. + * @param document The document, or its uri and language id. + * @param getConfiguration Injectable for tests. + * @returns The settings for the document. + */ + static forDocument( + document: ConfigurationScope, + getConfiguration: (section?: string, scope?: ConfigurationScope) => WorkspaceConfiguration = workspace.getConfiguration + ): Settings { + return new Settings(getConfiguration(Settings.SECTION, document)) + } + /** * @param index 1, 2 or 3. * @returns The keywords of the custom sort, or an empty list for any other index. diff --git a/src/test/suite/settings.test.ts b/src/test/suite/settings.test.ts index ee0f8a8..3c2f393 100644 --- a/src/test/suite/settings.test.ts +++ b/src/test/suite/settings.test.ts @@ -3,6 +3,7 @@ import { deepEqual, equal } from "assert" import { CLOUDFORMATION_SCHEMA } from "cloudformation-js-yaml-schema" import { HOMEASSISTANT_SCHEMA } from "homeassistant-js-yaml-schema" import { CORE_SCHEMA, DEFAULT_SCHEMA, FAILSAFE_SCHEMA, JSON_SCHEMA, Schema} from "js-yaml" +import { Uri, workspace } from "vscode" import { Settings } from "../../settings" @@ -127,3 +128,18 @@ suite("Test Settings - doSortOnSave()", () => { equal(settings.doSortOnSave(), false) }) }) + +suite("Test Settings - forDocument()", () => { + test("should read the configuration for the given document", () => { + const document = { uri: Uri.file("/project/a.yaml"), languageId: "yaml" } + const calls: unknown[][] = [] + const getConfiguration = (section?: string, scope?: unknown) => { + calls.push([section, scope]) + return workspace.getConfiguration(section) + } + + Settings.forDocument(document, getConfiguration) + + deepEqual(calls, [["vscode-yaml-sort", document]]) + }) +}) From 8667dce75563c90dbdb7a94eea6cb89780ea9dc7 Mon Sep 17 00:00:00 2001 From: Pascal Reitermann Date: Fri, 20 Nov 2026 07:14:38 +0000 Subject: [PATCH 5/6] perf(activation): activate only for yaml files and the extension's commands The extension was activated on onStartupFinished, i.e. in every workspace on every start of VS Code, even without a single yaml file. Activate on onLanguage:yaml, which registers the formatter before the first yaml document can be formatted, and on each contributed command. The onCommand events have to be listed explicitly, because engines.vscode is ^1.49.0 and VS Code derives them automatically only since 1.74. A test checks that the list matches the contributed commands. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Jdb5is9YsMnteaxHryN26M --- CHANGELOG.md | 2 ++ package.json | 9 ++++++++- src/test/suite/package-manifest.test.ts | 27 +++++++++++++++++++++++++ 3 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 src/test/suite/package-manifest.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index fd45274..59f0e23 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,8 @@ ✨ Feature * Settings can now be set per workspace folder in a multi-root workspace and per language (e.g. `"[yaml]": { "vscode-yaml-sort.indent": 4 }`). Every command and the formatter read the settings that apply to the processed document * (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) +⚡ Performance +* The extension is only activated when a yaml file is opened or one of its commands is run, instead of on every start of VS Code 📦 Dependencies * Move `@types/js-yaml` and `@vscode/test-electron` to `devDependencies`, so they are no longer shipped with the extension diff --git a/package.json b/package.json index 8f02f8e..bd6bebe 100644 --- a/package.json +++ b/package.json @@ -28,7 +28,14 @@ "Formatters" ], "activationEvents": [ - "onStartupFinished" + "onLanguage:yaml", + "onCommand:vscode-yaml-sort.customSortYaml_1", + "onCommand:vscode-yaml-sort.customSortYaml_2", + "onCommand:vscode-yaml-sort.customSortYaml_3", + "onCommand:vscode-yaml-sort.formatYaml", + "onCommand:vscode-yaml-sort.sortYaml", + "onCommand:vscode-yaml-sort.sortYamlFilesInDirectory", + "onCommand:vscode-yaml-sort.validateYaml" ], "main": "./out/extension.js", "contributes": { diff --git a/src/test/suite/package-manifest.test.ts b/src/test/suite/package-manifest.test.ts new file mode 100644 index 0000000..9b36fe5 --- /dev/null +++ b/src/test/suite/package-manifest.test.ts @@ -0,0 +1,27 @@ +import { deepEqual, ok } from "assert" +import { readFileSync } from "fs" +import { join } from "path" + +interface Manifest { + activationEvents: string[] + contributes: { commands: { command: string }[] } +} + +// out/test/suite -> project root +const manifest = JSON.parse(readFileSync(join(__dirname, "..", "..", "..", "package.json"), "utf-8")) as Manifest + +suite("Test package.json - activation events", () => { + test("should activate on every contributed command, required for VS Code before 1.74", () => { + const commands = manifest.contributes.commands.map((contribution) => `onCommand:${contribution.command}`) + + deepEqual(manifest.activationEvents.filter((event) => event.startsWith("onCommand:")), commands) + }) + + test("should activate when a yaml document is opened, so the formatter is registered", () => { + ok(manifest.activationEvents.includes("onLanguage:yaml")) + }) + + test("should not activate on startup in every workspace", () => { + ok(!manifest.activationEvents.includes("onStartupFinished") && !manifest.activationEvents.includes("*")) + }) +}) From b4f085ac84f31deb5f70d424f1ecc5855395d0f1 Mon Sep 17 00:00:00 2001 From: Pascal Reitermann Date: Fri, 20 Nov 2026 07:15:09 +0000 Subject: [PATCH 6/6] fix(commands): offer the editor commands only for yaml files The command contributions carried `"when": "editorLangId == yaml"`, but `when` is no property of contributes.commands and VS Code ignores it, so sort, custom sort, format and validate were offered in the command palette for every file. Move the conditions to menus.commandPalette, where VS Code evaluates them, and check them in the manifest test. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Jdb5is9YsMnteaxHryN26M --- CHANGELOG.md | 1 + package.json | 42 ++++++++++++++++++------- src/test/suite/package-manifest.test.ts | 19 ++++++++++- 3 files changed, 49 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 59f0e23..90c9327 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased 🐛 Bugfixes +* The editor commands (sort, custom sort, format, validate) are only offered in the command palette for yaml files. The condition was declared at a place VS Code ignores * (refs [#65](https://github.com/pascalre/vscode-yaml-sort/issues/65)) Formatting via "Format Document" or on save no longer shows "Yaml formatted successfully", once per document. The command `Format YAML` shows it once after the changes were applied * Command `Recursively sort YAML files` now sorts files with several documents, works without an open editor and is only offered for folders in the explorer. A file that cannot be sorted is reported and left unchanged. Files are now also found on Windows paths * Keep every document delimiter (`---`, including a comment behind it) in front of its own document. Before, several documents without a leading `---` got a duplicated `---` (an additional empty document), and with a leading `--- # comment` the comments moved to the next document or got lost diff --git a/package.json b/package.json index bd6bebe..10b13c4 100644 --- a/package.json +++ b/package.json @@ -257,28 +257,23 @@ "commands": [ { "command": "vscode-yaml-sort.customSortYaml_1", - "title": "YAML Sort: Custom sort 1", - "when": "editorLangId == yaml" + "title": "YAML Sort: Custom sort 1" }, { "command": "vscode-yaml-sort.customSortYaml_2", - "title": "YAML Sort: Custom sort 2", - "when": "editorLangId == yaml" + "title": "YAML Sort: Custom sort 2" }, { "command": "vscode-yaml-sort.customSortYaml_3", - "title": "YAML Sort: Custom sort 3", - "when": "editorLangId == yaml" + "title": "YAML Sort: Custom sort 3" }, { "command": "vscode-yaml-sort.formatYaml", - "title": "YAML Sort: Format YAML", - "when": "editorLangId == yaml" + "title": "YAML Sort: Format YAML" }, { "command": "vscode-yaml-sort.sortYaml", - "title": "YAML Sort: Sort YAML", - "when": "editorLangId == yaml" + "title": "YAML Sort: Sort YAML" }, { "command": "vscode-yaml-sort.sortYamlFilesInDirectory", @@ -286,8 +281,7 @@ }, { "command": "vscode-yaml-sort.validateYaml", - "title": "YAML Sort: Validate YAML", - "when": "editorLangId == yaml" + "title": "YAML Sort: Validate YAML" } ], "menus": { @@ -295,6 +289,30 @@ { "command": "vscode-yaml-sort.sortYamlFilesInDirectory", "when": "false" + }, + { + "command": "vscode-yaml-sort.customSortYaml_1", + "when": "editorLangId == yaml" + }, + { + "command": "vscode-yaml-sort.customSortYaml_2", + "when": "editorLangId == yaml" + }, + { + "command": "vscode-yaml-sort.customSortYaml_3", + "when": "editorLangId == yaml" + }, + { + "command": "vscode-yaml-sort.formatYaml", + "when": "editorLangId == yaml" + }, + { + "command": "vscode-yaml-sort.sortYaml", + "when": "editorLangId == yaml" + }, + { + "command": "vscode-yaml-sort.validateYaml", + "when": "editorLangId == yaml" } ], "explorer/context": [ diff --git a/src/test/suite/package-manifest.test.ts b/src/test/suite/package-manifest.test.ts index 9b36fe5..9ce8c51 100644 --- a/src/test/suite/package-manifest.test.ts +++ b/src/test/suite/package-manifest.test.ts @@ -4,7 +4,10 @@ import { join } from "path" interface Manifest { activationEvents: string[] - contributes: { commands: { command: string }[] } + contributes: { + commands: { command: string }[] + menus: { commandPalette: { command: string, when: string }[] } + } } // out/test/suite -> project root @@ -25,3 +28,17 @@ suite("Test package.json - activation events", () => { ok(!manifest.activationEvents.includes("onStartupFinished") && !manifest.activationEvents.includes("*")) }) }) + +suite("Test package.json - command palette", () => { + const palette = manifest.contributes.menus.commandPalette + + test("should offer the editor commands in the command palette only for yaml files", () => { + const editorCommands = manifest.contributes.commands + .map((contribution) => contribution.command) + .filter((command) => command !== "vscode-yaml-sort.sortYamlFilesInDirectory") + + for (const command of editorCommands) { + ok(palette.some((entry) => entry.command === command && entry.when === "editorLangId == yaml"), command) + } + }) +})