Skip to content

Commit

Permalink
Add ArrayProcessor to keep single line arrays (#36)
Browse files Browse the repository at this point in the history
  • Loading branch information
pascalre committed Jan 25, 2023
1 parent 77e4076 commit dd2530a
Show file tree
Hide file tree
Showing 25 changed files with 406 additions and 285 deletions.
39 changes: 34 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ YAML Sort extends VS Code to sort, format and validate YAML files.
## Preview
![Preview](images/preview.gif)

# Commands
# 💬 Commands
This extension contributes the following commands:

| Command | Description |
Expand All @@ -20,7 +20,7 @@ This extension contributes the following commands:
| `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. |

# Configuration
# ⚙️ Configuration
This extension contributes the following settings:

| Setting | Description | Default |
Expand All @@ -43,8 +43,11 @@ This extension contributes the following settings:
| `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` |
| `useArrayProcessor` | When `true`, will activate ArrayProcessor. | `true` |
| `useCommentProcessor` | When `true`, will activate CommentProcessor. | `true` |
| `useHelmProcessor` | When `true`, will activate HelmProcessor. | `true` |

# FAQ
# 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.

Expand All @@ -57,7 +60,33 @@ Register this extension as VS Code formatter. Also configure VS Code to format f
}
```

# Support
## What are the processors doing and how do I use them?
There are different types of processors. If you experience any issues with them, or just don't want to use them, you can turn them off.
### CommentProcessor
An activated CommentProcessor will keep comments while sorting.

### HelmProcessor
The HelmProcessor makes the extension compatible with Helm charts.

### ArrayProcessor
The ArrayProcessor will not add linebreaks to single-line array structures. Example:
```
test: [ "CMD", "pg_isready", "-q", "-d", "${DB_NAME}", "-U", "${DB_USER}" ]
```

If `useArrayProcessor` is set to `false` will output:
```
test:
- "CMD"
- "pg_isready"
- "-q"
- "-d"
- "${DB_NAME}"
- "-U"
- "${DB_USER}"
```

# 🎉 Support

If you like YAML Sort, please feel free to [rate it](https://marketplace.visualstudio.com/items?itemName=PascalReitermann93.vscode-yaml-sort&ssr=false#review-details) on the marketplace.

Expand All @@ -69,6 +98,6 @@ Check [open issues](https://github.com/pascalre/vscode-yaml-sort/issues) on GitH

Be careful with anchors and references, these don't work very well in this extension.

# License
# 📝 License

YAML Sort is licensed under the [MIT License](https://raw.githubusercontent.com/pascalre/vscode-yaml-sort/master/LICENSE).
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,21 @@
"type": "boolean",
"default": true,
"description": "Define if sorted YAML files should begin with leading dashes."
},
"vscode-yaml-sort.useArrayProcessor": {
"type": "boolean",
"default": true,
"description": "When `true`, will activate ArrayProcessor"
},
"vscode-yaml-sort.useCommentProcessor": {
"type": "boolean",
"default": true,
"description": "When `true`, will activate CommentProcessor"
},
"vscode-yaml-sort.useHelmProcessor": {
"type": "boolean",
"default": true,
"description": "When `true`, will activate HelmProcessor"
}
}
},
Expand Down
12 changes: 6 additions & 6 deletions src/adapter/js-yaml-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,14 @@ export class JsYamlAdapter {
const sort = new SortUtil(this.settings, custom)

let yaml = dump(text, {
indent: this.settings.getIndent(),
forceQuotes: this.settings.getForceQuotes(),
lineWidth: this.settings.getLineWidth(),
noArrayIndent: this.settings.getNoArrayIndent(),
noCompatMode: this.settings.getNoCompatMode(),
indent: this.settings.indent,
forceQuotes: this.settings.forceQuotes,
lineWidth: this.settings.lineWidth,
noArrayIndent: this.settings.noArrayIndent,
noCompatMode: this.settings.noCompatMode,
quotingType: this.settings.getQuotingType(),
schema: this.settings.getSchema(),
sortKeys: (!(custom > 0 && this.settings.getUseCustomSortRecursively()) ? sortKeys : (a: string, b: string) => {
sortKeys: (!(custom > 0 && this.settings.useCustomSortRecursively) ? sortKeys : (a: string, b: string) => {
return sort.customSort(a, b)
})
})
Expand Down
4 changes: 2 additions & 2 deletions src/adapter/vs-code-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export class VsCodeAdapter {
// on a configuration setting
registerFormatter(formatter: DocumentFormattingEditProvider) {
let registration: Disposable | undefined
const useAsFormatter = this.settings.getUseAsFormatter()
const useAsFormatter = this.settings.useAsFormatter
if (useAsFormatter && !registration) {
languages.registerDocumentFormattingEditProvider('yaml', formatter)
} else if (!useAsFormatter && registration) {
Expand All @@ -38,7 +38,7 @@ export class VsCodeAdapter {
}

notify(message: string) {
if (this.settings.getNotifySuccess()) {
if (this.settings.notifySuccess) {
window.showInformationMessage(message)
}
}
Expand Down
20 changes: 10 additions & 10 deletions src/controller.ts → src/controller/controller.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { TextEditor, TextEdit, Uri, window } from "vscode"
import { JsYamlAdapter } from "./adapter/js-yaml-adapter"
import { Severity, VsCodeAdapter } from "./adapter/vs-code-adapter"
import { prependWhitespacesOnEachLine, removeLeadingLineBreakOfFirstElement } from "./lib"
import { Settings } from "./settings"
import { FileUtil } from "./util/file-util"
import { getDelimiters, splitYaml, validateTextRange, YamlUtil } from "./util/yaml-util"
import { JsYamlAdapter } from "../adapter/js-yaml-adapter"
import { Severity, VsCodeAdapter } from "../adapter/vs-code-adapter"
import { prependWhitespacesOnEachLine, removeLeadingLineBreakOfFirstElement } from "../lib"
import { Settings } from "../settings"
import { FileUtil } from "../util/file-util"
import { getDelimiters, splitYaml, validateTextRange, YamlUtil } from "../util/yaml-util"

const settings = new Settings()
const jsyamladapter = new JsYamlAdapter()
Expand Down Expand Up @@ -77,7 +77,7 @@ export function sortYamlWrapper(customSort = 0): TextEdit[] {
return [] as TextEdit[]
}

let delimiters = getDelimiters(text, activeEditor.selection.isEmpty, settings.getUseLeadingDashes())
let delimiters = getDelimiters(text, activeEditor.selection.isEmpty, settings.useLeadingDashes)
// remove yaml metadata tags
const matchMetadata = /^%.*\n/gm
// set metadata tags, if there is no metadata tag it should be an emtpy array
Expand All @@ -103,7 +103,7 @@ export function sortYamlWrapper(customSort = 0): TextEdit[] {
return [] as TextEdit[]
}
})
if (activeEditor.selection.isEmpty && settings.getUseLeadingDashes()) {
if (activeEditor.selection.isEmpty && settings.useLeadingDashes) {
newText = `---\n${newText}`
}
outterVscodeadapter.showMessage(Severity.INFO, "Keys resorted successfully")
Expand All @@ -123,7 +123,7 @@ export function formatYamlWrapper(): TextEdit[] {

if (activeEditor) {
let doc = VsCodeAdapter.getActiveDocument(activeEditor)
let delimiters = getDelimiters(doc, true, settings.getUseLeadingDashes())
let delimiters = getDelimiters(doc, true, settings.useLeadingDashes)
// remove yaml metadata tags
const matchMetadata = /^%.*\n/gm
// set metadata tags, if there is no metadata tag it should be an emtpy array
Expand All @@ -145,7 +145,7 @@ export function formatYamlWrapper(): TextEdit[] {
return []
}
}
if (settings.getUseLeadingDashes()) {
if (settings.useLeadingDashes) {
newText = `---\n${newText}`
}
return updateText(activeEditor, newText)
Expand Down
57 changes: 57 additions & 0 deletions src/controller/processor-controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { ArrayProcessor } from "../processor/array-processor"
import { CommentProcessor } from "../processor/comment-processor"
import { HelmProcessor } from "../processor/helm-processor"
import { Settings } from "../settings"

export class ProcessorController {
arrayprocessor!: ArrayProcessor
commentprocessor!: CommentProcessor
helmprocessor!: HelmProcessor
text: string
settings: Settings

constructor(text: string, settings = new Settings()) {
this.text = text
this.settings = settings
}

preprocess() {
if (this.settings.useArrayProcessor) {
this.arrayprocessor = new ArrayProcessor(this.text)
this.arrayprocessor.preprocess()
this.text = this.arrayprocessor.text
}

if (this.settings.useHelmProcessor) {
this.helmprocessor = new HelmProcessor(this.text)
this.helmprocessor.preprocess()
this.text = this.helmprocessor.text
}

if (this.settings.useCommentProcessor) {
this.commentprocessor = new CommentProcessor(this.text)
this.commentprocessor.findComments()
this.text = this.commentprocessor.text
}
}

postprocess() {
if (this.settings.useCommentProcessor) {
this.commentprocessor.text = this.text
this.commentprocessor.postprocess()
this.text = this.commentprocessor.text
}

if (this.settings.useHelmProcessor) {
this.helmprocessor.text = this.text
this.helmprocessor.postprocess()
this.text = this.helmprocessor.text
}

if (this.settings.useArrayProcessor) {
this.arrayprocessor.text = this.text
this.arrayprocessor.postprocess()
this.text = this.arrayprocessor.text
}
}
}
2 changes: 1 addition & 1 deletion src/extension.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { ExtensionContext, DocumentFormattingEditProvider, commands, Uri, TextEdit } from "vscode"
import { Settings } from "./settings"
import { VsCodeAdapter } from "./adapter/vs-code-adapter"
import { formatYamlWrapper, sortYamlWrapper, Controller } from "./controller"
import { formatYamlWrapper, sortYamlWrapper, Controller } from "./controller/controller"

const settings = new Settings()
const vscodeadapter = new VsCodeAdapter()
Expand Down
7 changes: 7 additions & 0 deletions src/processor/array-processor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { GenericProcessor } from "./generic-processor";

export class ArrayProcessor extends GenericProcessor {
constructor(text: string) {
super("array", /\[([^[]*)\]/g, text)
}
}
13 changes: 6 additions & 7 deletions src/processor/comment-processor.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export class CommentProcessor {
comments: string[][] = []
store: string[][] = []
text: string
lines: string[]

Expand All @@ -26,23 +26,22 @@ export class CommentProcessor {

addLineToComments(index: number) {
if (index < this.lines.length-1) {
this.comments.push([this.lines[index], this.lines[index+1]])
this.store.push([this.lines[index], this.lines[index+1]])
} else {
this.comments.push([this.lines[index], 'vscode-yaml-sort.lastLine'])
this.store.push([this.lines[index], 'vscode-yaml-sort.lastLine'])
}
}

applyComments(text: string): string {
this.text = text
postprocess(): string {
this.reverseComments()
this.comments.forEach(comment => {
this.store.forEach(comment => {
this.applyComment(comment)
})
return this.text
}

reverseComments() {
this.comments.reverse()
this.store.reverse()
}

applyComment(comment: string[]) {
Expand Down
42 changes: 42 additions & 0 deletions src/processor/generic-processor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
export abstract class GenericProcessor {
filter: string
matcher: RegExp
store: Map<string, string> = new Map()
text: string

constructor(filter: string, matcher: RegExp, text: string) {
this.filter = filter
this.matcher = matcher
this.text = text
}

preprocess() {
const matches = this.findMatches()
if (matches) {
for (const match of matches) {
this.replaceValueWithSubstitue(match)
}
}
}

findMatches() {
return this.text.match(this.matcher)
}

replaceValueWithSubstitue(value: string) {
const substitue = `vscode-yaml-sort.${this.filter}.${this.store.size}`
this.store.set(substitue, value)
this.text = this.text.replace(value, substitue)
}

postprocess() {
this.store.forEach((value: string, key: string) => {
this.replaceSubstituteWithValue(key, value)
})
}

replaceSubstituteWithValue(substitue: string, value: string) {
const match = new RegExp(`('|")?${substitue}('|")?`)
this.text = this.text.replace(match, value)
}
}
Loading

0 comments on commit dd2530a

Please sign in to comment.