Skip to content

Commit

Permalink
Adding stricter tslint rules (vscode-kubernetes-tools#274)
Browse files Browse the repository at this point in the history
* Adding stricter tslint rules

* TSLint auto-fixing pass

* Manual fixes for stuff TSLint couldnt fix
  • Loading branch information
bnookala authored Jul 4, 2018
1 parent 5b09863 commit a63c2c5
Show file tree
Hide file tree
Showing 51 changed files with 462 additions and 525 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -562,7 +562,7 @@
},
{
"command": "extension.vsKubernetesUseNamespace",
"title": "Set as Current Namespace",
"title": "Use Namespace",
"category": "Kubernetes"
},
{
Expand Down
13 changes: 5 additions & 8 deletions src/components/clusterprovider/azure/azure.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import * as vscode from 'vscode';
import { Shell } from '../../../shell';
import { FS } from '../../../fs';
import { ActionResult, fromShellJson, fromShellExitCodeAndStandardError, fromShellExitCodeOnly, Diagnostic } from '../../../wizard';
import { Errorable, succeeded, failed } from '../../../errorable';
import { Errorable, failed } from '../../../errorable';
import * as compareVersions from 'compare-versions';
import { sleep } from '../../../sleep';

Expand Down Expand Up @@ -123,7 +123,7 @@ export async function getClusterList(context: Context, subscription: string, clu
}

async function listClustersAsync(context: Context, clusterType: string): Promise<Errorable<ClusterInfo[]>> {
let cmd = getListClustersCommand(context, clusterType);
const cmd = getListClustersCommand(context, clusterType);
const sr = await context.shell.exec(cmd);

return fromShellJson<ClusterInfo[]>(sr);
Expand All @@ -137,7 +137,7 @@ function listClustersFilter(clusterType: string): string {
}

function getListClustersCommand(context: Context, clusterType: string): string {
let filter = listClustersFilter(clusterType);
const filter = listClustersFilter(clusterType);
let query = `[${filter}].{name:name,resourceGroup:resourceGroup}`;
if (context.shell.isUnix()) {
query = `'${query}'`;
Expand All @@ -154,6 +154,7 @@ async function listLocations(context: Context): Promise<Errorable<Locations>> {
const sr = await context.shell.exec(`az account list-locations --query ${query} -ojson`);

return fromShellJson<Locations>(sr, (response) => {
/* tslint:disable-next-line:prefer-const */
let locations: any = {};
for (const r of response) {
locations[r.name] = r.displayName;
Expand Down Expand Up @@ -242,7 +243,7 @@ async function ensureResourceGroupAsync(context: Context, resourceGroupName: str
async function execCreateClusterCmd(context: Context, options: any): Promise<Errorable<Diagnostic>> {
const clusterCmd = getClusterCommand(options.clusterType);
let createCmd = `az ${clusterCmd} create -n "${options.metadata.clusterName}" -g "${options.metadata.resourceGroupName}" -l "${options.metadata.location}" --generate-ssh-keys --no-wait `;
if (clusterCmd == 'acs') {
if (clusterCmd === 'acs') {
createCmd = createCmd + `--agent-count ${options.agentSettings.count} --agent-vm-size "${options.agentSettings.vmSize}" -t Kubernetes`;
} else {
createCmd = createCmd + `--node-count ${options.agentSettings.count} --node-vm-size "${options.agentSettings.vmSize}"`;
Expand All @@ -254,10 +255,6 @@ async function execCreateClusterCmd(context: Context, options: any): Promise<Err
}

export async function createCluster(context: Context, options: any): Promise<ActionResult<Diagnostic>> {
const description = `
Created ${options.clusterType} cluster ${options.metadata.clusterName} in ${options.metadata.resourceGroupName} with ${options.agentSettings.count} agents.
`;

const login = await setSubscriptionAsync(context, options.subscription);
if (!login.succeeded) {
return {
Expand Down
10 changes: 5 additions & 5 deletions src/components/clusterprovider/azure/azureclusterprovider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ export async function init(registry: clusterproviderregistry.ClusterProviderRegi
wizardServer.get('/configure', (req, resp, n) => htmlServer.handleGetConfigure(req, resp, n));
wizardServer.post('/configure', (req, resp, n) => htmlServer.handlePostConfigure(req, resp, n));

registry.register({id: 'aks', displayName: "Azure Kubernetes Service", port: wizardPort, supportedActions: ['create','configure']});
registry.register({id: 'acs', displayName: "Azure Container Service", port: wizardPort, supportedActions: ['create','configure']});
registry.register({id: 'aks', displayName: "Azure Kubernetes Service", port: wizardPort, supportedActions: ['create', 'configure']});
registry.register({id: 'acs', displayName: "Azure Container Service", port: wizardPort, supportedActions: ['create', 'configure']});
}
}

Expand Down Expand Up @@ -77,7 +77,7 @@ class HtmlServer {
const html = await handler(request.query["step"], this.context, requestData);

response.contentType = 'text/html';
response.send("<html><body><style id='styleholder'></style>" + html + "</body></html>");
response.send(`<html><body><style id='styleholder'></style>${html}</body></html>`);

next();
}
Expand Down Expand Up @@ -229,7 +229,7 @@ async function promptForAgentSettings(previousData: any, context: azure.Context)
}

const defaultSize = "Standard_D2_v2";
const options = vmSizes.result.map((s) => `<option value="${s}" ${s == defaultSize ? "selected=true" : ""}>${s}</option>`).join('\n');
const options = vmSizes.result.map((s) => `<option value="${s}" ${s === defaultSize ? "selected=true" : ""}>${s}</option>`).join('\n');

return formPage({
stepId: 'PromptForAgentSettings',
Expand Down Expand Up @@ -416,7 +416,7 @@ ${styles()}
// Utility helpers

function formatCluster(cluster: any): string {
return cluster.resourceGroup + '/' + cluster.name;
return `${cluster.resourceGroup}/${cluster.name}`;
}

function parseCluster(encoded: string): azure.ClusterInfo {
Expand Down
1 change: 0 additions & 1 deletion src/components/clusterprovider/clusterproviderserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import * as restify from 'restify';
import * as portfinder from 'portfinder';
import * as clusterproviderregistry from './clusterproviderregistry';
import { styles, script, waitScript } from '../../wizard';
import TelemetryReporter from 'vscode-extension-telemetry';
import { reporter } from '../../telemetry';

let cpServer: restify.Server;
Expand Down
1 change: 0 additions & 1 deletion src/components/clusterprovider/common/form.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,3 @@ export function formPage(fd: FormData): string {
</form>
</div>`;
}

Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import * as clusterproviderregistry from '../clusterproviderregistry';
import { styles, formStyles, waitScript, ActionResult, Diagnostic, fromShellExitCodeOnly } from '../../../wizard';
import { propagationFields, formPage } from '../common/form';
import { refreshExplorer } from '../common/explorer';
import { Errorable, succeeded, failed, Failed, Succeeded } from '../../../errorable';
import { succeeded, Failed } from '../../../errorable';
import { Shell } from '../../../shell';

export interface Context {
Expand Down Expand Up @@ -41,7 +41,7 @@ export async function init(registry: clusterproviderregistry.ClusterProviderRegi
minikubeWizardServer.get('/configure', (req, resp, n) => htmlServer.handleGetConfigure(req, resp, n));
minikubeWizardServer.post('/configure', (req, resp, n) => htmlServer.handlePostConfigure(req, resp, n));

registry.register({id: 'minikube', displayName: "Minikube local cluster", port: port, supportedActions: ['create','configure']});
registry.register({id: 'minikube', displayName: "Minikube local cluster", port: port, supportedActions: ['create', 'configure']});
}
}

Expand Down Expand Up @@ -75,7 +75,7 @@ class HtmlServer {
async handleRequest(handler: HtmlRequestHandler, request: restify.Request, requestData: any, response: restify.Response, next: restify.Next) {
const html = await handler(request.query["step"], requestData, this.context);
response.contentType = 'text/html';
response.send("<html><body><style id='styleholder'></style>" + html + "</body></html>");
response.send(`<html><body><style id='styleholder'></style>${html}</body></html>`);

next();
}
Expand Down
1 change: 0 additions & 1 deletion src/components/git/git.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,3 @@ export class Git {
return { succeeded: false, error: [ sr.stderr ] };
}
}

3 changes: 1 addition & 2 deletions src/components/installer/installer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import * as tmp from 'tmp';
import * as vscode from 'vscode';
import { Shell, Platform } from '../../shell';
import { Errorable, failed, succeeded } from '../../errorable';
import { exec } from 'child_process';

export async function installKubectl(shell: Shell): Promise<Errorable<void>> {
const tool = 'kubectl';
Expand Down Expand Up @@ -137,7 +136,7 @@ async function downloadToTempFile(sourceUrl: string): Promise<Errorable<string>>

async function downloadTo(sourceUrl: string, destinationFile: string): Promise<Errorable<void>> {
try {
const buffer = await download(sourceUrl, path.dirname(destinationFile), { filename: path.basename(destinationFile) });
await download(sourceUrl, path.dirname(destinationFile), { filename: path.basename(destinationFile) });
return { succeeded: true, result: null };
} catch (e) {
return { succeeded: false, error: [e.message] };
Expand Down
12 changes: 5 additions & 7 deletions src/components/kubectl/dashboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import { Kubectl } from '../../kubectl';
import { Node, KubernetesCollection, Pod } from '../../kuberesources.objectmodel';
import { failed } from '../../errorable';


const KUBE_DASHBOARD_URL = "http://localhost:8001/ui/";
const TERMINAL_NAME = "Kubernetes Dashboard";
const PROXY_OUTPUT_FILE = resolve(__dirname, 'proxy.out');
Expand All @@ -31,18 +30,17 @@ async function isAKSCluster (kubectl: Kubectl): Promise<boolean> {
if (failed(nodes)) {
return false;
}
const nodeItems = nodes.result.items;
const nodeCount = nodeItems.length;

for (let nodeItem of nodeItems) {
let isAKSNode = _isNodeAKS(nodeItem);
const nodeItems = nodes.result.items;
for (const nodeItem of nodeItems) {
const isAKSNode = _isNodeAKS(nodeItem);

if (!isAKSNode) {
return false;
}
}

return true;
return true;
}

function _isNodeAKS(node: Node): boolean {
Expand Down Expand Up @@ -125,7 +123,7 @@ export async function dashboardKubernetes (kubectl: Kubectl): Promise<void> {
}

// Read kubectl proxy's stdout as a stream.
const proxyStream = createReadStream(
createReadStream(
PROXY_OUTPUT_FILE,
{encoding: 'utf8'}
).on('data', onStreamData);
Expand Down
49 changes: 49 additions & 0 deletions src/components/kubectl/namespace.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { refreshExplorer } from '../clusterprovider/common/explorer';
import { promptKindName } from '../../extension';
import { host } from '../../host';
import * as kubectlUtils from '../../kubectlUtils';
import * as kuberesources from '../../kuberesources';
import * as explorer from '../../explorer';
import { Kubectl } from '../../kubectl';

export async function useNamespaceKubernetes(kubectl: Kubectl, explorerNode: explorer.KubernetesObject) {
if (explorerNode) {
if (await kubectlUtils.switchNamespace(kubectl, explorerNode.id)) {
refreshExplorer();
host.showInformationMessage(`Switched to namespace ${explorerNode.id}`);
return;
}
}

const currentNS = await kubectlUtils.currentNamespace(kubectl);
promptKindName(
[kuberesources.allKinds.namespace],
undefined,
{
prompt: 'What namespace do you want to use?',
placeHolder: 'Enter the namespace to switch to or press enter to select from available list',
filterNames: [currentNS]
},
switchToNamespace.bind(this, kubectl, currentNS)
);
}

async function switchToNamespace (kubectl: Kubectl, currentNS: string, resource: string) {
if (!resource) {
return;
}

let toSwitchNamespace = resource;
// resource will be of format <kind>/<name>, when picked up from the quickpick
if (toSwitchNamespace.lastIndexOf('/') !== -1) {
toSwitchNamespace = toSwitchNamespace.substring(toSwitchNamespace.lastIndexOf('/') + 1);
}

// Switch if an only if the currentNS and toSwitchNamespace are different
if (toSwitchNamespace && currentNS !== toSwitchNamespace) {
if (await kubectlUtils.switchNamespace(kubectl, toSwitchNamespace)) {
refreshExplorer();
host.showInformationMessage(`Switched to namespace ${toSwitchNamespace}`);
}
}
}
9 changes: 4 additions & 5 deletions src/components/kubectl/port-forward.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ interface PodFromDocument {
readonly namespace?: string;
}


type PortForwardFindPodsResult = PodFromDocument | FindPodsResult;

function isFindResultFromDocument(obj: PortForwardFindPodsResult): obj is PodFromDocument {
Expand Down Expand Up @@ -130,10 +129,10 @@ async function promptForPort (): Promise<PortMapping[]> {
* @returns A ValidationResult object describing the first error found.
*/
function validatePortMapping (portMapping: string): ValidationResult {
let portPairs = portMapping.split(' ');
const portPairs = portMapping.split(' ');
const validationResults: ValidationResult[] = portPairs.map(validatePortPair);

return validationResults.find((result) => result.valid === false );
return validationResults.find((result) => !result.valid );
}

/**
Expand All @@ -143,7 +142,7 @@ function validatePortMapping (portMapping: string): ValidationResult {
*/
function validatePortPair (portPair: string): ValidationResult {
let localPort, targetPort;
let splitMapping = portPair.split(':');
const splitMapping = portPair.split(':');

// User provided only the target port
if (!portPair.includes(':') && Number(portPair)) {
Expand Down Expand Up @@ -220,7 +219,7 @@ function buildPortPair(portPair: string): PortMapping {
* Checks the open document and returns an object describing the Pod, if it can find one
*/
async function findPortForwardablePods (): Promise<PortForwardFindPodsResult> {
let kindFromEditor = tryFindKindNameFromEditor();
const kindFromEditor = tryFindKindNameFromEditor();

// Find the pod type from the open editor.
if (succeeded(kindFromEditor)) {
Expand Down
22 changes: 10 additions & 12 deletions src/configMap.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import * as vscode from 'vscode';
import { basename } from 'path';
import { fs } from './fs';
import { shell } from './shell';
import { host } from './host';
import { create as kubectlCreate, Kubectl } from './kubectl';
import { Kubectl } from './kubectl';
import { currentNamespace, DataHolder } from './kubectlUtils';
import { deleteMessageItems, overwriteMessageItems } from './extension';
import { KubernetesFileObject, KubernetesDataHolderResource, KubernetesExplorer } from './explorer';
Expand All @@ -23,12 +21,12 @@ export class ConfigMapTextProvider implements vscode.TextDocumentContentProvider
}

export function loadConfigMapData(obj: KubernetesFileObject) {
let encoded_data = obj.configData[obj.id];
if (obj.resource == allKinds.configMap.abbreviation) {
encoded_data = Buffer.from(obj.configData[obj.id]).toString('base64');
let encodedData = obj.configData[obj.id];
if (obj.resource === allKinds.configMap.abbreviation) {
encodedData = Buffer.from(obj.configData[obj.id]).toString('base64');
}
const uri_str = `${uriScheme}://${obj.resource}/${encoded_data}/${obj.id}`;
const uri = vscode.Uri.parse(uri_str);
const uriStr = `${uriScheme}://${obj.resource}/${encodedData}/${obj.id}`;
const uri = vscode.Uri.parse(uriStr);
vscode.workspace.openTextDocument(uri).then(
(doc) => {
vscode.window.showTextDocument(doc);
Expand All @@ -39,7 +37,7 @@ export function loadConfigMapData(obj: KubernetesFileObject) {
}

function removeKey(dictionary: any, keyToDelete: string) {
let newData = {};
const newData = {};
Object.keys(dictionary).forEach((key) => {
if (key !== keyToDelete) {
newData[key] = dictionary[key];
Expand Down Expand Up @@ -93,22 +91,22 @@ export async function addKubernetesConfigFile(kubectl: Kubectl, obj: KubernetesD
const filePath = uri.fsPath;
const fileName = basename(filePath);
if (dataHolder.data[fileName]) {
let response = await vscode.window.showWarningMessage(`Are you sure you want to overwrite '${fileName}'? This can not be undone`, ...overwriteMessageItems);
const response = await vscode.window.showWarningMessage(`Are you sure you want to overwrite '${fileName}'? This can not be undone`, ...overwriteMessageItems);
if (response.title !== overwriteMessageItems[0].title) {
return;
}
}
// TODO: I really don't like sync calls here...
const buff = fs.readFileToBufferSync(filePath);
if (obj.resource == 'configmap') {
if (obj.resource === 'configmap') {
dataHolder.data[fileName] = buff.toString();
} else {
dataHolder.data[fileName] = buff.toString('base64');
}
});
const out = JSON.stringify(dataHolder);
const shellRes = await kubectl.invokeAsync(`replace -f - --namespace=${currentNS}`, out);
if (shellRes.code != 0) {
if (shellRes.code !== 0) {
vscode.window.showErrorMessage('Failed to add file(s) to resource ${obj.id}: ' + shellRes.stderr);
return;
}
Expand Down
3 changes: 0 additions & 3 deletions src/debug/debugProvider.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
import * as vscode from "vscode";

import { Kubectl } from "../kubectl";
import { ShellResult } from "../shell";
import { IDockerfile } from "../docker/parser";

export interface PortInfo {
Expand Down
Loading

0 comments on commit a63c2c5

Please sign in to comment.