import * as vscode from 'vscode' ; import * as path from 'path' ; import * as fs from 'fs' ; import * as yaml from 'js-yaml' ; import fuzzysearch = require ( 'fuzzysearch' ) ; export interface CodeSnippet { readonly name : string ; readonly label : string ; readonly description : string ; readonly body : string ; } /**
 * A kubernetes completion provider provides yaml code snippets for kubernetes, eg: service, deployment.
 */ export class KubernetesCompletionProvider implements vscode . CompletionItemProvider { private snippets : CodeSnippet [ ] = [ ] ; public constructor ( context ) { this . loadCodeSnippets ( context ) ; } public provideCompletionItems ( doc , pos ) { const wordPos = doc . getWordRangeAtPosition ( pos ) ; const word = doc . getText ( wordPos ) ; return this . filterCodeSnippets ( word ) . map ( ( snippet ) : vscode . CompletionItem => { const item = new vscode . CompletionItem ( snippet . label , vscode . CompletionItemKind . Snippet ) ; item . insertText = new vscode . SnippetString ( snippet . body ) ; item . documentation = snippet . description ; return item ; } ) ; } private loadCodeSnippets ( context ) { const snippetRoot = context . asAbsolutePath ( 'snippets' ) ; this . snippets = fs . readdirSync ( snippetRoot ) . filter ( ( filename ) : boolean => filename . endsWith ( '.yaml' ) ) . map ( ( filename ) : CodeSnippet => this . readYamlCodeSnippet ( path . join ( snippetRoot , filename ) ) ) ; } private filterCodeSnippets ( word ) { return this . snippets . filter ( ( snippet ) : boolean => fuzzysearch ( word . toLowerCase ( ) , snippet . name . toLowerCase ( ) ) ) ; } private readYamlCodeSnippet ( filename ) { return < CodeSnippet > yaml . safeLoad ( fs . readFileSync ( filename , 'utf-8' ) ) ; } }