Skip to content

Commit

Permalink
Added formatter
Browse files Browse the repository at this point in the history
  • Loading branch information
JPinkney committed Sep 24, 2018
1 parent 74f640a commit a5092e3
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 35 deletions.
7 changes: 6 additions & 1 deletion package-lock.json

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

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"dependencies": {
"js-yaml": "^3.12.0",
"jsonc-parser": "^1.0.3",
"prettier": "^1.14.3",
"request-light": "^0.2.3",
"vscode-json-languageservice": "3.0.12",
"vscode-languageserver": "^4.0.0",
Expand Down
38 changes: 4 additions & 34 deletions src/languageservice/services/yamlFormatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,43 +5,13 @@
*--------------------------------------------------------------------------------------------*/
'use strict';

import * as jsyaml from 'js-yaml';
import * as Yaml from 'yaml-ast-parser'
import { EOL } from 'os';
import { TextDocument, Range, Position, FormattingOptions, TextEdit } from 'vscode-languageserver-types';
const prettier = require("prettier");

export function format(document: TextDocument, options: FormattingOptions, customTags: Array<String>): TextEdit[] {
const text = document.getText();

let schemaWithAdditionalTags = jsyaml.Schema.create(customTags.map((tag) => {
const typeInfo = tag.split(' ');
return new jsyaml.Type(typeInfo[0], { kind: typeInfo[1] || 'scalar' });
}));
const formatted = prettier.format(text, { parser: "yaml"});

//We need compiledTypeMap to be available from schemaWithAdditionalTags before we add the new custom properties
customTags.map((tag) => {
const typeInfo = tag.split(' ');
schemaWithAdditionalTags.compiledTypeMap[typeInfo[0]] = new jsyaml.Type(typeInfo[0], { kind: typeInfo[1] || 'scalar' });
});

let additionalOptions: Yaml.LoadOptions = {
schema: schemaWithAdditionalTags
}

const documents = []
jsyaml.loadAll(text, doc => documents.push(doc), additionalOptions)

const dumpOptions = { indent: options.tabSize, noCompatMode: true };

let newText;
if (documents.length == 1) {
const yaml = documents[0]
newText = jsyaml.safeDump(yaml, dumpOptions)
}
else {
const formatted = documents.map(d => jsyaml.safeDump(d, dumpOptions))
newText = '%YAML 1.2' + EOL + '---' + EOL + formatted.join('...' + EOL + '---' + EOL) + '...' + EOL
}

return [TextEdit.replace(Range.create(Position.create(0, 0), document.positionAt(text.length)), newText)]
}
return [TextEdit.replace(Range.create(Position.create(0, 0), document.positionAt(text.length)), formatted)];
}

0 comments on commit a5092e3

Please sign in to comment.