Skip to content

Commit

Permalink
Merge branch 'main' into f-custom-kubernetes-schema
Browse files Browse the repository at this point in the history
  • Loading branch information
tricktron authored Jun 4, 2024
2 parents f0d5a85 + 7203630 commit a4a1add
Show file tree
Hide file tree
Showing 8 changed files with 192 additions and 53 deletions.
4 changes: 2 additions & 2 deletions src/languageserver/handlers/settingsHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ export class SettingsHandler {

if (settings.yaml.schemaStore) {
this.yamlSettings.schemaStoreEnabled = settings.yaml.schemaStore.enable;
if (settings.yaml.schemaStore.url.length !== 0) {
if (settings.yaml.schemaStore.url?.length !== 0) {
this.yamlSettings.schemaStoreUrl = settings.yaml.schemaStore.url;
}
}
Expand Down Expand Up @@ -180,7 +180,7 @@ export class SettingsHandler {
private async setSchemaStoreSettingsIfNotSet(): Promise<void> {
const schemaStoreIsSet = this.yamlSettings.schemaStoreSettings.length !== 0;
let schemaStoreUrl = '';
if (this.yamlSettings.schemaStoreUrl.length !== 0) {
if (this.yamlSettings.schemaStoreUrl?.length !== 0) {
schemaStoreUrl = this.yamlSettings.schemaStoreUrl;
} else {
schemaStoreUrl = JSON_SCHEMASTORE_URL;
Expand Down
7 changes: 4 additions & 3 deletions src/languageservice/services/yamlCompletion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,7 @@ export class YamlCompletion {
proposed,
};

if (this.customTags.length > 0) {
if (this.customTags && this.customTags.length > 0) {
this.getCustomTagValueCompletions(collector);
}

Expand Down Expand Up @@ -925,7 +925,8 @@ export class YamlCompletion {
if (propertySchema) {
this.addSchemaValueCompletions(propertySchema, separatorAfter, collector, types, 'value');
}
} else if (s.schema.additionalProperties) {
}
if (s.schema.additionalProperties) {
this.addSchemaValueCompletions(s.schema.additionalProperties, separatorAfter, collector, types, 'value');
}
}
Expand Down Expand Up @@ -1205,7 +1206,7 @@ export class YamlCompletion {
insertText = `\${${insertIndex++}:0}`;
break;
case 'string':
insertText = `\${${insertIndex++}:""}`;
insertText = `\${${insertIndex++}}`;
break;
case 'object':
{
Expand Down
115 changes: 75 additions & 40 deletions src/languageservice/services/yamlSelectionRanges.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,81 +3,72 @@ import { yamlDocumentsCache } from '../parser/yaml-documents';
import { TextDocument } from 'vscode-languageserver-textdocument';
import { ASTNode } from 'vscode-json-languageservice';

export function getSelectionRanges(document: TextDocument, positions: Position[]): SelectionRange[] | undefined {
if (!document) {
return;
}
export function getSelectionRanges(document: TextDocument, positions: Position[]): SelectionRange[] {
const doc = yamlDocumentsCache.getYamlDocument(document);
return positions.map((position) => {
const ranges = getRanges(position);
let current: SelectionRange;
let current: SelectionRange | undefined;
for (const range of ranges) {
current = SelectionRange.create(range, current);
}
if (!current) {
current = SelectionRange.create({
start: position,
end: position,
});
}
return current;
return current ?? SelectionRange.create({ start: position, end: position });
});

function getRanges(position: Position): Range[] {
const offset = document.offsetAt(position);
const result: Range[] = [];
for (const ymlDoc of doc.documents) {
let currentNode: ASTNode;
let firstNodeOffset: number;
let isFirstNode = true;
let currentNode: ASTNode | undefined;
let overrideStartOffset: number | undefined;
ymlDoc.visit((node) => {
const endOffset = node.offset + node.length;
// Skip if end offset doesn't even reach cursor position
if (endOffset < offset) {
return true;
}
let startOffset = node.offset;
// Recheck start offset with the trimmed one in case of this
// key:
// - value
// ↑
if (startOffset > offset) {
const nodePosition = document.positionAt(startOffset);
if (nodePosition.line !== position.line) {
return true;
}
const lineBeginning = { line: nodePosition.line, character: 0 };
const text = document.getText({
start: lineBeginning,
end: nodePosition,
});
if (text.trim().length !== 0) {
// Skip if we're ending at new line
// times:
// - second: 1
// millisecond: 10
// | - second: 2
// ↑ millisecond: 0
// (| is actually part of { second: 1, millisecond: 10 })
// \r\n doesn't matter here
if (getTextFromOffsets(endOffset - 1, endOffset) === '\n') {
if (endOffset - 1 < offset) {
return true;
}
startOffset = document.offsetAt(lineBeginning);
if (startOffset > offset) {
}

let startOffset = node.offset;
if (startOffset > offset) {
// Recheck start offset for some special cases
const newOffset = getStartOffsetForSpecialCases(node, position);
if (!newOffset || newOffset > offset) {
return true;
}
startOffset = newOffset;
}

// Allow equal for children to override
if (!currentNode || startOffset >= currentNode.offset) {
currentNode = node;
firstNodeOffset = startOffset;
overrideStartOffset = startOffset;
}
return true;
});
while (currentNode) {
const startOffset = isFirstNode ? firstNodeOffset : currentNode.offset;
const startOffset = overrideStartOffset ?? currentNode.offset;
const endOffset = currentNode.offset + currentNode.length;
const range = {
start: document.positionAt(startOffset),
end: document.positionAt(endOffset),
};
const text = document.getText(range);
const trimmedText = text.trimEnd();
const trimmedLength = text.length - trimmedText.length;
if (trimmedLength > 0) {
range.end = document.positionAt(endOffset - trimmedLength);
const trimmedText = trimEndNewLine(text);
const trimmedEndOffset = startOffset + trimmedText.length;
if (trimmedEndOffset >= offset) {
range.end = document.positionAt(trimmedEndOffset);
}
// Add a jump between '' "" {} []
const isSurroundedBy = (startCharacter: string, endCharacter?: string): boolean => {
Expand All @@ -95,7 +86,7 @@ export function getSelectionRanges(document: TextDocument, positions: Position[]
}
result.push(range);
currentNode = currentNode.parent;
isFirstNode = false;
overrideStartOffset = undefined;
}
// A position can't be in multiple documents
if (result.length > 0) {
Expand All @@ -104,4 +95,48 @@ export function getSelectionRanges(document: TextDocument, positions: Position[]
}
return result.reverse();
}

function getStartOffsetForSpecialCases(node: ASTNode, position: Position): number | undefined {
const nodeStartPosition = document.positionAt(node.offset);
if (nodeStartPosition.line !== position.line) {
return;
}

if (node.parent?.type === 'array') {
// array:
// - value
// ↑
if (getTextFromOffsets(node.offset - 2, node.offset) === '- ') {
return node.offset - 2;
}
}

if (node.type === 'array' || node.type === 'object') {
// array:
// - value
// ↑
const lineBeginning = { line: nodeStartPosition.line, character: 0 };
const text = document.getText({ start: lineBeginning, end: nodeStartPosition });
if (text.trim().length === 0) {
return document.offsetAt(lineBeginning);
}
}
}

function getTextFromOffsets(startOffset: number, endOffset: number): string {
return document.getText({
start: document.positionAt(startOffset),
end: document.positionAt(endOffset),
});
}
}

function trimEndNewLine(str: string): string {
if (str.endsWith('\r\n')) {
return str.substring(0, str.length - 2);
}
if (str.endsWith('\n')) {
return str.substring(0, str.length - 1);
}
return str;
}
2 changes: 1 addition & 1 deletion src/languageservice/yamlLanguageService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ export interface LanguageService {
deleteSchemaContent: (schemaDeletions: SchemaDeletions) => void;
deleteSchemasWhole: (schemaDeletions: SchemaDeletionsAll) => void;
getFoldingRanges: (document: TextDocument, context: FoldingRangesContext) => FoldingRange[] | null;
getSelectionRanges: (document: TextDocument, positions: Position[]) => SelectionRange[] | undefined;
getSelectionRanges: (document: TextDocument, positions: Position[]) => SelectionRange[];
getCodeAction: (document: TextDocument, params: CodeActionParams) => CodeAction[] | undefined;
getCodeLens: (document: TextDocument) => PromiseLike<CodeLens[] | undefined> | CodeLens[] | undefined;
resolveCodeLens: (param: CodeLens) => PromiseLike<CodeLens> | CodeLens;
Expand Down
7 changes: 6 additions & 1 deletion test/autoCompletion.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1047,7 +1047,7 @@ describe('Auto Completion Tests', () => {
const completion = parseSetup(content, content.lastIndexOf('Ba') + 2); // pos: 3+2
completion
.then(function (result) {
assert.strictEqual('fooBar:\n - ${1:""}', result.items[0].insertText);
assert.strictEqual('fooBar:\n - ${1}', result.items[0].insertText);
})
.then(done, done);
});
Expand Down Expand Up @@ -3126,5 +3126,10 @@ describe('Auto Completion Tests', () => {
expect(result.items.map((i) => i.label)).to.have.members(['fruit', 'vegetable']);
});
});
it('Should function when settings are undefined', async () => {
languageService.configure({ completion: true });
const content = '';
await parseSetup(content, 0);
});
});
});
26 changes: 25 additions & 1 deletion test/autoCompletionFix.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -482,7 +482,7 @@ objB:

expect(completion.items.length).equal(1);
expect(completion.items[0]).to.be.deep.equal(
createExpectedCompletion('objectWithArray', 'objectWithArray:\n - ${1:""}', 1, 4, 1, 4, 10, 2, {
createExpectedCompletion('objectWithArray', 'objectWithArray:\n - ${1}', 1, 4, 1, 4, 10, 2, {
documentation: '',
})
);
Expand Down Expand Up @@ -1183,6 +1183,30 @@ objB:
expect(completion.items[0].insertText).to.be.equal('test1');
});

it('should suggest defaultSnippets from additionalProperties', async () => {
const schema: JSONSchema = {
type: 'object',
properties: {
id: {
type: 'string',
},
},
additionalProperties: {
anyOf: [
{
type: 'string',
defaultSnippets: [{ label: 'snippet', body: 'snippetBody' }],
},
],
},
};
schemaProvider.addSchema(SCHEMA_ID, schema);
const content = 'value: |\n|';
const completion = await parseCaret(content);

expect(completion.items.map((i) => i.insertText)).to.be.deep.equal(['snippetBody']);
});

describe('should suggest prop of the object (based on not completed prop name)', () => {
const schema: JSONSchema = {
definitions: {
Expand Down
82 changes: 78 additions & 4 deletions test/yamlSelectionRanges.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,16 @@ function isRangesEqual(range1: Range, range2: Range): boolean {
);
}

function expectSelections(selectionRange: SelectionRange, ranges: Range[]): void {
function expectSelections(selectionRange: SelectionRange | undefined, ranges: Range[]): void {
for (const range of ranges) {
expect(selectionRange.range).eql(range);
expect(selectionRange?.range).eql(range);

// Deduplicate ranges
while (selectionRange.parent && isRangesEqual(selectionRange.range, selectionRange.parent.range)) {
while (selectionRange?.parent && isRangesEqual(selectionRange.range, selectionRange.parent.range)) {
selectionRange = selectionRange.parent;
}
selectionRange = selectionRange.parent;

selectionRange = selectionRange?.parent;
}
}

Expand Down Expand Up @@ -62,6 +64,20 @@ key:
{ start: { line: 1, character: 0 }, end: { line: 3, character: 8 } },
]);

positions = [
{
line: 3,
character: 3,
},
];
ranges = getSelectionRanges(document, positions);
expect(ranges.length).equal(positions.length);
expectSelections(ranges[0], [
{ start: { line: 3, character: 2 }, end: { line: 3, character: 8 } },
{ start: { line: 2, character: 2 }, end: { line: 3, character: 8 } },
{ start: { line: 1, character: 0 }, end: { line: 3, character: 8 } },
]);

positions = [
{
line: 2,
Expand All @@ -76,6 +92,64 @@ key:
]);
});

it('selection ranges for array of objects', () => {
const yaml = `
times:
- second: 1
millisecond: 10
- second: 2
millisecond: 0
`;
let positions: Position[] = [
{
line: 4,
character: 0,
},
];
const document = setupTextDocument(yaml);
let ranges = getSelectionRanges(document, positions);
expect(ranges.length).equal(positions.length);
expectSelections(ranges[0], [
{ start: { line: 2, character: 2 }, end: { line: 5, character: 18 } },
{ start: { line: 1, character: 0 }, end: { line: 5, character: 18 } },
]);

positions = [
{
line: 5,
character: 2,
},
];
ranges = getSelectionRanges(document, positions);
expect(ranges.length).equal(positions.length);
expectSelections(ranges[0], [
{ start: { line: 4, character: 4 }, end: { line: 5, character: 18 } },
{ start: { line: 2, character: 2 }, end: { line: 5, character: 18 } },
{ start: { line: 1, character: 0 }, end: { line: 5, character: 18 } },
]);
});

it('selection ranges for trailing spaces', () => {
const yaml = `
key:
- 1
- 2 \t
`;
const positions: Position[] = [
{
line: 2,
character: 9,
},
];
const document = setupTextDocument(yaml);
const ranges = getSelectionRanges(document, positions);
expect(ranges.length).equal(positions.length);
expectSelections(ranges[0], [
{ start: { line: 2, character: 2 }, end: { line: 3, character: 9 } },
{ start: { line: 1, character: 0 }, end: { line: 3, character: 9 } },
]);
});

it('selection ranges jump for "" \'\'', () => {
const yaml = `
- "word"
Expand Down
Loading

0 comments on commit a4a1add

Please sign in to comment.