diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 00000000..32b4467c --- /dev/null +++ b/.prettierignore @@ -0,0 +1,6 @@ +languages +snippets +syntaxes +out +vendor +package-lock.json diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 00000000..3fb240e0 --- /dev/null +++ b/.prettierrc @@ -0,0 +1,9 @@ +{ + "singleQuote": true, + "tabWidth": 2, + "endOfLine": "lf", + "printWidth": 120, + "useTabs": false, + "trailingComma": "all", + "semi": true, +} diff --git a/.vscode/extensions.json b/.vscode/extensions.json index f48fe078..e6bab840 100644 --- a/.vscode/extensions.json +++ b/.vscode/extensions.json @@ -1,6 +1,7 @@ { "recommendations": [ "eamodio.gitlens", + "esbenp.prettier-vscode", "ms-vscode.vscode-typescript-tslint-plugin", "wwm.better-align", "rebornix.Ruby" diff --git a/.vscode/launch.json b/.vscode/launch.json index 9f543d39..270a8a67 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -10,12 +10,8 @@ "type": "extensionHost", "request": "launch", "runtimeExecutable": "${execPath}", - "args": [ - "--extensionDevelopmentPath=${workspaceFolder}" - ], - "outFiles": [ - "${workspaceFolder}/out/**/*.js" - ], + "args": ["--extensionDevelopmentPath=${workspaceFolder}"], + "outFiles": ["${workspaceFolder}/out/**/*.js"], "preLaunchTask": "npm: watch" }, { @@ -27,9 +23,7 @@ "--extensionDevelopmentPath=${workspaceFolder}", "--extensionTestsPath=${workspaceFolder}/out/test/suite/index" ], - "outFiles": [ - "${workspaceFolder}/out/test/**/*.js" - ], + "outFiles": ["${workspaceFolder}/out/test/**/*.js"], "preLaunchTask": "npm: watch" }, { @@ -38,8 +32,8 @@ "name": "DebugAdapter", "cwd": "${workspaceFolder}", "program": "${workspaceFolder}/src/debugAdapter.ts", - "args": [ "--server=4711" ], - "outFiles": [ "${workspaceFolder}/out/**/*.js" ] + "args": ["--server=4711"], + "outFiles": ["${workspaceFolder}/out/**/*.js"] }, { "type": "node", @@ -56,7 +50,7 @@ "compounds": [ { "name": "Extension + DebugAdapter", - "configurations": [ "Extension", "DebugAdapter" ] + "configurations": ["Extension", "DebugAdapter"] } ] } diff --git a/.vscode/settings.json b/.vscode/settings.json index dc9dd85e..9f4c3bce 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,29 +1,31 @@ // Place your settings in this file to overwrite default and user settings. { - "editor.insertSpaces": true, - "editor.tabSize": 2, - "editor.trimAutoWhitespace": true, - - "files.encoding": "utf8", - // The default end of line character. Use \n for LF and \r\n for CRLF. - "files.eol": "\n", - "files.insertFinalNewline": true, - "files.trimFinalNewlines": true, - "files.trimTrailingWhitespace": false, - "files.exclude": { - "node_modules": true, - "out": true, // set this to true to hide the "out" folder with the compiled JS files - ".vscode-test": true - }, - "search.exclude": { - "node_modules": true, - "out": true // set this to false to include "out" folder in search results - }, - - "prettier.printWidth": 120, - "prettier.singleQuote": true, - "prettier.tabWidth": 2, + "editor.insertSpaces": true, + "editor.tabSize": 2, + "editor.trimAutoWhitespace": true, - // Turn off tsc task auto detection since we have the necessary tasks as npm scripts - "typescript.tsc.autoDetect": "off" + "files.encoding": "utf8", + // The default end of line character. Use \n for LF and \r\n for CRLF. + "files.eol": "\n", + "files.insertFinalNewline": true, + "files.trimFinalNewlines": true, + "files.trimTrailingWhitespace": false, + "files.exclude": { + "node_modules": true, + "out": true, // set this to true to hide the "out" folder with the compiled JS files + ".vscode-test": true + }, + "search.exclude": { + "node_modules": true, + "out": true // set this to false to include "out" folder in search results + }, + + // Turn off tsc task auto detection since we have the necessary tasks as npm scripts + "typescript.tsc.autoDetect": "off", + "typescript.format.enable": false, + "[typescript]": { + "editor.formatOnSave": true, + "editor.formatOnType": true, + "editor.defaultFormatter": "esbenp.prettier-vscode" } +} diff --git a/CHANGELOG.md b/CHANGELOG.md index bdcacac2..0bd2e0c5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ Check [Keep a Changelog](http://keepachangelog.com/) for recommendations on how - ([GH-649](https://github.com/puppetlabs/puppet-vscode/issues/649)) Reduce activation events for extension - ([GH-639](https://github.com/puppetlabs/puppet-vscode/issues/639)) Deprecate Bolt Commands +- ([GH-643](https://github.com/puppetlabs/puppet-vscode/issues/643)) Enable, configure and run prettier ## [0.26.1] - 2020-05-12 diff --git a/assets/js/main.js b/assets/js/main.js index e83f4aa7..ba5fbe4b 100644 --- a/assets/js/main.js +++ b/assets/js/main.js @@ -10,15 +10,15 @@ function generate_cy_stylesheet(cy) { { selector: 'node', style: { - label: "data(id)", - shape: "round-rectangle", - "background-color": html_style.getPropertyValue('--vscode-button-background'), - "background-width": "90%", - "background-height": "90%", - width: "228", - height: "128", - "border-width": "0", - } + label: 'data(id)', + shape: 'round-rectangle', + 'background-color': html_style.getPropertyValue('--vscode-button-background'), + 'background-width': '90%', + 'background-height': '90%', + width: '228', + height: '128', + 'border-width': '0', + }, }, { selector: 'label', @@ -27,8 +27,8 @@ function generate_cy_stylesheet(cy) { 'font-family': '"Segoe UI", Arial, Helvetica, sans-serif', 'font-size': '28vh', 'text-valign': 'center', - 'text-halign': 'center' - } + 'text-halign': 'center', + }, }, { selector: ':selected', @@ -38,8 +38,8 @@ function generate_cy_stylesheet(cy) { 'background-color': html_style.getPropertyValue('--vscode-button-hoverBackground'), 'line-color': html_style.getPropertyValue('--vscode-minimap-errorHighlight'), 'target-arrow-color': html_style.getPropertyValue('--vscode-minimap-errorHighlight'), - 'source-arrow-color': html_style.getPropertyValue('--vscode-minimap-errorHighlight') - } + 'source-arrow-color': html_style.getPropertyValue('--vscode-minimap-errorHighlight'), + }, }, { selector: 'edge', @@ -47,9 +47,9 @@ function generate_cy_stylesheet(cy) { 'target-arrow-shape': 'triangle', 'curve-style': 'bezier', 'control-point-step-size': 40, - width: 10 - } - } + width: 10, + }, + }, ]) .update(); // indicate the end of your new stylesheet so that it can be updated on elements } @@ -62,7 +62,7 @@ function init() { wheelSensitivity: 0.15, maxZoom: 5, minZoom: 0.2, - selectionType: 'single' + selectionType: 'single', }); generate_cy_stylesheet(cy); @@ -70,34 +70,34 @@ function init() { vscode.postMessage({ command: 'initialized' }); } -window.addEventListener('message', event => { +window.addEventListener('message', (event) => { const message = event.data; - if(message.redraw == true){ + if (message.redraw == true) { cy.remove('*'); } nodeGraph = message.content; - try { - nodeGraph.vertices.forEach(element => { + try { + nodeGraph.vertices.forEach((element) => { cy.add({ - data: { id: element.label } + data: { id: element.label }, }); }); - nodeGraph.edges.forEach(element => { + nodeGraph.edges.forEach((element) => { cy.add({ data: { id: element.source + element.target, source: element.source, - target: element.target - } + target: element.target, + }, }); }); } catch (error) { vscode.postMessage({ command: 'error', - errorMsg: `Error building node graph from json graph data: ${error}` + errorMsg: `Error building node graph from json graph data: ${error}`, }); } @@ -107,6 +107,6 @@ window.addEventListener('message', event => { circle: false, nodeDimensionsIncludeLabels: true, spacingFactor: 1.5, - animate: true + animate: true, }).run(); }); diff --git a/package.json b/package.json index 4df683bb..053a9f97 100644 --- a/package.json +++ b/package.json @@ -551,7 +551,8 @@ "build": "pwsh -file ./build.ps1", "watch": "npm run build && tsc -watch -p ./", "pretest": "npm run compile", - "test": "node ./out/test/runtest.js" + "test": "node ./out/test/runtest.js", + "format": "prettier --write '**/**/*.{ts,js,json}'" }, "devDependencies": { "@types/glob": "^7.1.1", diff --git a/snippets/puppetfile.snippets.json b/snippets/puppetfile.snippets.json index a6b96ebe..8d4a382b 100644 --- a/snippets/puppetfile.snippets.json +++ b/snippets/puppetfile.snippets.json @@ -1,12 +1,16 @@ { "Forge_module1": { "prefix": "Forge Module", - "body": ["mod '${1:author}-${2:name}', '${3:version}'"], + "body": [ + "mod '${1:author}-${2:name}', '${3:version}'" + ], "description": "Install from the forge" }, "Forge_module2": { "prefix": "Latest Forge Module", - "body": ["mod '${1:author}-${2:name}', :latest"], + "body": [ + "mod '${1:author}-${2:name}', :latest" + ], "description": "Install the latest version from the forge" }, "Git_module1": { @@ -46,7 +50,9 @@ }, "Local_module1": { "prefix": "Local Module", - "body": ["mod '${1:name}', :local => true"], + "body": [ + "mod '${1:name}', :local => true" + ], "description": "Install from the local Puppetfile module path" } } diff --git a/src/configuration.ts b/src/configuration.ts index ed5e46a0..9eafe510 100644 --- a/src/configuration.ts +++ b/src/configuration.ts @@ -8,7 +8,7 @@ import { ISettings, ConnectionType, ProtocolType, PuppetInstallType } from './se import * as pdk from './configuration/pdkResolver'; /** Creates an Aggregate Configuration based on the VSCode Workspace settings (ISettings) */ -export function CreateAggregrateConfiguration(settings:ISettings): IAggregateConfiguration { +export function CreateAggregrateConfiguration(settings: ISettings): IAggregateConfiguration { const value = new AggregateConfiguration(settings); return value; @@ -27,15 +27,15 @@ interface IRubyConfiguration { readonly sslCertFile: string; readonly sslCertDir: string; - readonly pdkBinDir:string; - readonly pdkRubyLib:string; - readonly pdkRubyVerDir:string; - readonly pdkGemDir:string; - readonly pdkRubyDir:string; - readonly pdkRubyBinDir:string; - readonly pdkGemVerDir:string; + readonly pdkBinDir: string; + readonly pdkRubyLib: string; + readonly pdkRubyVerDir: string; + readonly pdkGemDir: string; + readonly pdkRubyDir: string; + readonly pdkRubyBinDir: string; + readonly pdkGemVerDir: string; readonly pdkPuppetVersions: string[]; - readonly pdkVersion:string; + readonly pdkVersion: string; } /** The IConnectionConfiguration interface describes the connection used to @@ -61,7 +61,7 @@ export class AggregateConfiguration implements IAggregateConfiguration { public ruby: IRubyConfiguration; public connection: IConnectionConfiguration; - constructor(settings:ISettings) { + constructor(settings: ISettings) { this.workspace = settings; // If the user has set the installType to 'auto' then we need @@ -69,7 +69,7 @@ export class AggregateConfiguration implements IAggregateConfiguration { if (settings.installType === PuppetInstallType.AUTO) { if (fs.existsSync(this.getPdkBasePath())) { settings.installType = PuppetInstallType.PDK; - } else if(fs.existsSync(this.getAgentBasePath())) { + } else if (fs.existsSync(this.getAgentBasePath())) { settings.installType = PuppetInstallType.PUPPET; } else { // We can't automatically figure it out so, assume PDK @@ -88,15 +88,23 @@ export class AggregateConfiguration implements IAggregateConfiguration { if (settings.installType === PuppetInstallType.PDK) { const pdkInfo = pdk.pdkInstances(puppetBaseDir); let result: pdk.IPDKRubyInstance; - if (settings.editorService !== undefined && settings.editorService.puppet !== undefined && settings.editorService.puppet.version !== undefined) { + if ( + settings.editorService !== undefined && + settings.editorService.puppet !== undefined && + settings.editorService.puppet.version !== undefined + ) { result = pdkInfo.InstanceForPuppetVersion(settings.editorService.puppet.version); } // If we can't find the PDK instance from the puppet version or it wasn't defined, assume the latest. - if (result === undefined) { result = pdkInfo.latest; } + if (result === undefined) { + result = pdkInfo.latest; + } // An undefined instance means that either PDK isn't installed or that // the requested version doesn't exist. - if (result !== undefined) { pdkInstance = result; } + if (result !== undefined) { + pdkInstance = result; + } puppetVersions = pdkInfo.allPuppetVersions; } @@ -123,7 +131,10 @@ export class AggregateConfiguration implements IAggregateConfiguration { this.connection = { type: this.calculateConnectionType(settings), - protocol: (settings.editorService !== undefined && settings.editorService.protocol === ProtocolType.TCP) ? ProtocolType.TCP : ProtocolType.STDIO + protocol: + settings.editorService !== undefined && settings.editorService.protocol === ProtocolType.TCP + ? ProtocolType.TCP + : ProtocolType.STDIO, }; } @@ -131,18 +142,26 @@ export class AggregateConfiguration implements IAggregateConfiguration { let foundUndefined: Boolean = false; // path.join makes sure that no elements are 'undefined' and throws if there is. Instead // we can search for it and just return undefined ourself. - paths.forEach( (item) => { foundUndefined = foundUndefined || (item === undefined); }); - if (foundUndefined) { return undefined; } + paths.forEach((item) => { + foundUndefined = foundUndefined || item === undefined; + }); + if (foundUndefined) { + return undefined; + } return path.join(...paths); } - private calculateConnectionType(settings:ISettings): ConnectionType { - if (settings.editorService === undefined) { return undefined; } + private calculateConnectionType(settings: ISettings): ConnectionType { + if (settings.editorService === undefined) { + return undefined; + } switch (settings.editorService.protocol) { case ProtocolType.TCP: - if (settings.editorService.tcp.address === '127.0.0.1' || - settings.editorService.tcp.address === 'localhost' || - settings.editorService.tcp.address === '') { + if ( + settings.editorService.tcp.address === '127.0.0.1' || + settings.editorService.tcp.address === 'localhost' || + settings.editorService.tcp.address === '' + ) { return ConnectionType.Local; } else { return ConnectionType.Remote; @@ -158,10 +177,10 @@ export class AggregateConfiguration implements IAggregateConfiguration { // PATH=%PUPPET_DIR%\bin;%FACTERDIR%\bin;%HIERA_DIR%\bin;%PL_BASEDIR%\bin;%RUBY_DIR%\bin;%PL_BASEDIR%\sys\tools\bin;%PATH% private calculateEnvironmentPath( - puppetDir:string, - facterDir:string, - puppetBaseDir:string, - rubydir:string + puppetDir: string, + facterDir: string, + puppetBaseDir: string, + rubydir: string, ): string { return new Array( path.join(puppetDir, 'bin'), @@ -169,20 +188,22 @@ export class AggregateConfiguration implements IAggregateConfiguration { // path.join(hieraDir, 'bin'), path.join(puppetBaseDir, 'bin'), path.join(rubydir, 'bin'), - path.join(puppetBaseDir, 'sys', 'tools', 'bin') + path.join(puppetBaseDir, 'sys', 'tools', 'bin'), ).join(PathResolver.pathEnvSeparator()); } // RUBYLIB=%PUPPET_DIR%\lib;%FACTERDIR%\lib;%HIERA_DIR%\lib;%RUBYLIB% - private calculateRubylib(puppetDir:string, facterDir:string): string { - return this.replaceSlashes(new Array( - path.join(puppetDir, 'lib'), - path.join(facterDir, 'lib'), - // path.join(this.hieraDir, 'lib'), - ).join(PathResolver.pathEnvSeparator())); + private calculateRubylib(puppetDir: string, facterDir: string): string { + return this.replaceSlashes( + new Array( + path.join(puppetDir, 'lib'), + path.join(facterDir, 'lib'), + // path.join(this.hieraDir, 'lib'), + ).join(PathResolver.pathEnvSeparator()), + ); } - - private calculateRubyDir(puppetBaseDir:string): string { + + private calculateRubyDir(puppetBaseDir: string): string { switch (process.platform) { case 'win32': return path.join(puppetBaseDir, 'sys', 'ruby'); @@ -191,8 +212,12 @@ export class AggregateConfiguration implements IAggregateConfiguration { } } - private calculatePuppetBaseDir(settings:ISettings): string { - if ( (settings.installDirectory !== null) && (settings.installDirectory !== undefined) && (settings.installDirectory.trim() !== "") ) { + private calculatePuppetBaseDir(settings: ISettings): string { + if ( + settings.installDirectory !== null && + settings.installDirectory !== undefined && + settings.installDirectory.trim() !== '' + ) { return settings.installDirectory; } @@ -210,11 +235,11 @@ export class AggregateConfiguration implements IAggregateConfiguration { let programFiles = PathResolver.getprogramFiles(); switch (process.platform) { case 'win32': - // On Windows we have a subfolder called 'Puppet' that has - // every product underneath + // On Windows we have a subfolder called 'Puppet' that has + // every product underneath return path.join(programFiles, 'Puppet Labs', 'Puppet'); default: - // On *nix we don't have a sub folder called 'Puppet' + // On *nix we don't have a sub folder called 'Puppet' return path.join(programFiles, 'puppetlabs'); } } @@ -229,25 +254,29 @@ export class AggregateConfiguration implements IAggregateConfiguration { } } - private getPdkVersionFromFile(puppetBaseDir:string){ + private getPdkVersionFromFile(puppetBaseDir: string) { let basePath = path.join(puppetBaseDir, 'PDK_VERSION'); - if(fs.existsSync(basePath)){ + if (fs.existsSync(basePath)) { let contents = fs.readFileSync(basePath, 'utf8').toString(); return contents.trim(); - }else{ + } else { return ''; } } private findFirstDirectory(rootDir: string): string { - if (!fs.existsSync(rootDir)) { return undefined; } + if (!fs.existsSync(rootDir)) { + return undefined; + } var files = fs.readdirSync(rootDir); - let result = files.sort( (a, b) => a.localeCompare(b, undefined, { numeric:true }) ).reverse()[0]; + let result = files.sort((a, b) => a.localeCompare(b, undefined, { numeric: true })).reverse()[0]; return path.join(rootDir, result); } private replaceSlashes(path: string): string { - if (path === undefined) { return path; } + if (path === undefined) { + return path; + } if (process.platform === 'win32') { // Translate all slashes to / style to avoid puppet/ruby issue #11930 path = path.replace(/\\/g, '/'); diff --git a/src/configuration/pathResolver.ts b/src/configuration/pathResolver.ts index c6c3eb0f..66f43ec9 100644 --- a/src/configuration/pathResolver.ts +++ b/src/configuration/pathResolver.ts @@ -2,7 +2,6 @@ import * as path from 'path'; import * as fs from 'fs'; export class PathResolver { - public static getprogramFiles(): string { switch (process.platform) { case 'win32': @@ -42,5 +41,4 @@ export class PathResolver { return ':'; } } - } diff --git a/src/configuration/pdkResolver.ts b/src/configuration/pdkResolver.ts index cb0a31c2..7433d4a2 100644 --- a/src/configuration/pdkResolver.ts +++ b/src/configuration/pdkResolver.ts @@ -52,14 +52,14 @@ export function pdkInstances(pdkRootDirectory: string): IPDKRubyInstances { export function emptyPDKInstance(): IPDKRubyInstance { return { - 'rubyVerDir': undefined, - 'rubyDir': undefined, - 'rubyBinDir': undefined, - 'gemVerDir': undefined, - 'gemDir': undefined, - 'puppetVersions': undefined, - 'rubyVersion': undefined, - 'valid': false + rubyVerDir: undefined, + rubyDir: undefined, + rubyBinDir: undefined, + gemVerDir: undefined, + gemDir: undefined, + puppetVersions: undefined, + rubyVersion: undefined, + valid: false, }; } @@ -68,65 +68,77 @@ class PDKRubyInstances implements IPDKRubyInstances { private rubyInstances: IPDKRubyInstance[] = undefined; private puppetVersions: string[] = undefined; - constructor( - pdkRootDirectory: string - ) { + constructor(pdkRootDirectory: string) { this.pdkDirectory = pdkRootDirectory; } get instances(): IPDKRubyInstance[] { - if (this.rubyInstances !== undefined) { return this.rubyInstances; } + if (this.rubyInstances !== undefined) { + return this.rubyInstances; + } this.rubyInstances = new Array(); - if (this.pdkDirectory === undefined) { return this.rubyInstances; } - if (!fs.existsSync(this.pdkDirectory)) { return this.rubyInstances; } + if (this.pdkDirectory === undefined) { + return this.rubyInstances; + } + if (!fs.existsSync(this.pdkDirectory)) { + return this.rubyInstances; + } var rubyDir = path.join(this.pdkDirectory, 'private', 'ruby'); - if (!fs.existsSync(rubyDir)) { return this.rubyInstances; } + if (!fs.existsSync(rubyDir)) { + return this.rubyInstances; + } - fs.readdirSync(rubyDir).forEach( (item) => { - this.rubyInstances.push(new PDKRubyInstance( - this.pdkDirectory, - path.join(rubyDir, item) - )); + fs.readdirSync(rubyDir).forEach((item) => { + this.rubyInstances.push(new PDKRubyInstance(this.pdkDirectory, path.join(rubyDir, item))); }); return this.rubyInstances; } get allPuppetVersions(): string[] { - if (this.puppetVersions !== undefined) { return this.puppetVersions; } + if (this.puppetVersions !== undefined) { + return this.puppetVersions; + } this.puppetVersions = []; // This searching method isn't the most performant but as the list will probably // be very small (< 20 items) it's not a big deal and is cached anyway - this.instances.forEach( (instance) => { - instance.puppetVersions.forEach ( (puppetVersion) => { - if (this.puppetVersions.indexOf(puppetVersion) === -1) { this.puppetVersions.push(puppetVersion); } + this.instances.forEach((instance) => { + instance.puppetVersions.forEach((puppetVersion) => { + if (this.puppetVersions.indexOf(puppetVersion) === -1) { + this.puppetVersions.push(puppetVersion); + } }); }); return this.puppetVersions; } public InstanceForPuppetVersion(puppetVersion: string): IPDKRubyInstance { - return this.instances.find( (instance) => { + return this.instances.find((instance) => { return instance.puppetVersions.includes(puppetVersion); }); } // Override toString to make it look pretty toString(): string { - return "[" + - this.instances.map( (item) => { - return item.toString(); - }).join(", ") + "]"; + return ( + '[' + + this.instances + .map((item) => { + return item.toString(); + }) + .join(', ') + + ']' + ); } get latest(): IPDKRubyInstance { let result = undefined; - let lastVersion = "0.0.0"; + let lastVersion = '0.0.0'; - this.instances.forEach( (instance) => { + this.instances.forEach((instance) => { // We don't have a real semver module so treat the strings as numbers and sort. - if (instance.rubyVersion.localeCompare(lastVersion,undefined, { numeric:true }) > 0) { + if (instance.rubyVersion.localeCompare(lastVersion, undefined, { numeric: true }) > 0) { result = instance; lastVersion = instance.rubyVersion; } @@ -148,37 +160,58 @@ class PDKRubyInstance implements IPDKRubyInstance { private _valid: boolean = undefined; // Directory Paths - get rubyVerDir():string { return this._rubyVerDir; } - get rubyDir():string { return this._rubyDir; } - get rubyBinDir():string { return this._rubyBinDir; } - get gemVerDir():string { return this._gemVerDir; } - get gemDir():string { return this._gemDir; } + get rubyVerDir(): string { + return this._rubyVerDir; + } + get rubyDir(): string { + return this._rubyDir; + } + get rubyBinDir(): string { + return this._rubyBinDir; + } + get gemVerDir(): string { + return this._gemVerDir; + } + get gemDir(): string { + return this._gemDir; + } - get rubyVersion():string { return this._rubyVersion; } + get rubyVersion(): string { + return this._rubyVersion; + } - get valid():boolean { - if (this._valid !== undefined) { return this._valid; } + get valid(): boolean { + if (this._valid !== undefined) { + return this._valid; + } // This instance is valid if these directories exist - this._valid = fs.existsSync(this._rubyDir) && - fs.existsSync(this._rubyBinDir) && - fs.existsSync(this._rubyVerDir) && - fs.existsSync(this._gemVerDir) && - fs.existsSync(this._gemDir); + this._valid = + fs.existsSync(this._rubyDir) && + fs.existsSync(this._rubyBinDir) && + fs.existsSync(this._rubyVerDir) && + fs.existsSync(this._gemVerDir) && + fs.existsSync(this._gemDir); return this._valid; } - get puppetVersions():string[] { - if (this._puppetVersions !== undefined) { return this._puppetVersions; } + get puppetVersions(): string[] { + if (this._puppetVersions !== undefined) { + return this._puppetVersions; + } this._puppetVersions = []; let gemdir = path.join(this._rubyVerDir, 'gems'); - if (!fs.existsSync(gemdir)) { return this._puppetVersions; } + if (!fs.existsSync(gemdir)) { + return this._puppetVersions; + } // We could just call Ruby and ask it for all gems called puppet, but searching // the gem cache is just as easy and doesn't need to spawn a ruby process per // ruby version. - fs.readdirSync(gemdir).forEach( (item) => { + fs.readdirSync(gemdir).forEach((item) => { let pathMatch = item.match(/^puppet-(\d+\.\d+\.\d+)(?:(-|$))/); - if (pathMatch !== null) { this._puppetVersions.push(pathMatch[1]); } + if (pathMatch !== null) { + this._puppetVersions.push(pathMatch[1]); + } }); return this._puppetVersions; @@ -186,20 +219,23 @@ class PDKRubyInstance implements IPDKRubyInstance { // Override toString to make it look pretty toString(): string { - return "{" + - [`rubyVersion: \"${this._rubyVersion}\"`, - `rubyDir: \"${this._rubyDir}\"`, - `rubyVerDir: \"${this.rubyVerDir}\"`, - `gemVerDir: \"${this.gemVerDir}\"`, - `gemDir: \"${this.gemDir}\"`, - `gemDir: \"${this.gemDir}\"`, - `puppetVersions: \"${this.puppetVersions}\"`, - `valid: \"${this.valid}\"` - ].join(", ") + - "}"; - } - - constructor(pdkDirectory: string, rubyDir:string) { + return ( + '{' + + [ + `rubyVersion: \"${this._rubyVersion}\"`, + `rubyDir: \"${this._rubyDir}\"`, + `rubyVerDir: \"${this.rubyVerDir}\"`, + `gemVerDir: \"${this.gemVerDir}\"`, + `gemDir: \"${this.gemDir}\"`, + `gemDir: \"${this.gemDir}\"`, + `puppetVersions: \"${this.puppetVersions}\"`, + `valid: \"${this.valid}\"`, + ].join(', ') + + '}' + ); + } + + constructor(pdkDirectory: string, rubyDir: string) { this._rubyDir = rubyDir; this._rubyBinDir = path.join(rubyDir, 'bin'); this._rubyVersion = path.basename(rubyDir); diff --git a/src/extension.ts b/src/extension.ts index d9539cb6..54c7a857 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -37,12 +37,10 @@ let extensionFeatures: IFeature[] = []; export function activate(context: vscode.ExtensionContext) { let pkg = vscode.extensions.getExtension('jpogran.puppet-vscode'); - if (pkg){ - let message = 'The "jpogran.puppet-vscode" extension has been detected, which will conflict with the "puppet.puppet-vscode" extension. This will cause problems activating when each extension tries to load at the same time and may cause errors. Please uninstall it by executing the following from the commandline: "code --uninstall-extension jpogran.puppet-vscode"'; - vscode.window.showWarningMessage( - message, - { modal: false }, - ); + if (pkg) { + let message = + 'The "jpogran.puppet-vscode" extension has been detected, which will conflict with the "puppet.puppet-vscode" extension. This will cause problems activating when each extension tries to load at the same time and may cause errors. Please uninstall it by executing the following from the commandline: "code --uninstall-extension jpogran.puppet-vscode"'; + vscode.window.showWarningMessage(message, { modal: false }); } extContext = context; @@ -59,14 +57,14 @@ export function activate(context: vscode.ExtensionContext) { logger = new OutputChannelLogger(configSettings.workspace.editorService.loglevel); if (configSettings.workspace.installType !== previousInstallType) { logger.debug( - `Installation type has changed from ${previousInstallType} to ${configSettings.workspace.installType}` + `Installation type has changed from ${previousInstallType} to ${configSettings.workspace.installType}`, ); } reporter.sendTelemetryEvent('config', { installType: configSettings.workspace.installType, protocol: configSettings.workspace.editorService.protocol, - pdkVersion: configSettings.ruby.pdkVersion + pdkVersion: configSettings.ruby.pdkVersion, }); const statusBar = new PuppetStatusBarFeature([puppetLangID, puppetFileLangID], configSettings, logger, context); @@ -75,7 +73,7 @@ export function activate(context: vscode.ExtensionContext) { new PDKFeature(extContext, logger), new BoltFeature(extContext), new UpdateConfigurationFeature(logger, extContext), - statusBar + statusBar, ]; if (configSettings.workspace.editorService.enable === false) { @@ -108,7 +106,7 @@ export function activate(context: vscode.ExtensionContext) { } extensionFeatures.push( - new FormatDocumentFeature(puppetLangID, connectionHandler, configSettings, logger, extContext) + new FormatDocumentFeature(puppetLangID, connectionHandler, configSettings, logger, extContext), ); extensionFeatures.push(new PuppetNodeGraphFeature(puppetLangID, connectionHandler, logger, extContext)); extensionFeatures.push(new PuppetResourceFeature(extContext, connectionHandler, logger)); @@ -120,12 +118,11 @@ export function activate(context: vscode.ExtensionContext) { let facts = new PuppetFactsProvider(connectionHandler); vscode.window.registerTreeDataProvider('puppetFacts', facts); - } export function deactivate() { // Dispose all extension features - extensionFeatures.forEach(feature => { + extensionFeatures.forEach((feature) => { feature.dispose(); }); @@ -147,7 +144,7 @@ function checkForLegacySettings() { 'Deprecated Puppet settings have been detected. Please either remove them or, convert them to the correct settings names. (' + settingNames.join(', ') + ')', - { modal: false } + { modal: false }, ); } } @@ -168,7 +165,7 @@ function checkInstallDirectory(config: IAggregateConfiguration, logger: ILogger) if (SettingsFromWorkspace().installType === PuppetInstallType.AUTO) { let m = [ 'The extension failed to find a Puppet installation automatically in the default locations for PDK and for Puppet Agent.', - 'While syntax highlighting and grammar detection will still work, intellisense and other advanced features will not.' + 'While syntax highlighting and grammar detection will still work, intellisense and other advanced features will not.', ]; message = m.join(' '); } else { @@ -179,7 +176,7 @@ function checkInstallDirectory(config: IAggregateConfiguration, logger: ILogger) message, 'Troubleshooting Information', 'https://puppet-vscode.github.io/docs/experience-a-problem', - logger + logger, ); return false; } else { @@ -190,7 +187,7 @@ function checkInstallDirectory(config: IAggregateConfiguration, logger: ILogger) function showErrorMessage(message: string, title: string, helpLink: string, logger: ILogger) { logger.error(message); - vscode.window.showErrorMessage(message, { modal: false }, { title: title }).then(item => { + vscode.window.showErrorMessage(message, { modal: false }, { title: title }).then((item) => { if (item === undefined) { return; } @@ -216,7 +213,7 @@ async function notifyOnNewExtensionVersion(context: vscode.ExtensionContext) { `Puppet VSCode has been updated to v${version}`, { modal: false }, { title: dontShowAgainNotice }, - { title: viewReleaseNotes } + { title: viewReleaseNotes }, ); if (result === undefined) { @@ -226,7 +223,7 @@ async function notifyOnNewExtensionVersion(context: vscode.ExtensionContext) { if (result.title === viewReleaseNotes) { vscode.commands.executeCommand( 'vscode.open', - vscode.Uri.parse('https://marketplace.visualstudio.com/items/puppet.puppet-vscode/changelog') + vscode.Uri.parse('https://marketplace.visualstudio.com/items/puppet.puppet-vscode/changelog'), ); } else { context.globalState.update(suppressUpdateNotice, true); @@ -244,7 +241,7 @@ async function notifyEditorServiceDisabled(context: vscode.ExtensionContext) { const result = await vscode.window.showInformationMessage( `Puppet Editor Services has been disabled. While syntax highlighting and grammar detection will still work, intellisense and other advanced features will not.`, { modal: false }, - { title: dontShowAgainNotice } + { title: dontShowAgainNotice }, ); if (result === undefined) { @@ -277,20 +274,20 @@ async function notifyIfNewPDKVersion(context: vscode.ExtensionContext, settings: axios .get('https://s3.amazonaws.com/puppet-pdk/pdk/LATEST') - .then(response => { + .then((response) => { return response.data; }) - .then(latest_version => { + .then((latest_version) => { if (version !== latest_version) { return vscode.window.showWarningMessage( `The installed PDK version is ${version}, the newest version is ${latest_version}. To find out how to update to the latest version click the more info button`, { modal: false }, { title: dontCheckAgainNotice }, - { title: viewPDKDownloadPage } + { title: viewPDKDownloadPage }, ); } }) - .then(result => { + .then((result) => { if (result === undefined) { return; } @@ -302,11 +299,11 @@ async function notifyIfNewPDKVersion(context: vscode.ExtensionContext, settings: if (result.title === viewPDKDownloadPage) { vscode.commands.executeCommand( 'vscode.open', - vscode.Uri.parse('https://puppet.com/download-puppet-development-kit') + vscode.Uri.parse('https://puppet.com/download-puppet-development-kit'), ); } }) - .catch(error => { + .catch((error) => { logger.error(error); }); } @@ -319,30 +316,30 @@ function setLanguageConfiguration() { beforeText: /^.*{\s{0,}'.*':/, afterText: /\s{0,}}$/, action: { - indentAction: vscode.IndentAction.IndentOutdent - } - } + indentAction: vscode.IndentAction.IndentOutdent, + }, + }, ], brackets: [ ['{', '}'], ['[', ']'], - ['(', ')'] + ['(', ')'], ], comments: { lineComment: '#', - blockComment: ['/*', '*/'] - } + blockComment: ['/*', '*/'], + }, }); vscode.languages.setLanguageConfiguration(puppetFileLangID, { onEnterRules: [], brackets: [ ['{', '}'], ['[', ']'], - ['(', ')'] + ['(', ')'], ], comments: { lineComment: '#', - blockComment: ['/*', '*/'] - } + blockComment: ['/*', '*/'], + }, }); } diff --git a/src/feature.ts b/src/feature.ts index c0a52241..4bac37db 100644 --- a/src/feature.ts +++ b/src/feature.ts @@ -1,5 +1,5 @@ -import vscode = require("vscode"); +import vscode = require('vscode'); export interface IFeature extends vscode.Disposable { - dispose(); + dispose(); } diff --git a/src/feature/BoltFeature.ts b/src/feature/BoltFeature.ts index d2c9ab1e..0215c63d 100644 --- a/src/feature/BoltFeature.ts +++ b/src/feature/BoltFeature.ts @@ -5,28 +5,23 @@ import * as fs from 'fs'; import { reporter } from '../telemetry'; export class BoltFeature implements IFeature { - dispose() { } + dispose() {} - showDeprecation(){ - let message = 'The "Open Bolt User Configuration File" and "Open Bolt User Inventory File" commands will be removed in a future release. Do you think they should be kept? Think there are other ways for this extension to help using Puppet Bolt? Let us know by clicking "Feedback" to add a comment to Github Issue #639'; - window.showWarningMessage(message, - { modal: false }, - { title: 'Feedback' } - ).then(result => { + showDeprecation() { + let message = + 'The "Open Bolt User Configuration File" and "Open Bolt User Inventory File" commands will be removed in a future release. Do you think they should be kept? Think there are other ways for this extension to help using Puppet Bolt? Let us know by clicking "Feedback" to add a comment to Github Issue #639'; + window.showWarningMessage(message, { modal: false }, { title: 'Feedback' }).then((result) => { if (result === undefined) { return; } if (result.title === 'Feedback') { - commands.executeCommand( - 'vscode.open', - Uri.parse('https://github.com/puppetlabs/puppet-vscode/issues/639') - ); + commands.executeCommand('vscode.open', Uri.parse('https://github.com/puppetlabs/puppet-vscode/issues/639')); } }); } - constructor(context: ExtensionContext) { + constructor(context: ExtensionContext) { context.subscriptions.push( commands.registerCommand('puppet-bolt.OpenUserConfigFile', () => { this.showDeprecation(); @@ -36,13 +31,13 @@ export class BoltFeature implements IFeature { this.openOrCreateFile( userInventoryFile, `Default bolt config yml not present. Do you want to create it?`, - '# This is an empty bolt config file.\n# You can get started quickly by using the built-in bolt snippets' + '# This is an empty bolt config file.\n# You can get started quickly by using the built-in bolt snippets', ); if (reporter) { reporter.sendTelemetryEvent('puppet-bolt.OpenUserConfigFile'); } - }) + }), ); context.subscriptions.push( @@ -54,13 +49,13 @@ export class BoltFeature implements IFeature { this.openOrCreateFile( userInventoryFile, `Default bolt inventory yml not present. Do you want to create it?`, - '# This is an empty bolt inventory file.\n# You can get started quickly by using the built-in bolt snippets or use bolt to generate an inventory file from PuppetDb' + '# This is an empty bolt inventory file.\n# You can get started quickly by using the built-in bolt snippets or use bolt to generate an inventory file from PuppetDb', ); if (reporter) { reporter.sendTelemetryEvent('puppet-bolt.OpenUserInventoryFile'); } - }) + }), ); } @@ -70,9 +65,9 @@ export class BoltFeature implements IFeature { .showQuickPick(['yes', 'no'], { placeHolder: message, canPickMany: false, - ignoreFocusOut: true + ignoreFocusOut: true, }) - .then(answer => { + .then((answer) => { switch (answer) { case 'no': break; @@ -83,8 +78,7 @@ export class BoltFeature implements IFeature { commands.executeCommand('vscode.openFolder', Uri.file(file), false); } }); - } - else { + } else { commands.executeCommand('vscode.openFolder', Uri.file(file), false); } } diff --git a/src/feature/DebuggingFeature.ts b/src/feature/DebuggingFeature.ts index 7e2083c4..0e507bf7 100644 --- a/src/feature/DebuggingFeature.ts +++ b/src/feature/DebuggingFeature.ts @@ -1,12 +1,12 @@ 'use strict'; -import * as vscode from "vscode"; +import * as vscode from 'vscode'; import * as cp from 'child_process'; -import { IFeature } from "../feature"; -import { ILogger } from "../logging"; -import { CommandEnvironmentHelper } from "../helpers/commandHelper"; -import { IAggregateConfiguration } from "../configuration"; +import { IFeature } from '../feature'; +import { ILogger } from '../logging'; +import { CommandEnvironmentHelper } from '../helpers/commandHelper'; +import { IAggregateConfiguration } from '../configuration'; // Socket vs Exec DebugAdapter types // https://github.com/Microsoft/vscode/blob/2808feeaf6b24feaaa6ba49fb91ea165c4d5fb06/src/vs/workbench/parts/debug/node/debugger.ts#L58-L61 @@ -15,7 +15,7 @@ import { IAggregateConfiguration } from "../configuration"; // https://github.com/Microsoft/vscode/blob/2808feeaf6b24feaaa6ba49fb91ea165c4d5fb06/src/vs/workbench/parts/debug/node/debugAdapter.ts#L305 // // DebugAdapterServer uses tcp -// https://github.com/Microsoft/vscode/blob/2808feeaf6b24feaaa6ba49fb91ea165c4d5fb06/src/vs/workbench/parts/debug/node/debugAdapter.ts#L256 +// https://github.com/Microsoft/vscode/blob/2808feeaf6b24feaaa6ba49fb91ea165c4d5fb06/src/vs/workbench/parts/debug/node/debugAdapter.ts#L256 export class DebugAdapterDescriptorFactory implements vscode.DebugAdapterDescriptorFactory, vscode.Disposable { readonly Context: vscode.ExtensionContext; @@ -24,64 +24,67 @@ export class DebugAdapterDescriptorFactory implements vscode.DebugAdapterDescrip public ChildProcesses: cp.ChildProcess[] = []; - constructor( - context: vscode.ExtensionContext, - config: IAggregateConfiguration, - logger: ILogger - ) { + constructor(context: vscode.ExtensionContext, config: IAggregateConfiguration, logger: ILogger) { this.Context = context; this.Config = config; this.Logger = logger; } - public createDebugAdapterDescriptor(session: vscode.DebugSession, executable: vscode.DebugAdapterExecutable): vscode.ProviderResult { + public createDebugAdapterDescriptor( + session: vscode.DebugSession, + executable: vscode.DebugAdapterExecutable, + ): vscode.ProviderResult { // Right now we don't care about session as we only have one type of adapter, which is launch. When // we add the ability to attach to a debugger remotely we'll need to switch scenarios based on `session` let thisFactory = this; - return new Promise( function(resolve, reject) { + return new Promise(function (resolve, reject) { let debugServer = CommandEnvironmentHelper.getDebugServerRubyEnvFromConfiguration( thisFactory.Context.asAbsolutePath(thisFactory.Config.ruby.debugServerPath), thisFactory.Config, ); - + let spawn_options: cp.SpawnOptions = {}; spawn_options.env = debugServer.options.env; spawn_options.stdio = 'pipe'; - if (process.platform !== 'win32') { spawn_options.shell = true; } - - thisFactory.Logger.verbose("Starting the Debug Server with " + debugServer.command + " " + debugServer.args.join(" ")); + if (process.platform !== 'win32') { + spawn_options.shell = true; + } + + thisFactory.Logger.verbose( + 'Starting the Debug Server with ' + debugServer.command + ' ' + debugServer.args.join(' '), + ); let debugServerProc = cp.spawn(debugServer.command, debugServer.args, spawn_options); thisFactory.ChildProcesses.push(debugServerProc); - + let debugSessionRunning: boolean = false; debugServerProc.stdout.on('data', (data) => { - thisFactory.Logger.debug("Debug Server STDOUT: " + data.toString()); + thisFactory.Logger.debug('Debug Server STDOUT: ' + data.toString()); // If the debug client isn't already running and it's sent the trigger text, start up a client - if ( !debugSessionRunning && (data.toString().match("DEBUG SERVER RUNNING") !== null) ) { + if (!debugSessionRunning && data.toString().match('DEBUG SERVER RUNNING') !== null) { debugSessionRunning = true; var p = data.toString().match(/DEBUG SERVER RUNNING (.*):(\d+)/); if (p === null) { - reject("Debug Server started but unable to parse hostname and port"); + reject('Debug Server started but unable to parse hostname and port'); } else { - thisFactory.Logger.debug("Starting Debug Client connection to " + p[1] + ":" + p[2]); + thisFactory.Logger.debug('Starting Debug Client connection to ' + p[1] + ':' + p[2]); resolve(new vscode.DebugAdapterServer(Number(p[2]), p[1])); } } }); debugServerProc.on('error', (data) => { - thisFactory.Logger.error("Debug Srver errored with " + data); - reject("Spawning Debug Server failed with " + data); + thisFactory.Logger.error('Debug Srver errored with ' + data); + reject('Spawning Debug Server failed with ' + data); }); debugServerProc.on('close', (exitCode) => { - thisFactory.Logger.verbose("Debug Server exited with exitcode " + exitCode); + thisFactory.Logger.verbose('Debug Server exited with exitcode ' + exitCode); }); }); } public dispose(): any { - this.ChildProcesses.forEach( (item) => { + this.ChildProcesses.forEach((item) => { item.kill('SIGHUP'); }); this.ChildProcesses = []; @@ -94,7 +97,7 @@ export class DebugConfigurationProvider implements vscode.DebugConfigurationProv private logger: ILogger; private context: vscode.ExtensionContext; - constructor(debugType:string, logger: ILogger, context: vscode.ExtensionContext) { + constructor(debugType: string, logger: ILogger, context: vscode.ExtensionContext) { this.debugType = debugType; this.logger = logger; this.context = context; @@ -102,15 +105,15 @@ export class DebugConfigurationProvider implements vscode.DebugConfigurationProv public provideDebugConfigurations( folder: vscode.WorkspaceFolder | undefined, - token?: vscode.CancellationToken + token?: vscode.CancellationToken, ): vscode.ProviderResult { - return [ this.createLaunchConfigFromContext(folder) ]; + return [this.createLaunchConfigFromContext(folder)]; } public resolveDebugConfiguration( folder: vscode.WorkspaceFolder | undefined, debugConfiguration: vscode.DebugConfiguration, - token?: vscode.CancellationToken + token?: vscode.CancellationToken, ): vscode.ProviderResult { return debugConfiguration; } @@ -120,10 +123,10 @@ export class DebugConfigurationProvider implements vscode.DebugConfigurationProv type: this.debugType, request: 'launch', name: 'Puppet Apply current file', - manifest: "${file}", + manifest: '${file}', args: [], noop: true, - cwd: "${file}", + cwd: '${file}', }; return config; @@ -134,20 +137,15 @@ export class DebuggingFeature implements IFeature { private factory: DebugAdapterDescriptorFactory; private provider: DebugConfigurationProvider; - constructor( - debugType: string, - config: IAggregateConfiguration, - context: vscode.ExtensionContext, - logger: ILogger - ) { + constructor(debugType: string, config: IAggregateConfiguration, context: vscode.ExtensionContext, logger: ILogger) { this.factory = new DebugAdapterDescriptorFactory(context, config, logger); this.provider = new DebugConfigurationProvider(debugType, logger, context); - logger.debug("Registered DebugAdapterDescriptorFactory for " + debugType); + logger.debug('Registered DebugAdapterDescriptorFactory for ' + debugType); context.subscriptions.push(vscode.debug.registerDebugAdapterDescriptorFactory(debugType, this.factory)); context.subscriptions.push(vscode.debug.registerDebugConfigurationProvider(debugType, this.provider)); - logger.debug("Registered DebugConfigurationProvider for " + debugType); + logger.debug('Registered DebugConfigurationProvider for ' + debugType); } public dispose(): any { diff --git a/src/feature/FormatDocumentFeature.ts b/src/feature/FormatDocumentFeature.ts index 3b767e08..5ebee5eb 100644 --- a/src/feature/FormatDocumentFeature.ts +++ b/src/feature/FormatDocumentFeature.ts @@ -1,12 +1,12 @@ 'use strict'; -import * as vscode from "vscode"; -import { IFeature } from "../feature"; -import { ILogger } from "../logging"; +import * as vscode from 'vscode'; +import { IFeature } from '../feature'; +import { ILogger } from '../logging'; import { ConnectionStatus } from '../interfaces'; import * as messages from '../messages'; -import { ConnectionHandler } from "../handler"; -import { IAggregateConfiguration } from "../configuration"; +import { ConnectionHandler } from '../handler'; +import { IAggregateConfiguration } from '../configuration'; class RequestParams implements messages.PuppetFixDiagnosticErrorsRequestParams { documentUri: string; @@ -20,19 +20,26 @@ class FormatDocumentProvider { this.connectionHandler = connectionManager; } - public async formatTextEdits(document: vscode.TextDocument, options: vscode.FormattingOptions): Promise { - if ((this.connectionHandler.status !== ConnectionStatus.RunningLoaded) && (this.connectionHandler.status !== ConnectionStatus.RunningLoading)) { - vscode.window.showInformationMessage("Please wait and try again. The Puppet extension is still loading..."); + public async formatTextEdits( + document: vscode.TextDocument, + options: vscode.FormattingOptions, + ): Promise { + if ( + this.connectionHandler.status !== ConnectionStatus.RunningLoaded && + this.connectionHandler.status !== ConnectionStatus.RunningLoading + ) { + vscode.window.showInformationMessage('Please wait and try again. The Puppet extension is still loading...'); return []; } - let requestParams = new RequestParams; + let requestParams = new RequestParams(); requestParams.documentUri = document.uri.toString(false); requestParams.alwaysReturnContent = false; - const result = await this.connectionHandler - .languageClient - .sendRequest(messages.PuppetFixDiagnosticErrorsRequest.type, requestParams) as messages.PuppetFixDiagnosticErrorsResponse; + const result = (await this.connectionHandler.languageClient.sendRequest( + messages.PuppetFixDiagnosticErrorsRequest.type, + requestParams, + )) as messages.PuppetFixDiagnosticErrorsResponse; if (result.fixesApplied > 0 && result.newContent !== undefined) { return [vscode.TextEdit.replace(new vscode.Range(0, 0, document.lineCount, 0), result.newContent)]; } @@ -48,20 +55,25 @@ export class FormatDocumentFeature implements IFeature { connectionManager: ConnectionHandler, config: IAggregateConfiguration, logger: ILogger, - context: vscode.ExtensionContext + context: vscode.ExtensionContext, ) { this.provider = new FormatDocumentProvider(connectionManager); if (config.workspace.format.enable === true) { - logger.debug("Registered Format Document provider"); - context.subscriptions.push(vscode.languages.registerDocumentFormattingEditProvider(langID, { - provideDocumentFormattingEdits: (document, options, token) => { return this.provider.formatTextEdits(document, options); } - } - )); + logger.debug('Registered Format Document provider'); + context.subscriptions.push( + vscode.languages.registerDocumentFormattingEditProvider(langID, { + provideDocumentFormattingEdits: (document, options, token) => { + return this.provider.formatTextEdits(document, options); + }, + }), + ); } else { - logger.debug("Format Document provider has not been registered"); + logger.debug('Format Document provider has not been registered'); } } - public dispose(): any { return undefined; } + public dispose(): any { + return undefined; + } } diff --git a/src/feature/PDKFeature.ts b/src/feature/PDKFeature.ts index 2acfafaf..5e692a2a 100644 --- a/src/feature/PDKFeature.ts +++ b/src/feature/PDKFeature.ts @@ -11,7 +11,7 @@ export class PDKFeature implements IFeature { constructor(context: vscode.ExtensionContext, logger: ILogger) { this.terminal = vscode.window.createTerminal('Puppet PDK'); - this.terminal.processId.then(pid => { + this.terminal.processId.then((pid) => { logger.debug('pdk shell started, pid: ' + pid); }); context.subscriptions.push(this.terminal); @@ -19,33 +19,33 @@ export class PDKFeature implements IFeature { context.subscriptions.push( vscode.commands.registerCommand(PDKCommandStrings.PdkNewModuleCommandId, () => { this.pdkNewModuleCommand(); - }) + }), ); - logger.debug("Registered " + PDKCommandStrings.PdkNewModuleCommandId + " command"); + logger.debug('Registered ' + PDKCommandStrings.PdkNewModuleCommandId + ' command'); context.subscriptions.push( vscode.commands.registerCommand(PDKCommandStrings.PdkNewClassCommandId, () => { this.pdkNewClassCommand(); - }) + }), ); - logger.debug("Registered " + PDKCommandStrings.PdkNewClassCommandId + " command"); + logger.debug('Registered ' + PDKCommandStrings.PdkNewClassCommandId + ' command'); context.subscriptions.push( vscode.commands.registerCommand(PDKCommandStrings.PdkNewTaskCommandId, () => { this.pdkNewTaskCommand(); - }) + }), ); - logger.debug("Registered " + PDKCommandStrings.PdkNewTaskCommandId + " command"); + logger.debug('Registered ' + PDKCommandStrings.PdkNewTaskCommandId + ' command'); context.subscriptions.push( vscode.commands.registerCommand(PDKCommandStrings.PdkValidateCommandId, () => { this.pdkValidateCommand(); - }) + }), ); - logger.debug("Registered " + PDKCommandStrings.PdkValidateCommandId + " command"); + logger.debug('Registered ' + PDKCommandStrings.PdkValidateCommandId + ' command'); context.subscriptions.push( vscode.commands.registerCommand(PDKCommandStrings.PdkTestUnitCommandId, () => { this.pdkTestUnitCommand(); - }) + }), ); - logger.debug("Registered " + PDKCommandStrings.PdkTestUnitCommandId + " command"); + logger.debug('Registered ' + PDKCommandStrings.PdkTestUnitCommandId + ' command'); } public dispose(): any { @@ -56,20 +56,20 @@ export class PDKFeature implements IFeature { let nameOpts: vscode.QuickPickOptions = { placeHolder: 'Enter a name for the new Puppet module', matchOnDescription: true, - matchOnDetail: true + matchOnDetail: true, }; let dirOpts: vscode.QuickPickOptions = { placeHolder: 'Enter a path for the new Puppet module', matchOnDescription: true, - matchOnDetail: true + matchOnDetail: true, }; - vscode.window.showInputBox(nameOpts).then(moduleName => { + vscode.window.showInputBox(nameOpts).then((moduleName) => { if (moduleName === undefined) { vscode.window.showWarningMessage('No module name specifed. Exiting.'); return; } - vscode.window.showInputBox(dirOpts).then(dir => { + vscode.window.showInputBox(dirOpts).then((dir) => { this.terminal.sendText(`pdk new module --skip-interview ${moduleName} ${dir}`); this.terminal.sendText(`code ${dir}`); this.terminal.show(); @@ -84,9 +84,9 @@ export class PDKFeature implements IFeature { let nameOpts: vscode.QuickPickOptions = { placeHolder: 'Enter a name for the new Puppet class', matchOnDescription: true, - matchOnDetail: true + matchOnDetail: true, }; - vscode.window.showInputBox(nameOpts).then(moduleName => { + vscode.window.showInputBox(nameOpts).then((moduleName) => { this.terminal.sendText(`pdk new class ${moduleName}`); this.terminal.show(); if (reporter) { @@ -99,9 +99,9 @@ export class PDKFeature implements IFeature { let nameOpts: vscode.QuickPickOptions = { placeHolder: 'Enter a name for the new Puppet Task', matchOnDescription: true, - matchOnDetail: true + matchOnDetail: true, }; - vscode.window.showInputBox(nameOpts).then(taskName => { + vscode.window.showInputBox(nameOpts).then((taskName) => { this.terminal.sendText(`pdk new task ${taskName}`); this.terminal.show(); if (reporter) { diff --git a/src/feature/PuppetModuleHoverFeature.ts b/src/feature/PuppetModuleHoverFeature.ts index a8560d1b..10ea709a 100644 --- a/src/feature/PuppetModuleHoverFeature.ts +++ b/src/feature/PuppetModuleHoverFeature.ts @@ -18,7 +18,7 @@ export class PuppetModuleHoverProvider implements vscode.HoverProvider { provideHover( document: vscode.TextDocument, position: vscode.Position, - token: vscode.CancellationToken + token: vscode.CancellationToken, ): Thenable | null { const offset = document.offsetAt(position); const location = getLocation(document.getText(), offset); @@ -40,12 +40,9 @@ export class PuppetModuleHoverProvider implements vscode.HoverProvider { this.logger.debug('Metadata hover info found ' + word + ' module'); - let name = word - .replace('"', '') - .replace('"', '') - .replace('/', '-'); + let name = word.replace('"', '').replace('"', '').replace('/', '-'); - return this.getModuleInfo(name).then(function(result: any) { + return this.getModuleInfo(name).then(function (result: any) { let msg: string[] = []; msg.push(`### ${result.slug}`); @@ -75,11 +72,11 @@ export class PuppetModuleHoverProvider implements vscode.HoverProvider { private getModuleInfo(name: string) { var options = { - url: `https://forgeapi.puppet.com/v3/modules/${name}?exclude_fields=readme%20changelog%20license%20reference` + url: `https://forgeapi.puppet.com/v3/modules/${name}?exclude_fields=readme%20changelog%20license%20reference`, }; - return new Promise(function(resolve, reject) { + return new Promise(function (resolve, reject) { const request = require('request'); - request.get(options, function(err, resp, body) { + request.get(options, function (err, resp, body) { if (err) { reject(err); } else { diff --git a/src/feature/PuppetNodeGraphFeature.ts b/src/feature/PuppetNodeGraphFeature.ts index e4c893da..58e095de 100644 --- a/src/feature/PuppetNodeGraphFeature.ts +++ b/src/feature/PuppetNodeGraphFeature.ts @@ -18,7 +18,7 @@ export class PuppetNodeGraphFeature implements IFeature { protected puppetLangID: string, protected handler: ConnectionHandler, protected logger: ILogger, - protected context: vscode.ExtensionContext + protected context: vscode.ExtensionContext, ) { this.providers = []; @@ -35,7 +35,7 @@ export class PuppetNodeGraphFeature implements IFeature { this.handler.status !== ConnectionStatus.RunningLoading ) { vscode.window.showInformationMessage( - 'The Puppet Node Graph Preview is not available as the Editor Service is not ready. Please try again.' + 'The Puppet Node Graph Preview is not available as the Editor Service is not ready. Please try again.', ); return; } @@ -44,29 +44,29 @@ export class PuppetNodeGraphFeature implements IFeature { vscode.window.activeTextEditor.document.uri, handler, logger, - context + context, ); this.providers.push(provider); provider.show(); - }) + }), ); logger.debug('Registered command for node graph event handler'); context.subscriptions.push( - vscode.workspace.onDidSaveTextDocument(document => { + vscode.workspace.onDidSaveTextDocument((document) => { // Subscribe to save events and fire updates - this.providers.forEach(item => { + this.providers.forEach((item) => { if (document.uri === vscode.window.activeTextEditor.document.uri) { item.show(true); } }); - }) + }), ); logger.debug('Registered onDidSaveTextDocument for node graph event handler'); } dispose() { - this.providers.forEach(p => { + this.providers.forEach((p) => { p.dispose(); }); } @@ -79,18 +79,18 @@ class NodeGraphWebViewProvider implements vscode.Disposable { protected resource: vscode.Uri, protected connectionHandler: ConnectionHandler, protected logger: ILogger, - protected context: vscode.ExtensionContext + protected context: vscode.ExtensionContext, ) { let fileName = path.basename(resource.fsPath); this.panel = vscode.window.createWebviewPanel( 'puppetNodeGraph', // Identifies the type of the webview. Used internally `Node Graph '${fileName}'`, // Title of the panel displayed to the user vscode.ViewColumn.Beside, // Editor column to show the new webview panel in. - { enableScripts: true } + { enableScripts: true }, ); this.panel.webview.html = this.getHtml(this.context.extensionPath); this.panel.onDidDispose(() => {}); - this.panel.webview.onDidReceiveMessage(message => { + this.panel.webview.onDidReceiveMessage((message) => { switch (message.command) { case 'error': vscode.window.showErrorMessage(message.errorMsg); @@ -109,9 +109,9 @@ class NodeGraphWebViewProvider implements vscode.Disposable { if (notificationType === undefined) { return this.connectionHandler.languageClient .sendRequest(PuppetNodeGraphRequest.type, { - external: this.resource.toString() + external: this.resource.toString(), }) - .then(compileResult => { + .then((compileResult) => { this.getJsonContent(compileResult, redraw); }); } else { @@ -119,19 +119,19 @@ class NodeGraphWebViewProvider implements vscode.Disposable { { location: notificationType, title: 'Puppet', - cancellable: false + cancellable: false, }, - progress => { + (progress) => { progress.report({ message: 'Generating New Node Graph' }); return this.connectionHandler.languageClient .sendRequest(PuppetNodeGraphRequest.type, { - external: this.resource.toString() + external: this.resource.toString(), }) - .then(compileResult => { + .then((compileResult) => { this.getJsonContent(compileResult, redraw); }); - } + }, ); } } @@ -140,13 +140,13 @@ class NodeGraphWebViewProvider implements vscode.Disposable { this.panel.dispose(); } - private getJsonContent(compileResult: PuppetNodeGraphResponse, redraw: boolean){ - if(compileResult === undefined){ + private getJsonContent(compileResult: PuppetNodeGraphResponse, redraw: boolean) { + if (compileResult === undefined) { vscode.window.showErrorMessage('Invalid data returned from manifest. Cannot build node graph'); return; } - if(compileResult.error){ + if (compileResult.error) { vscode.window.showErrorMessage(compileResult.error); return; } @@ -157,7 +157,7 @@ class NodeGraphWebViewProvider implements vscode.Disposable { this.panel.webview.postMessage({ content: compileResult, - redraw: redraw + redraw: redraw, }); } @@ -188,13 +188,13 @@ class NodeGraphWebViewProvider implements vscode.Disposable { private getHtml(extensionPath: string): string { let cytoPath = this.panel.webview.asWebviewUri( - vscode.Uri.file(path.join(extensionPath, 'vendor', 'cytoscape', 'cytoscape.min.js')) + vscode.Uri.file(path.join(extensionPath, 'vendor', 'cytoscape', 'cytoscape.min.js')), ); let mainScript = this.panel.webview.asWebviewUri( - vscode.Uri.file(path.join(extensionPath, 'assets', 'js', 'main.js')) + vscode.Uri.file(path.join(extensionPath, 'assets', 'js', 'main.js')), ); let mainCss = this.panel.webview.asWebviewUri( - vscode.Uri.file(path.join(extensionPath, 'assets', 'css', 'main.css')) + vscode.Uri.file(path.join(extensionPath, 'assets', 'css', 'main.css')), ); let html = ` diff --git a/src/feature/PuppetResourceFeature.ts b/src/feature/PuppetResourceFeature.ts index cec8a0a8..3debda67 100644 --- a/src/feature/PuppetResourceFeature.ts +++ b/src/feature/PuppetResourceFeature.ts @@ -3,7 +3,12 @@ import * as vscode from 'vscode'; import { IFeature } from '../feature'; import { ILogger } from '../logging'; -import { PuppetCommandStrings, PuppetResourceRequestParams, PuppetResourceRequest, PuppetResourceResponse } from '../messages'; +import { + PuppetCommandStrings, + PuppetResourceRequestParams, + PuppetResourceRequest, + PuppetResourceResponse, +} from '../messages'; import { reporter } from '../telemetry'; import { ConnectionStatus } from '../interfaces'; import { ConnectionHandler } from '../handler'; @@ -21,7 +26,7 @@ export class PuppetResourceFeature implements IFeature { context.subscriptions.push( vscode.commands.registerCommand(PuppetCommandStrings.PuppetResourceCommandId, () => { this.run(); - }) + }), ); } public run() { @@ -32,7 +37,7 @@ export class PuppetResourceFeature implements IFeature { return; } - this.pickPuppetResource().then(moduleName => { + this.pickPuppetResource().then((moduleName) => { if (moduleName) { let editor = vscode.window.activeTextEditor; if (!editor) { @@ -44,44 +49,56 @@ export class PuppetResourceFeature implements IFeature { requestParams.typename = moduleName; // Calculate where the progress message should go, if at all. - const currentSettings:ISettings = SettingsFromWorkspace(); - var notificationType = vscode.ProgressLocation.Notification; + const currentSettings: ISettings = SettingsFromWorkspace(); + var notificationType = vscode.ProgressLocation.Notification; if (currentSettings.notification !== undefined && currentSettings.notification.puppetResource !== undefined) { switch (currentSettings.notification.puppetResource.toLowerCase()) { - case "messagebox": notificationType = vscode.ProgressLocation.Notification; break; - case "statusbar": notificationType = vscode.ProgressLocation.Window; break; - case "none": notificationType = undefined; break; - default: break; // Default is already set + case 'messagebox': + notificationType = vscode.ProgressLocation.Notification; + break; + case 'statusbar': + notificationType = vscode.ProgressLocation.Window; + break; + case 'none': + notificationType = undefined; + break; + default: + break; // Default is already set } } if (notificationType !== undefined) { - vscode.window.withProgress({ - location: notificationType, - title: "Puppet", - cancellable: false - }, (progress) => { - progress.report({message: `Gathering Puppet ${moduleName} Resources`}); - return thisCommand._connectionHandler.languageClient - .sendRequest(PuppetResourceRequest.type, requestParams) - .then(resourceResult => { - this.respsonseToVSCodeEdit(resourceResult, editor, doc); - } - ); - }); + vscode.window.withProgress( + { + location: notificationType, + title: 'Puppet', + cancellable: false, + }, + (progress) => { + progress.report({ message: `Gathering Puppet ${moduleName} Resources` }); + return thisCommand._connectionHandler.languageClient + .sendRequest(PuppetResourceRequest.type, requestParams) + .then((resourceResult) => { + this.respsonseToVSCodeEdit(resourceResult, editor, doc); + }); + }, + ); } else { thisCommand._connectionHandler.languageClient .sendRequest(PuppetResourceRequest.type, requestParams) - .then(resourceResult => { + .then((resourceResult) => { this.respsonseToVSCodeEdit(resourceResult, editor, doc); - } - ); + }); } } }); } - private respsonseToVSCodeEdit(resourceResult: PuppetResourceResponse, editor: vscode.TextEditor, doc: vscode.TextDocument) { + private respsonseToVSCodeEdit( + resourceResult: PuppetResourceResponse, + editor: vscode.TextEditor, + doc: vscode.TextDocument, + ) { if (resourceResult.error !== undefined && resourceResult.error.length > 0) { this.logger.error(resourceResult.error); return; @@ -110,7 +127,7 @@ export class PuppetResourceFeature implements IFeature { let options: vscode.QuickPickOptions = { placeHolder: 'Enter a Puppet resource to interrogate', matchOnDescription: true, - matchOnDetail: true + matchOnDetail: true, }; return vscode.window.showInputBox(options); } diff --git a/src/feature/PuppetStatusBarFeature.ts b/src/feature/PuppetStatusBarFeature.ts index 985046db..5bc325d3 100644 --- a/src/feature/PuppetStatusBarFeature.ts +++ b/src/feature/PuppetStatusBarFeature.ts @@ -1,30 +1,26 @@ 'use strict'; -import * as vscode from "vscode"; -import { IFeature } from "../feature"; -import { ILogger } from "../logging"; +import * as vscode from 'vscode'; +import { IFeature } from '../feature'; +import { ILogger } from '../logging'; import { ConnectionStatus } from '../interfaces'; import { PuppetCommandStrings } from '../messages'; -import { IAggregateConfiguration } from "../configuration"; -import { ProtocolType } from "../settings"; +import { IAggregateConfiguration } from '../configuration'; +import { ProtocolType } from '../settings'; class PuppetStatusBarProvider { private statusBarItem: vscode.StatusBarItem; private logger: ILogger; private config: IAggregateConfiguration; - constructor( - langIDs: string[], - config: IAggregateConfiguration, - logger: ILogger - ) { + constructor(langIDs: string[], config: IAggregateConfiguration, logger: ILogger) { this.logger = logger; this.config = config; this.statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 1); this.statusBarItem.command = PuppetCommandStrings.PuppetShowConnectionMenuCommandId; this.statusBarItem.show(); - vscode.window.onDidChangeActiveTextEditor(textEditor => { + vscode.window.onDidChangeActiveTextEditor((textEditor) => { if (textEditor === undefined || langIDs.indexOf(textEditor.document.languageId) === -1) { this.statusBarItem.hide(); } else { @@ -68,7 +64,9 @@ class PuppetStatusBarProvider { this.statusBarItem.color = statusColor; // Using a conditional here because resetting a $(sync~spin) will cause the animation to restart. Instead // Only change the status bar text if it has actually changed. - if (this.statusBarItem.text !== statusIconText) { this.statusBarItem.text = statusIconText; } + if (this.statusBarItem.text !== statusIconText) { + this.statusBarItem.text = statusIconText; + } this.statusBarItem.tooltip = toolTip; // TODO: killme (new Date()).getUTCDate().toString() + "\nNewline\nWee!"; } @@ -76,56 +74,49 @@ class PuppetStatusBarProvider { var menuItems: PuppetConnectionMenuItem[] = []; menuItems.push( - new PuppetConnectionMenuItem( - "Show Puppet Session Logs", - () => { vscode.commands.executeCommand(PuppetCommandStrings.PuppetShowConnectionLogsCommandId); }), + new PuppetConnectionMenuItem('Show Puppet Session Logs', () => { + vscode.commands.executeCommand(PuppetCommandStrings.PuppetShowConnectionLogsCommandId); + }), ); if ( this.config.ruby.pdkPuppetVersions !== undefined && this.config.ruby.pdkPuppetVersions.length > 0 && this.config.connection.protocol != ProtocolType.TCP - ) { + ) { // Add a static menu item to use the latest version menuItems.push( - new PuppetConnectionMenuItem( - "Switch to latest Puppet version", - () => { vscode.commands.executeCommand(PuppetCommandStrings.PuppetUpdateConfigurationCommandId, { - "puppet.editorService.puppet.version": undefined + new PuppetConnectionMenuItem('Switch to latest Puppet version', () => { + vscode.commands.executeCommand(PuppetCommandStrings.PuppetUpdateConfigurationCommandId, { + 'puppet.editorService.puppet.version': undefined, }); }), ); this.config.ruby.pdkPuppetVersions - .sort( (a, b) => b.localeCompare(a, undefined, { numeric:true }) ) // Reverse sort - .forEach( (puppetVersion) => { + .sort((a, b) => b.localeCompare(a, undefined, { numeric: true })) // Reverse sort + .forEach((puppetVersion) => { menuItems.push( - new PuppetConnectionMenuItem( - "Switch to Puppet " + puppetVersion.toString(), - () => { vscode.commands.executeCommand(PuppetCommandStrings.PuppetUpdateConfigurationCommandId, { - "puppet.editorService.puppet.version": puppetVersion + new PuppetConnectionMenuItem('Switch to Puppet ' + puppetVersion.toString(), () => { + vscode.commands.executeCommand(PuppetCommandStrings.PuppetUpdateConfigurationCommandId, { + 'puppet.editorService.puppet.version': puppetVersion, }); }), ); - }); + }); } - vscode - .window - .showQuickPick(menuItems) - .then((selectedItem) => { - if(selectedItem){ - selectedItem.callback(); - } - }); + vscode.window.showQuickPick(menuItems).then((selectedItem) => { + if (selectedItem) { + selectedItem.callback(); + } + }); } } class PuppetConnectionMenuItem implements vscode.QuickPickItem { public description: string = ''; - constructor(public readonly label: string, public readonly callback: () => void = () => { }) - { - } + constructor(public readonly label: string, public readonly callback: () => void = () => {}) {} } export interface IPuppetStatusBar { @@ -135,15 +126,12 @@ export interface IPuppetStatusBar { export class PuppetStatusBarFeature implements IFeature, IPuppetStatusBar { private provider: PuppetStatusBarProvider; - constructor( - langIDs: string[], - config: IAggregateConfiguration, - logger: ILogger, - context: vscode.ExtensionContext - ) { - context.subscriptions.push(vscode.commands.registerCommand(PuppetCommandStrings.PuppetShowConnectionMenuCommandId, - () => { this.provider.showConnectionMenu(); } - )); + constructor(langIDs: string[], config: IAggregateConfiguration, logger: ILogger, context: vscode.ExtensionContext) { + context.subscriptions.push( + vscode.commands.registerCommand(PuppetCommandStrings.PuppetShowConnectionMenuCommandId, () => { + this.provider.showConnectionMenu(); + }), + ); this.provider = new PuppetStatusBarProvider(langIDs, config, logger); } @@ -151,5 +139,7 @@ export class PuppetStatusBarFeature implements IFeature, IPuppetStatusBar { this.provider.setConnectionStatus(statusText, status, toolTip); } - public dispose(): any { return undefined; } + public dispose(): any { + return undefined; + } } diff --git a/src/feature/UpdateConfigurationFeature.ts b/src/feature/UpdateConfigurationFeature.ts index 104b7e56..0fd46120 100644 --- a/src/feature/UpdateConfigurationFeature.ts +++ b/src/feature/UpdateConfigurationFeature.ts @@ -1,48 +1,56 @@ 'use strict'; -import * as vscode from "vscode"; -import { IFeature } from "../feature"; -import { ILogger } from "../logging"; +import * as vscode from 'vscode'; +import { IFeature } from '../feature'; +import { ILogger } from '../logging'; import { PuppetCommandStrings } from '../messages'; export class UpdateConfigurationFeature implements IFeature { private logger: ILogger; - private settingsRequireRestart = ["puppet.editorService.puppet.version"]; + private settingsRequireRestart = ['puppet.editorService.puppet.version']; private async updateSettingsAsync(updateSettingsHash) { // If there are no workspace folders then we've just opened a puppet file. Therefore we can't updated the workspace folder settings, so we need to update // the global configuration instead. - const configTarget = (vscode.workspace.workspaceFolders === undefined || vscode.workspace.workspaceFolders.length === 0) ? vscode.ConfigurationTarget.Global : null; + const configTarget = + vscode.workspace.workspaceFolders === undefined || vscode.workspace.workspaceFolders.length === 0 + ? vscode.ConfigurationTarget.Global + : null; var requiresRestart = false; - await Object.keys(updateSettingsHash).forEach( (key) => { + await Object.keys(updateSettingsHash).forEach((key) => { requiresRestart = requiresRestart || this.settingsRequireRestart.includes(key); let value = updateSettingsHash[key]; let config = vscode.workspace.getConfiguration(); - this.logger.debug("Updating configuration item " + key + " to '" + value + "'"); + this.logger.debug('Updating configuration item ' + key + " to '" + value + "'"); config.update(key, value, configTarget); }); if (requiresRestart) { vscode.window - .showInformationMessage("Puppet extensions needs to restart the editor. Would you like to do that now?", { modal: false }, ...['Yes', 'No']) - .then(selection => { - if (selection === "Yes") { - vscode.commands.executeCommand("workbench.action.reloadWindow"); + .showInformationMessage( + 'Puppet extensions needs to restart the editor. Would you like to do that now?', + { modal: false }, + ...['Yes', 'No'], + ) + .then((selection) => { + if (selection === 'Yes') { + vscode.commands.executeCommand('workbench.action.reloadWindow'); } }); } } - constructor( - logger: ILogger, - context: vscode.ExtensionContext - ) { + constructor(logger: ILogger, context: vscode.ExtensionContext) { this.logger = logger; - context.subscriptions.push(vscode.commands.registerCommand(PuppetCommandStrings.PuppetUpdateConfigurationCommandId, - (updateSettingsHash) => { this.updateSettingsAsync(updateSettingsHash); } - )); + context.subscriptions.push( + vscode.commands.registerCommand(PuppetCommandStrings.PuppetUpdateConfigurationCommandId, (updateSettingsHash) => { + this.updateSettingsAsync(updateSettingsHash); + }), + ); } - public dispose(): any { return undefined; } + public dispose(): any { + return undefined; + } } diff --git a/src/handler.ts b/src/handler.ts index 25aa9af3..f1c8715c 100644 --- a/src/handler.ts +++ b/src/handler.ts @@ -7,11 +7,11 @@ import { IPuppetStatusBar } from './feature/PuppetStatusBarFeature'; import { OutputChannelLogger } from './logging/outputchannel'; import { PuppetVersionDetails, PuppetVersionRequest, PuppetCommandStrings } from './messages'; import { reporter } from './telemetry'; -import { puppetFileLangID, puppetLangID} from './extension'; +import { puppetFileLangID, puppetLangID } from './extension'; import { IAggregateConfiguration } from './configuration'; export abstract class ConnectionHandler { - private timeSpent:number; + private timeSpent: number; private _status: ConnectionStatus; public get status(): ConnectionStatus { @@ -38,7 +38,10 @@ export abstract class ConnectionHandler { this.timeSpent = Date.now(); this.setConnectionStatus('Initializing', ConnectionStatus.Initializing); - let documents = [{ scheme: 'file', language: puppetLangID }, { scheme: 'file', language: puppetFileLangID }]; + let documents = [ + { scheme: 'file', language: puppetLangID }, + { scheme: 'file', language: puppetFileLangID }, + ]; this.logger.debug('Configuring language client options'); let clientOptions: LanguageClientOptions = { @@ -56,14 +59,14 @@ export abstract class ConnectionHandler { .onReady() .then( () => { - this.languageClient.onTelemetry(event => { + this.languageClient.onTelemetry((event) => { const eventName = event.Name ? event.Name : 'PUPPET_LANGUAGESERVER_EVENT'; reporter.sendTelemetryEvent(eventName, event.Measurements, event.Properties); }); this.setConnectionStatus('Loading Puppet', ConnectionStatus.Starting); this.queryLanguageServerStatusWithProgress(); }, - reason => { + (reason) => { this.setConnectionStatus('Starting error', ConnectionStatus.Starting); this.languageClient.error(reason); reporter.sendTelemetryException(reason); @@ -75,9 +78,11 @@ export abstract class ConnectionHandler { }); this.setConnectionStatus('Initialization Complete', ConnectionStatus.InitializationComplete); - this.context.subscriptions.push(vscode.commands.registerCommand(PuppetCommandStrings.PuppetShowConnectionLogsCommandId, - () => { this.logger.show(); } - )); + this.context.subscriptions.push( + vscode.commands.registerCommand(PuppetCommandStrings.PuppetShowConnectionLogsCommandId, () => { + this.logger.show(); + }), + ); } abstract createServerOptions(): ServerOptions; @@ -92,12 +97,12 @@ export abstract class ConnectionHandler { this.setConnectionStatus('Stopping languageserver', ConnectionStatus.Stopping, ''); if (this.languageClient !== undefined) { this.timeSpent = Date.now() - this.timeSpent; - this._languageClient.sendRequest(PuppetVersionRequest.type).then(versionDetails => { + this._languageClient.sendRequest(PuppetVersionRequest.type).then((versionDetails) => { reporter.sendTelemetryEvent('data', { - 'timeSpent' : this.timeSpent.toString(), - 'puppetVersion' : versionDetails.puppetVersion, - 'facterVersion' : versionDetails.facterVersion, - 'languageServerVersion': versionDetails.languageServerVersion, + timeSpent: this.timeSpent.toString(), + puppetVersion: versionDetails.puppetVersion, + facterVersion: versionDetails.facterVersion, + languageServerVersion: versionDetails.languageServerVersion, }); }); this.languageClient.stop(); @@ -128,7 +133,7 @@ export abstract class ConnectionHandler { return; } - this._languageClient.sendRequest(PuppetVersionRequest.type).then(versionDetails => { + this._languageClient.sendRequest(PuppetVersionRequest.type).then((versionDetails) => { lastVersionResponse = versionDetails; if ( versionDetails.factsLoaded && diff --git a/src/handlers/stdio.ts b/src/handlers/stdio.ts index 258911b7..4202f327 100644 --- a/src/handlers/stdio.ts +++ b/src/handlers/stdio.ts @@ -41,10 +41,10 @@ export class StdioConnectionHandler extends ConnectionHandler { case PuppetInstallType.PUPPET: logPrefix = '[getRubyExecFromPuppetAgent] '; this.logger.debug(logPrefix + 'Using environment variable SSL_CERT_FILE=' + exe.options.env.SSL_CERT_FILE); - this.logger.debug(logPrefix + 'Using environment variable SSL_CERT_DIR=' + exe.options.env.SSL_CERT_DIR); + this.logger.debug(logPrefix + 'Using environment variable SSL_CERT_DIR=' + exe.options.env.SSL_CERT_DIR); break; } - + this.logger.debug(logPrefix + 'Using environment variable RUBY_DIR=' + exe.options.env.RUBY_DIR); this.logger.debug(logPrefix + 'Using environment variable RUBYLIB=' + exe.options.env.RUBYLIB); this.logger.debug(logPrefix + 'Using environment variable PATH=' + exe.options.env.PATH); diff --git a/src/handlers/tcp.ts b/src/handlers/tcp.ts index bb6f6594..219007d3 100644 --- a/src/handlers/tcp.ts +++ b/src/handlers/tcp.ts @@ -50,14 +50,14 @@ export class TcpConnectionHandler extends ConnectionHandler { this.logger.debug(logPrefix + 'Editor Services will invoke with: ' + exe.command + ' ' + exe.args.join(' ')); var proc = cp.spawn(exe.command, exe.args, convertedOptions); - proc.stdout.on('data', data => { + proc.stdout.on('data', (data) => { if (/LANGUAGE SERVER RUNNING/.test(data.toString())) { var p = data.toString().match(/LANGUAGE SERVER RUNNING.*:(\d+)/); config.workspace.editorService.tcp.port = Number(p[1]); this.start(); } }); - proc.on('close', exitCode => { + proc.on('close', (exitCode) => { this.logger.debug('SERVER terminated with exit code: ' + exitCode); }); if (!proc || !proc.pid) { @@ -88,9 +88,7 @@ export class TcpConnectionHandler extends ConnectionHandler { createServerOptions(): ServerOptions { this.logger.debug( - `Starting language server client (host ${this.config.workspace.editorService.tcp.address} port ${ - this.config.workspace.editorService.tcp.port - })`, + `Starting language server client (host ${this.config.workspace.editorService.tcp.address} port ${this.config.workspace.editorService.tcp.port})`, ); let serverOptions = () => { diff --git a/src/helpers/commandHelper.ts b/src/helpers/commandHelper.ts index f4dbaf5f..cd6b975f 100644 --- a/src/helpers/commandHelper.ts +++ b/src/helpers/commandHelper.ts @@ -33,11 +33,7 @@ export class CommandEnvironmentHelper { return exe; } - private static applyRubyEnvFromConfiguration( - exe: Executable, - config: IAggregateConfiguration - ): Executable { - + private static applyRubyEnvFromConfiguration(exe: Executable, config: IAggregateConfiguration): Executable { // setup defaults exe.options.env = this.shallowCloneObject(process.env); exe.options.stdio = 'pipe'; @@ -95,7 +91,7 @@ export class CommandEnvironmentHelper { // not so much on Linux etc.. Look through all of the environment names looking for PATH in a // case insensitive way and remove the conflicting env var. let envPath: string = ''; - Object.keys(exe.options.env).forEach(function(keyname) { + Object.keys(exe.options.env).forEach(function (keyname) { if (keyname.match(/^PATH$/i)) { envPath = exe.options.env[keyname]; exe.options.env[keyname] = undefined; @@ -108,7 +104,6 @@ export class CommandEnvironmentHelper { } } - private static buildExecutableCommand(config: IAggregateConfiguration) { let command: string = ''; switch (config.workspace.installType) { @@ -122,10 +117,7 @@ export class CommandEnvironmentHelper { return command; } - private static buildLanguageServerArguments( - serverPath: string, - settings: IAggregateConfiguration, - ): string[] { + private static buildLanguageServerArguments(serverPath: string, settings: IAggregateConfiguration): string[] { let args = [serverPath]; switch (settings.workspace.editorService.protocol) { @@ -133,7 +125,10 @@ export class CommandEnvironmentHelper { args.push('--stdio'); break; case ProtocolType.TCP: - if (settings.workspace.editorService.tcp.address === undefined || settings.workspace.editorService.tcp.address === '') { + if ( + settings.workspace.editorService.tcp.address === undefined || + settings.workspace.editorService.tcp.address === '' + ) { args.push('--ip=127.0.0.1'); } else { args.push('--ip=' + settings.workspace.editorService.tcp.address); @@ -158,7 +153,7 @@ export class CommandEnvironmentHelper { { name: 'confdir', value: settings.workspace.editorService.puppet.confdir }, { name: 'environment', value: settings.workspace.editorService.puppet.environment }, { name: 'modulepath', value: settings.workspace.editorService.puppet.modulePath }, - { name: 'vardir', value: settings.workspace.editorService.puppet.vardir } + { name: 'vardir', value: settings.workspace.editorService.puppet.vardir }, ].forEach(function (item) { if (item.value !== undefined && item.value !== '') { puppetSettings.push('--' + item.name + ',' + item.value); @@ -168,19 +163,23 @@ export class CommandEnvironmentHelper { args.push('--puppet-settings=' + puppetSettings.join(',')); } - if (settings.workspace.editorService.puppet.version !== undefined && settings.workspace.editorService.puppet.version.trim() !== "") { + if ( + settings.workspace.editorService.puppet.version !== undefined && + settings.workspace.editorService.puppet.version.trim() !== '' + ) { args.push('--puppet-version=' + settings.workspace.editorService.puppet.version.trim()); } - if (settings.workspace.editorService.debugFilePath !== undefined && settings.workspace.editorService.debugFilePath !== '') { + if ( + settings.workspace.editorService.debugFilePath !== undefined && + settings.workspace.editorService.debugFilePath !== '' + ) { args.push('--debug=' + settings.workspace.editorService.debugFilePath); } return args; } - private static buildDebugServerArguments( - serverPath: string - ): string[] { + private static buildDebugServerArguments(serverPath: string): string[] { let args = [serverPath]; // The Debug Adapter always runs on TCP and IPv4 loopback @@ -208,9 +207,17 @@ export class CommandEnvironmentHelper { exe.options.env.DEVKIT_BASEDIR = config.ruby.puppetBaseDir; exe.options.env.RUBY_DIR = config.ruby.pdkRubyDir; exe.options.env.GEM_HOME = config.ruby.pdkGemDir; - exe.options.env.GEM_PATH = this.buildPathArray([config.ruby.pdkGemVerDir, config.ruby.pdkGemDir, config.ruby.pdkRubyVerDir]); + exe.options.env.GEM_PATH = this.buildPathArray([ + config.ruby.pdkGemVerDir, + config.ruby.pdkGemDir, + config.ruby.pdkRubyVerDir, + ]); exe.options.env.RUBYLIB = this.buildPathArray([config.ruby.pdkRubyLib, exe.options.env.RUBYLIB]); - exe.options.env.PATH = this.buildPathArray([config.ruby.pdkBinDir, config.ruby.pdkRubyBinDir, exe.options.env.PATH]); + exe.options.env.PATH = this.buildPathArray([ + config.ruby.pdkBinDir, + config.ruby.pdkRubyBinDir, + exe.options.env.PATH, + ]); } private static buildPathArray(items: any[]) { diff --git a/src/interfaces.ts b/src/interfaces.ts index 10ad4f80..49a8b6e1 100644 --- a/src/interfaces.ts +++ b/src/interfaces.ts @@ -10,5 +10,5 @@ export enum ConnectionStatus { Failed, Stopped, Initializing, - InitializationComplete + InitializationComplete, } diff --git a/src/logging.ts b/src/logging.ts index c887cc6e..57535360 100644 --- a/src/logging.ts +++ b/src/logging.ts @@ -5,14 +5,14 @@ export enum LogLevel { Verbose, Normal, Warning, - Error + Error, } export interface ILogger { - show():void; - verbose(message: string):void; - debug(message: string):void; - normal(message: string):void; - warning(message: string):void; - error(message: string):void; + show(): void; + verbose(message: string): void; + debug(message: string): void; + normal(message: string): void; + warning(message: string): void; + error(message: string): void; } diff --git a/src/logging/outputchannel.ts b/src/logging/outputchannel.ts index 8c052068..29264501 100644 --- a/src/logging/outputchannel.ts +++ b/src/logging/outputchannel.ts @@ -5,9 +5,8 @@ import * as logging from '../logging'; import { ISettings } from '../settings'; export class OutputChannelLogger implements logging.ILogger { - - private _logChannel : vscode.OutputChannel; - public get logChannel() : vscode.OutputChannel { + private _logChannel: vscode.OutputChannel; + public get logChannel(): vscode.OutputChannel { return this._logChannel; } diff --git a/src/messages.ts b/src/messages.ts index ff4ed484..2be80845 100644 --- a/src/messages.ts +++ b/src/messages.ts @@ -21,7 +21,7 @@ export interface PuppetResourceRequestParams { export namespace PuppetResourceRequest { export const type = new RequestType( - 'puppet/getResource' + 'puppet/getResource', ); } @@ -37,7 +37,7 @@ export interface PuppetFixDiagnosticErrorsRequestParams { export namespace PuppetFixDiagnosticErrorsRequest { export const type = new RequestType( - 'puppet/fixDiagnosticErrors' + 'puppet/fixDiagnosticErrors', ); } diff --git a/src/settings.ts b/src/settings.ts index 4007a62b..6efca0b3 100644 --- a/src/settings.ts +++ b/src/settings.ts @@ -5,19 +5,19 @@ import vscode = require('vscode'); export enum PuppetInstallType { PDK = 'pdk', PUPPET = 'agent', - AUTO = 'auto' + AUTO = 'auto', } export enum ProtocolType { UNKNOWN = '', STDIO = 'stdio', - TCP = 'tcp' + TCP = 'tcp', } export enum ConnectionType { Unknown, Local, - Remote + Remote, } export interface IEditorServiceTCPSettings { @@ -131,26 +131,26 @@ export function DefaultWorkspaceSettings(): ISettings { featureFlags: [], loglevel: 'normal', protocol: ProtocolType.STDIO, - timeout: 10 + timeout: 10, }, format: { - enable: true + enable: true, }, hover: { - showMetadataInfo: true + showMetadataInfo: true, }, installDirectory: undefined, installType: PuppetInstallType.AUTO, lint: { - enable: true + enable: true, }, notification: { nodeGraph: 'messagebox', - puppetResource: 'messagebox' + puppetResource: 'messagebox', }, pdk: { - checkVersion: true - } + checkVersion: true, + }, }; } @@ -167,7 +167,7 @@ export function SettingsFromWorkspace(): ISettings { installType: workspaceConfig.get('installType', defaults.installType), lint: workspaceConfig.get('lint', defaults.lint), notification: workspaceConfig.get('notification', defaults.notification), - pdk: workspaceConfig.get('pdk', defaults.pdk) + pdk: workspaceConfig.get('pdk', defaults.pdk), }; /** @@ -196,10 +196,12 @@ export function SettingsFromWorkspace(): ISettings { // Translate the legacy settings into the new setting names for (const [settingName, value] of oldSettings) { - switch (settingName) { + switch ( + settingName // case 'puppet.puppetAgentDir': // --> puppet.installDirectory // settings.installDirectory = value; // break; + ) { } } diff --git a/src/telemetry.ts b/src/telemetry.ts index 48684804..d908a869 100644 --- a/src/telemetry.ts +++ b/src/telemetry.ts @@ -1,30 +1,25 @@ import * as vscode from 'vscode'; import TelemetryReporter from 'vscode-extension-telemetry'; - -export const reporter:TelemetryReporter = getTelemetryReporter(); +export const reporter: TelemetryReporter = getTelemetryReporter(); function getTelemetryReporter() { let pkg = getPackageInfo(); - let reporter:TelemetryReporter = new TelemetryReporter( - pkg.name, - pkg.version, - pkg.aiKey - ); + let reporter: TelemetryReporter = new TelemetryReporter(pkg.name, pkg.version, pkg.aiKey); return reporter; } function getPackageInfo(): IPackageInfo { let pkg = vscode.extensions.getExtension('puppet.puppet-vscode'); - return { - name: pkg.packageJSON.name, - version: pkg.packageJSON.version, - aiKey: pkg.packageJSON.aiKey - }; + return { + name: pkg.packageJSON.name, + version: pkg.packageJSON.version, + aiKey: pkg.packageJSON.aiKey, + }; } -interface IPackageInfo { - name: string; - version: string; - aiKey: string; +interface IPackageInfo { + name: string; + version: string; + aiKey: string; } diff --git a/src/test/suite/configuration.test.ts b/src/test/suite/configuration.test.ts index 29fd7ce4..38c3a8ca 100644 --- a/src/test/suite/configuration.test.ts +++ b/src/test/suite/configuration.test.ts @@ -3,45 +3,45 @@ import * as assert from 'assert'; import { CreateAggregrateConfiguration } from '../../configuration'; import { DefaultWorkspaceSettings, ISettings, PuppetInstallType } from '../../settings'; -suite("Configuration Tests", () => { +suite('Configuration Tests', () => { var pdkBinDir = ''; var pdkPuppetBaseDir = ''; var puppetBaseDir = ''; - switch(process.platform){ + switch (process.platform) { case 'win32': pdkPuppetBaseDir = 'C:\\Program Files\\Puppet Labs\\DevelopmentKit'; - pdkBinDir = 'C:\\Program Files\\Puppet Labs\\DevelopmentKit\\bin'; - puppetBaseDir = 'C:\\Program Files\\Puppet Labs\\Puppet'; + pdkBinDir = 'C:\\Program Files\\Puppet Labs\\DevelopmentKit\\bin'; + puppetBaseDir = 'C:\\Program Files\\Puppet Labs\\Puppet'; break; default: pdkPuppetBaseDir = '/opt/puppetlabs/pdk'; - pdkBinDir = '/opt/puppetlabs/pdk/bin'; - puppetBaseDir = '/opt/puppetlabs'; + pdkBinDir = '/opt/puppetlabs/pdk/bin'; + puppetBaseDir = '/opt/puppetlabs'; break; } - test("resolves pdkPuppetBaseDir as puppet with default installtype", () => { + test('resolves pdkPuppetBaseDir as puppet with default installtype', () => { const settings: ISettings = DefaultWorkspaceSettings(); var config = CreateAggregrateConfiguration(settings); assert.equal(config.ruby.puppetBaseDir, pdkPuppetBaseDir); }); - test("resolves puppetBaseDir as puppet with installtype eq puppet", () => { + test('resolves puppetBaseDir as puppet with installtype eq puppet', () => { const settings: ISettings = DefaultWorkspaceSettings(); settings.installType = PuppetInstallType.PUPPET; var config = CreateAggregrateConfiguration(settings); assert.equal(config.ruby.puppetBaseDir, puppetBaseDir); }); - test("resolves puppetBaseDir as pdk with installtype eq pdk", () => { + test('resolves puppetBaseDir as pdk with installtype eq pdk', () => { const settings: ISettings = DefaultWorkspaceSettings(); settings.installType = PuppetInstallType.PDK; var config = CreateAggregrateConfiguration(settings); assert.equal(config.ruby.puppetBaseDir, pdkPuppetBaseDir); }); - test("resolves pdkBinDir with installtype eq pdk", () => { + test('resolves pdkBinDir with installtype eq pdk', () => { const settings: ISettings = DefaultWorkspaceSettings(); settings.installType = PuppetInstallType.PDK; var config = CreateAggregrateConfiguration(settings); @@ -50,22 +50,25 @@ suite("Configuration Tests", () => { // Note that these integration tests REQUIRE the PDK to be installed locally // as the fileystem is queried for path information - test("resolves latest PDK Instance with installtype eq pdk", () => { + test('resolves latest PDK Instance with installtype eq pdk', () => { const settings: ISettings = DefaultWorkspaceSettings(); settings.installType = PuppetInstallType.PDK; var config = CreateAggregrateConfiguration(settings); assert.notEqual(config.ruby.pdkGemDir, undefined); }); - test("resolves All Puppet Versions with installtype eq pdk", () => { + test('resolves All Puppet Versions with installtype eq pdk', () => { const settings: ISettings = DefaultWorkspaceSettings(); settings.installType = PuppetInstallType.PDK; var config = CreateAggregrateConfiguration(settings); assert.notEqual(config.ruby.pdkPuppetVersions, undefined); - assert.ok(config.ruby.pdkPuppetVersions.length > 0, "config.ruby.pdkPuppetVersions.length should have at least one element"); + assert.ok( + config.ruby.pdkPuppetVersions.length > 0, + 'config.ruby.pdkPuppetVersions.length should have at least one element', + ); }); - test("resolves a puppet version with installtype eq pdk", () => { + test('resolves a puppet version with installtype eq pdk', () => { // Find all of the available puppet settings let settings: ISettings = DefaultWorkspaceSettings(); settings.installType = PuppetInstallType.PDK; @@ -73,7 +76,7 @@ suite("Configuration Tests", () => { // Use the first version available const puppetVersion = config.ruby.pdkPuppetVersions[0]; settings.editorService.puppet = { - version: puppetVersion + version: puppetVersion, }; // Generate the settings again config = CreateAggregrateConfiguration(settings); diff --git a/src/test/suite/extension.test.ts b/src/test/suite/extension.test.ts index 25ae4af4..63ecb141 100644 --- a/src/test/suite/extension.test.ts +++ b/src/test/suite/extension.test.ts @@ -12,10 +12,9 @@ import * as vscode from 'vscode'; import * as myExtension from '../../extension'; // Defines a Mocha test suite to group tests of similar kind together -suite("Extension Tests", () => { - +suite('Extension Tests', () => { // Defines a Mocha unit test - test("Something 1", () => { + test('Something 1', () => { assert.equal(-1, [1, 2, 3].indexOf(5)); assert.equal(-1, [1, 2, 3].indexOf(0)); }); diff --git a/src/test/suite/index.ts b/src/test/suite/index.ts index 7dc787be..9d5d8618 100644 --- a/src/test/suite/index.ts +++ b/src/test/suite/index.ts @@ -18,11 +18,11 @@ export function run(): Promise { } // Add files to the test suite - files.forEach(f => mocha.addFile(path.resolve(testsRoot, f))); + files.forEach((f) => mocha.addFile(path.resolve(testsRoot, f))); try { // Run the mocha test - mocha.run(failures => { + mocha.run((failures) => { if (failures > 0) { e(new Error(`${failures} tests failed.`)); } else { diff --git a/src/test/suite/paths.test.ts b/src/test/suite/paths.test.ts index 433ad51e..36a8d3c4 100644 --- a/src/test/suite/paths.test.ts +++ b/src/test/suite/paths.test.ts @@ -3,10 +3,9 @@ import * as assert from 'assert'; import * as vscode from 'vscode'; import { PathResolver } from '../../configuration/pathResolver'; -suite("Path Resolution Tests", () => { - - test("resolves programfiles", () => { - switch(process.platform){ +suite('Path Resolution Tests', () => { + test('resolves programfiles', () => { + switch (process.platform) { case 'win32': assert.equal('C:\\Program Files', PathResolver.getprogramFiles()); break; @@ -15,9 +14,9 @@ suite("Path Resolution Tests", () => { break; } }); - - test("resolves environment PATH seperator", () => { - switch(process.platform){ + + test('resolves environment PATH seperator', () => { + switch (process.platform) { case 'win32': assert.equal(';', PathResolver.pathEnvSeparator()); break; @@ -26,5 +25,4 @@ suite("Path Resolution Tests", () => { break; } }); - }); diff --git a/src/test/suite/pdkResolver.test.ts b/src/test/suite/pdkResolver.test.ts index 71ae3f7a..e50595bc 100644 --- a/src/test/suite/pdkResolver.test.ts +++ b/src/test/suite/pdkResolver.test.ts @@ -2,8 +2,8 @@ import * as assert from 'assert'; import * as pdk from '../../configuration/pdkResolver'; -suite("configuration/pdkResolver Tests", () => { - test("resolves directories that do not exist as an empty instances array", () => { +suite('configuration/pdkResolver Tests', () => { + test('resolves directories that do not exist as an empty instances array', () => { const result = pdk.pdkInstances('/somedirectory/that/does/not/exist'); assert.equal(result.instances.length, 0); }); diff --git a/src/views/facts.ts b/src/views/facts.ts index 34cee16a..48e6ab67 100644 --- a/src/views/facts.ts +++ b/src/views/facts.ts @@ -18,7 +18,7 @@ class PuppetFact extends TreeItem { public readonly label: string, private value: string, public readonly collapsibleState: TreeItemCollapsibleState, - public readonly children?: Array<[string, PuppetFact]> + public readonly children?: Array<[string, PuppetFact]>, ) { super(label, collapsibleState); if (children) { @@ -77,7 +77,7 @@ export class PuppetFactsProvider implements TreeDataProvider { await this.handler.languageClient.onReady(); const details = await this.handler.languageClient.sendRequest( - new RequestType0('puppet/getVersion') + new RequestType0('puppet/getVersion'), ); if (!details.factsLoaded) { // language server is ready, but hasn't loaded facts yet @@ -89,7 +89,7 @@ export class PuppetFactsProvider implements TreeDataProvider { clearInterval(handle); const results = await this.handler.languageClient.sendRequest( - new RequestType0('puppet/getFacts') + new RequestType0('puppet/getFacts'), ); this.elements = this.toList(results.facts); @@ -101,13 +101,13 @@ export class PuppetFactsProvider implements TreeDataProvider { } const details = await this.handler.languageClient.sendRequest( - new RequestType0('puppet/getVersion') + new RequestType0('puppet/getVersion'), ); if (details.factsLoaded) { clearInterval(handle); const results = await this.handler.languageClient.sendRequest( - new RequestType0('puppet/getFacts') + new RequestType0('puppet/getFacts'), ); this.elements = this.toList(results.facts); @@ -124,7 +124,7 @@ export class PuppetFactsProvider implements TreeDataProvider { } const results = await this.handler.languageClient.sendRequest( - new RequestType0('puppet/getFacts') + new RequestType0('puppet/getFacts'), ); this.elements = this.toList(results.facts); diff --git a/tsconfig.json b/tsconfig.json index 8eb90b6c..e44c4833 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -3,22 +3,16 @@ "module": "commonjs", "target": "es6", "outDir": "out", - "lib": [ - "dom", - "es2016" - ], + "lib": ["dom", "es2016"], "sourceMap": true, "rootDir": "src", /* Strict Type-Checking Option */ - "strict": false, /* enable all strict type-checking options */ + "strict": false /* enable all strict type-checking options */, /* Additional Checks */ "noUnusedLocals": false /* Report errors on unused locals. */ // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ // "noUnusedParameters": true, /* Report errors on unused parameters. */ }, - "exclude": [ - "node_modules", - ".vscode-test" - ] + "exclude": ["node_modules", ".vscode-test"] } diff --git a/tslint.json b/tslint.json index 1ac5b65e..24071028 100644 --- a/tslint.json +++ b/tslint.json @@ -5,10 +5,7 @@ "no-duplicate-variable": true, "curly": true, "class-name": true, - "semicolon": [ - true, - "always" - ], + "semicolon": [true, "always"], "triple-equals": true }, "defaultSeverity": "warning"