Skip to content

Commit

Permalink
Merge 1200169 into 60a726e
Browse files Browse the repository at this point in the history
  • Loading branch information
pascalre committed Feb 11, 2023
2 parents 60a726e + 1200169 commit d573d2d
Show file tree
Hide file tree
Showing 13 changed files with 96 additions and 103 deletions.
7 changes: 3 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ This extension contributes the following commands:
| `Custom Sort 1` | This command will sort a given YAML with custom order. If some of the keys of `customSortKeywords_1` will be found at the top level of the YAML, these will be put at the beginning of the YAML file (in the given order). You can use this e. g. to sort Kubernetes configmaps. |
| `Custom Sort 2` | Same as `Custom Sort 1` |
| `Custom Sort 3` | Same as `Custom Sort 1` |
| `Format Document` | Formats a yaml document without sorting it. Also possible using the shortcut (e. g. `SHIFT` + `OPTION` + `F` on Mac). |
| `Format Document` | Formats a yaml document without sorting it. Also possible using the shortcut (⇧⌥F on Mac). |
| `Recursively sort YAML files` | Sorts all `.yaml` and `.yml` files in a directory and all its subdirectories. |
| `Sort YAML` | Sorts a given YAML. You can either sort the whole YAML document or sort only a selection of the text. |
| `Validate YAML` | Validates a given YAML. |
Expand All @@ -39,7 +39,7 @@ This extension contributes the following settings:
| `notifySuccess` | When `true`, will notify on successfully performed tasks. | `true` |
| `quotingType` | Strings will be quoted using this quoting style. If you specify single quotes, double quotes will still be used for non-printable characters. | `'` |
| `schema` | Schema to use. Possible values are `HOMEASSISTANT_SCHEMA`, `CLOUDFORMATION_SCHEMA`, `CORE_SCHEMA`, `DEFAULT_SCHEMA`, `FAILSAFE_SCHEMA`, `JSON_SCHEMA`. | `DEFAULT_SCHEMA` |
| `sortOnSave` | When `0`, will sort files when saving document. When `1`, `2` or `3`, will use customSortKeywords. Set to negative value to disable sortOnSave. Only works in combination with `editor.formatOnSave` and `vscode-yaml-sort.useAsFormatter` both set to `true`. | `0` |
| `sortOnSave` | When `0`, will sort files when saving document. When `1`, `2` or `3`, will use customSortKeywords. Set to negative value to disable sortOnSave. Only works in combination with `editor.formatOnSave` set to `true`. | `0` |
| `useAsFormatter` | When `true`, will enable default YAML formatter (requires restart). | `false` |
| `useCustomSortRecursively` | When `true`, will use the custom sort keywords recursively on a file, when using custom sort. | `false` |
| `useLeadingDashes` | When `true`, sorted YAML files begin with leading dashes. | `true` |
Expand All @@ -56,8 +56,7 @@ Register this extension as VS Code formatter. Also configure VS Code to format f
```json
{
"editor.formatOnSave": true,
"vscode-yaml-sort.sortOnSave": 0,
"vscode-yaml-sort.useAsFormatter": true
"vscode-yaml-sort.sortOnSave": 0
}
```

Expand Down
5 changes: 0 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -157,11 +157,6 @@
"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.useAsFormatter": {
"type": "boolean",
"default": false,
"description": "When true, will enable default YAML formatter (requires restart)."
},
"vscode-yaml-sort.useCustomSortRecursively": {
"type": "boolean",
"default": false,
Expand Down
18 changes: 5 additions & 13 deletions src/adapter/vs-code-adapter.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { workspace, TextEditor, Range, Position, Selection, TextEdit, WorkspaceEdit, window, DocumentFormattingEditProvider, languages, Disposable } from "vscode"
import { workspace, TextEditor, Range, Position, Selection, TextEdit, WorkspaceEdit, window, DocumentFormattingEditProvider, languages } from "vscode"
import { Settings } from "../settings"

export enum Severity {
Expand All @@ -17,18 +17,6 @@ export class VsCodeAdapter {
return workspace.getConfiguration().get(`${this.section}.${property}`)
}

// have a function that adds/removes the formatter based
// on a configuration setting
registerFormatter(formatter: DocumentFormattingEditProvider) {
let registration: Disposable | undefined
const useAsFormatter = this.settings.useAsFormatter
if (useAsFormatter && !registration) {
languages.registerDocumentFormattingEditProvider('yaml', formatter)
} else if (!useAsFormatter && registration) {
registration.dispose()
}
}

showMessage(severity: Severity, message: string) {
if (severity === Severity.ERROR) {
window.showErrorMessage(message)
Expand All @@ -43,6 +31,10 @@ export class VsCodeAdapter {
}
}

static registerFormatter(formatter: DocumentFormattingEditProvider) {
languages.registerDocumentFormattingEditProvider('yaml', formatter)
}

static getText(textEditor: TextEditor, range: Range) {
return textEditor.document.getText(range)
}
Expand Down
18 changes: 8 additions & 10 deletions src/controller/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,14 @@ import { ErrorUtil } from "../util/error-util"
import { FileUtil } from "../util/file-util"
import { splitYaml, validateTextRange, YamlUtil } from "../util/yaml-util"

const settings = new Settings()
const jsyamladapter = new JsYamlAdapter()
const outteryamlutil = new YamlUtil()

export class Controller {
editor: TextEditor
fileutil = new FileUtil()
yamlutil = new YamlUtil()
jsyamladapter = new JsYamlAdapter()
vscodeadapter = new VsCodeAdapter()
errorutil = new ErrorUtil()
settings = new Settings()

constructor() {
if (window.activeTextEditor) {
Expand All @@ -29,7 +27,7 @@ export class Controller {
validateYamlWrapper(): boolean {
const text = VsCodeAdapter.getActiveDocument(this.editor)
try {
jsyamladapter.validateYaml(text)
this.jsyamladapter.validateYaml(text)
this.vscodeadapter.showMessage(Severity.INFO, "YAML is valid.")
return true
} catch (error) {
Expand Down Expand Up @@ -73,14 +71,14 @@ export class Controller {
const yamls = splitYaml(doc)
let newText = ""
for (const unformattedYaml of yamls) {
const formattedYaml = outteryamlutil.formatYaml(unformattedYaml, false)
const formattedYaml = this.yamlutil.formatYaml(unformattedYaml, false)
if (formattedYaml) {
newText += delimiters.shift() + formattedYaml
} else {
return []
}
}
if (settings.useLeadingDashes) {
if (this.settings.useLeadingDashes) {
newText = `---\n${newText}`
}
return this.applyEdits(newText)
Expand All @@ -98,7 +96,7 @@ export class Controller {

try {
validateTextRange(text)
jsyamladapter.validateYaml(text)
this.jsyamladapter.validateYaml(text)
} catch (error) {
this.errorutil.handleError(error)
return [] as TextEdit[]
Expand All @@ -118,7 +116,7 @@ export class Controller {
// sort yaml
let newText = ""
splitYaml(text).forEach((unsortedYaml) => {
let sortedYaml = outteryamlutil.sortYaml(unsortedYaml, customSort)
let sortedYaml = this.yamlutil.sortYaml(unsortedYaml, customSort)
if (sortedYaml) {
if (!this.editor.selection.isEmpty) {
// get number of leading whitespaces, these whitespaces will be used for indentation
Expand All @@ -130,7 +128,7 @@ export class Controller {
return [] as TextEdit[]
}
})
if (this.editor.selection.isEmpty && settings.useLeadingDashes) {
if (this.editor.selection.isEmpty && this.settings.useLeadingDashes) {
newText = `---\n${newText}`
}
this.vscodeadapter.showMessage(Severity.INFO, "Keys resorted successfully")
Expand Down
8 changes: 7 additions & 1 deletion src/controller/processor-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { CommentProcessor } from "../processor/comment-processor"
import { HelmProcessor } from "../processor/helm-processor"
import { OctalProcessor } from "../processor/octal-processor"
import { SpacingProcessor } from "../processor/spacing-processor"
import { TabsToSpacesProcessor } from "../processor/tabs-to-spaces-processor"
import { Settings } from "../settings"

export class ProcessorController {
Expand All @@ -11,6 +12,7 @@ export class ProcessorController {
helmprocessor!: HelmProcessor
octalprocessor!: OctalProcessor
spacingprocessor!: SpacingProcessor
tabstospacespreprocessor!: TabsToSpacesProcessor
text: string
settings: Settings

Expand All @@ -20,6 +22,10 @@ export class ProcessorController {
}

preprocess() {
this.tabstospacespreprocessor = new TabsToSpacesProcessor(this.text)
this.tabstospacespreprocessor.preprocess()
this.text = this.tabstospacespreprocessor.text

if (this.settings.useArrayProcessor) {
this.arrayprocessor = new ArrayProcessor(this.text)
this.arrayprocessor.preprocess()
Expand Down Expand Up @@ -53,7 +59,7 @@ export class ProcessorController {
}

if (this.settings.useOctalProcessor) {
this.octalprocessor = new OctalProcessor(this.text)
this.octalprocessor.text = this.text
this.octalprocessor.postprocess()
this.text = this.octalprocessor.text
}
Expand Down
32 changes: 10 additions & 22 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,21 @@ import { Settings } from "./settings"
import { VsCodeAdapter } from "./adapter/vs-code-adapter"
import { Controller } from "./controller/controller"

const settings = new Settings()
const vscodeadapter = new VsCodeAdapter()

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: ExtensionContext) {

const formatter: DocumentFormattingEditProvider = {
provideDocumentFormattingEdits(): TextEdit[] {
const settings = new Settings()
if (settings.doSortOnSave()) {
return new Controller().sortYamlWrapper(settings.sortOnSave)
} else {/* istanbul ignore next */
} else {
return new Controller().formatYamlWrapper()
}
}
}

// register at activate-time
vscodeadapter.registerFormatter(formatter)
VsCodeAdapter.registerFormatter(formatter)

// The command has been defined in the package.json file
// Now provide the implementation of the command with registerCommand
// The commandId parameter must match the command field in package.json
context.subscriptions.push(
commands.registerCommand("vscode-yaml-sort.sortYaml", () => {
new Controller().sortYamlWrapper()
Expand All @@ -36,19 +28,15 @@ export function activate(context: ExtensionContext) {
commands.registerCommand("vscode-yaml-sort.formatYaml", () => {
new Controller().formatYamlWrapper()
}),
commands.registerCommand("vscode-yaml-sort.customSortYaml_1", () => {
new Controller().sortYamlWrapper(1)
}),
commands.registerCommand("vscode-yaml-sort.customSortYaml_2", () => {
/* istanbul ignore next */
new Controller().sortYamlWrapper(2)
}),
commands.registerCommand("vscode-yaml-sort.customSortYaml_3", () => {
/* istanbul ignore next */
new Controller().sortYamlWrapper(3)
}),
commands.registerCommand("vscode-yaml-sort.sortYamlFilesInDirectory", (uri: Uri) => {
new Controller().sortYamlFiles(uri)
})
)
for (const index of [1, 2, 3]) {
context.subscriptions.push(
commands.registerCommand(`vscode-yaml-sort.customSortYaml_${index}`, () => {
new Controller().sortYamlWrapper(index)
})
)
}
}
15 changes: 0 additions & 15 deletions src/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,21 +28,6 @@ export function removeLeadingLineBreakOfFirstElement(delimiters: RegExpMatchArra
return delimiters
}

/**
* Replace all tabs in a given string with spaces
* @param {string} text Text to be processed
* @param {number} count Number of spaces to be added for a removed tab
* @returns {string} processed text
*/
export function replaceTabsWithSpaces(text: string, count: number): string {
if (count < 1) {
throw new Error("The count parameter has to be 1 or higher")
}

const spaces = " ".repeat(count)
return text.replace(/\t/mg, spaces)
}

/**
* Add a new line before each occurence of a top level keyword after a new line
* @param {string} text Text to be processed
Expand Down
16 changes: 16 additions & 0 deletions src/processor/tabs-to-spaces-processor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Settings } from "../settings"

export class TabsToSpacesProcessor {
text: string
settings = new Settings()

constructor(text: string) {
this.text = text
}

preprocess() {
const spaces = " ".repeat(this.settings.indent)
this.text = this.text.replace(/\t/mg, spaces)
}
}

1 change: 0 additions & 1 deletion src/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ export class Settings {
quotingType = this.getQuotingType()
schema = this.getSchema()
sortOnSave = this.getNumber("sortOnSave")
useAsFormatter = this.getBoolean("useAsFormatter")
useCustomSortRecursively = this.getBoolean("useCustomSortRecursively")
useLeadingDashes = this.getBoolean("useLeadingDashes")
useArrayProcessor = this.getBoolean("useArrayProcessor")
Expand Down
24 changes: 1 addition & 23 deletions src/test/suite/lib.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { strictEqual, throws} from "assert"
import {
addNewLineBeforeRootKeywords,
prependWhitespacesOnEachLine,
replaceTabsWithSpaces
prependWhitespacesOnEachLine
} from "../../lib"
import { removeTrailingCharacters } from "../../util/yaml-util"

Expand Down Expand Up @@ -52,27 +51,6 @@ suite("Test prependWhitespacesOnEachLine", () => {
})
})

suite("Test replaceTabsWithSpaces", () => {
const actual = `
a-1:
\tb:
\t\td: g
\tc:
\t\td: g`
const expected = `
a-1:
b:
d: g
c:
d: g`
test("should replace all tabs with spaces", () => {
strictEqual(replaceTabsWithSpaces(actual, 2), expected)
})
test("should throw error when count is smaller than `1`", () => {
throws(() => replaceTabsWithSpaces(actual, 0))
})
})

suite("Test addNewLineBeforeRootKeywords", () => {
test("should add an empty line before each top level keyword, but only if they appear after a new line", () => {
const actual = `data:
Expand Down
25 changes: 25 additions & 0 deletions src/test/suite/processor/tabs-to-spaces-preprocessor.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { equal } from "assert"
import { TabsToSpacesProcessor } from "../../../processor/tabs-to-spaces-processor"

suite("Test TabsToSpacesPreprocessor - preprocess()", () => {
const text =
'a-1:\n' +
'\tb:\n' +
'\t\td: g\n' +
'\tc:\n' +
'\t\td: g'

const expected =
'a-1:\n' +
' b:\n' +
' d: g\n' +
' c:\n' +
' d: g'

const tabstospacespreprocessor = new TabsToSpacesProcessor(text)

test("should replace all tabs with spaces", () => {
tabstospacespreprocessor.preprocess()
equal(tabstospacespreprocessor.text, expected)
})
})
4 changes: 0 additions & 4 deletions src/test/suite/settings.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,6 @@ suite("Test Settings - getter", () => {
deepEqual(settings.sortOnSave, 0)
})

test("default value of useAsFormatter is set to `false`", () => {
deepEqual(settings.useAsFormatter, false)
})

test("default value of useCustomSortRecursively is set to `false`", () => {
deepEqual(settings.useCustomSortRecursively, false)
})
Expand Down

0 comments on commit d573d2d

Please sign in to comment.