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 +} diff --git a/CHANGELOG.md b/CHANGELOG.md index ac18ac0..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 @@ -23,7 +24,10 @@ * (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) +⚡ 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/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..10b13c4 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": { @@ -51,11 +58,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 +79,7 @@ }, "vscode-yaml-sort.customSortKeywords_2": { "type": "array", + "scope": "language-overridable", "items": { "type": "string" }, @@ -78,6 +88,7 @@ }, "vscode-yaml-sort.customSortKeywords_3": { "type": "array", + "scope": "language-overridable", "items": { "type": "string" }, @@ -86,6 +97,7 @@ }, "vscode-yaml-sort.extensions": { "type": "array", + "scope": "resource", "items": { "type": "string" }, @@ -97,26 +109,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 +153,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 +170,7 @@ }, "vscode-yaml-sort.quotingType": { "type": "string", + "scope": "language-overridable", "default": "'", "enum": [ "'", @@ -160,6 +180,7 @@ }, "vscode-yaml-sort.schema": { "type": "string", + "scope": "language-overridable", "default": "DEFAULT_SCHEMA", "enum": [ "HOMEASSISTANT_SCHEMA", @@ -173,51 +194,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" } @@ -226,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", @@ -255,8 +281,7 @@ }, { "command": "vscode-yaml-sort.validateYaml", - "title": "YAML Sort: Validate YAML", - "when": "editorLangId == yaml" + "title": "YAML Sort: Validate YAML" } ], "menus": { @@ -264,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/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/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/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/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/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/settings.ts b/src/settings.ts index 4ffe044..18dfbea 100644 --- a/src/settings.ts +++ b/src/settings.ts @@ -1,89 +1,145 @@ 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 { ConfigurationScope, WorkspaceConfiguration, workspace } from "vscode" +type QuotingType = "'" | "\"" + +// js-yaml only supports these styles for the !!null tag +const NULL_STYLES = ["lowercase", "uppercase", "camelcase", "canonical", "empty"] + +/** + * 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 { - filter = "vscode-yaml-sort" - workspace = workspace + static readonly SECTION = "vscode-yaml-sort" - getBoolean(name: string) { - return this.workspace.getConfiguration().get(`${this.filter}.${name}`) as boolean - } + 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 - getNumber(name: string) { - return this.workspace.getConfiguration().get(`${this.filter}.${name}`) as number - } + /** + * @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") + } - getString(name: string) { - return this.workspace.getConfiguration().get(`${this.filter}.${name}`) as string - } + /** + * 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)) + } - 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")) 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/package-manifest.test.ts b/src/test/suite/package-manifest.test.ts new file mode 100644 index 0000000..9ce8c51 --- /dev/null +++ b/src/test/suite/package-manifest.test.ts @@ -0,0 +1,44 @@ +import { deepEqual, ok } from "assert" +import { readFileSync } from "fs" +import { join } from "path" + +interface Manifest { + activationEvents: string[] + contributes: { + commands: { command: string }[] + menus: { commandPalette: { command: string, when: 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("*")) + }) +}) + +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) + } + }) +}) 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]]) + }) +}) 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