cli.contribution.ts 8.7 KB
Newer Older
J
Joao Moreno 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

import * as nls from 'vs/nls';
import * as path from 'path';
import * as fs from 'fs';
import * as os from 'os';
import * as cp from 'child_process';
import * as pfs from 'vs/base/node/pfs';
import { nfcall } from 'vs/base/common/async';
import { TPromise } from 'vs/base/common/winjs.base';
import URI from 'vs/base/common/uri';
import { Action } from 'vs/base/common/actions';
import { IWorkbenchActionRegistry, Extensions as ActionExtensions } from 'vs/workbench/common/actionRegistry';
import { IWorkbenchContributionsRegistry, IWorkbenchContribution, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions';
import { Registry } from 'vs/platform/platform';
import { SyncActionDescriptor } from 'vs/platform/actions/common/actions';
import { IMessageService, Severity } from 'vs/platform/message/common/message';
import { IEditorService } from 'vs/platform/editor/common/editor';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
J
Joao Moreno 已提交
23
import product from 'vs/platform/product';
24

J
Joao Moreno 已提交
25 26 27 28 29
interface ILegacyUse {
	file: string;
	lineNumber: number;
}

J
Joao Moreno 已提交
30 31 32 33
function ignore<T>(code: string, value: T = null): (err: any) => TPromise<T> {
	return err => err.code === code ? TPromise.as<T>(value) : TPromise.wrapError<T>(err);
}

J
Joao Moreno 已提交
34 35 36 37
function readOrEmpty(name: string): TPromise<string> {
	return pfs.readFile(name, 'utf8').then(null, ignore('ENOENT', ''));
}

J
Joao Moreno 已提交
38 39
const root = URI.parse(require.toUrl('')).fsPath;
const source = path.resolve(root, '..', 'bin', 'code');
J
Joao Moreno 已提交
40
// TODO@Joao remove this, show the actions regardless and mention the actions can't run if that's the case
J
Joao Moreno 已提交
41 42 43 44 45
const isAvailable = fs.existsSync(source);

class InstallAction extends Action {

	static ID = 'workbench.action.installCommandLine';
46
	static LABEL = nls.localize('install', "Install '{0}' command in PATH", product.applicationName);
J
Joao Moreno 已提交
47 48 49 50 51 52 53 54 55 56 57

	constructor(
		id: string,
		label: string,
		@IMessageService private messageService: IMessageService,
		@IEditorService private editorService: IEditorService
	) {
		super(id, label);
	}

	private get target(): string {
58
		return `/usr/local/bin/${ product.applicationName }`;
J
Joao Moreno 已提交
59 60 61 62
	}

	run(): TPromise<void> {
		return this.checkLegacy()
J
Joao Moreno 已提交
63 64 65
			.then(uses => {
				if (uses.length > 0) {
					const { file, lineNumber } = uses[0];
66 67 68 69 70 71 72 73
					const message = nls.localize(
						'exists',
						"Please remove the alias referencing '{0}' in '{1}' (line {2}) and retry this action.",
						product.darwinBundleIdentifier,
						file,
						lineNumber
					);

74
					const resource = URI.file(file);
J
Joao Moreno 已提交
75 76 77 78
					const input = { resource, mime: 'text/x-shellscript' };
					const actions = [
						new Action('inlineEdit', nls.localize('editFile', "Edit '{0}'", file), '', true, () => {
							return this.editorService.openEditor(input).then(() => {
79
								const message = nls.localize('again', "Please remove the '{0}' alias from '{1}' before continuing.", product.applicationName, file);
J
Joao Moreno 已提交
80
								const actions = [
81 82
									new Action('continue', nls.localize('continue', "Continue"), '', true, () => this.run()),
									new Action('cancel', nls.localize('cancel', "Cancel"))
J
Joao Moreno 已提交
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
								];

								this.messageService.show(Severity.Info, { message, actions });
							});
						})
					];

					this.messageService.show(Severity.Warning, { message, actions });
					return TPromise.as(null);
				}

				return this.isInstalled()
					.then(isInstalled => {
						if (!isAvailable || isInstalled) {
							return TPromise.as(null);
						} else {
							const createSymlink = () => {
								return pfs.unlink(this.target)
									.then(null, ignore('ENOENT'))
									.then(() => pfs.symlink(source, this.target));
							};

							return createSymlink().then(null, err => {
								if (err.code === 'EACCES' || err.code === 'ENOENT') {
									return this.createBinFolder()
										.then(() => createSymlink());
								}

								return TPromise.wrapError(err);
							});
						}
					})
115
					.then(() => this.messageService.show(Severity.Info, nls.localize('successIn', "Shell command '{0}' successfully installed in PATH.", product.applicationName)));
J
Joao Moreno 已提交
116 117 118 119 120 121 122 123 124 125 126 127
			});
	}

	private isInstalled(): TPromise<boolean> {
		return pfs.lstat(this.target)
			.then(stat => stat.isSymbolicLink())
			.then(() => pfs.readlink(this.target))
			.then(link => link === source)
			.then(null, ignore('ENOENT', false));
	}

	private createBinFolder(): TPromise<void> {
J
Joao Moreno 已提交
128
		return new TPromise<void>((c, e) => {
J
wording  
Joao Moreno 已提交
129
			const message = nls.localize('warnEscalation', "Code will now prompt with 'osascript' for Administrator privileges to install the shell command.");
J
Joao Moreno 已提交
130 131 132 133 134 135 136 137 138
			const actions = [
				new Action('ok', nls.localize('ok', "OK"), '', true, () => {
					const command = 'osascript -e "do shell script \\"mkdir -p /usr/local/bin && chown \\" & (do shell script (\\"whoami\\")) & \\" /usr/local/bin\\" with administrator privileges"';

					nfcall(cp.exec, command, {})
						.then(null, _ => TPromise.wrapError(new Error(nls.localize('cantCreateBinFolder', "Unable to create '/usr/local/bin'."))))
						.done(c, e);

					return null;
139 140
				}),
				new Action('cancel2', nls.localize('cancel2', "Cancel"), '', true, () => { e(new Error(nls.localize('aborted', "Aborted"))); return null; })
J
Joao Moreno 已提交
141 142 143 144
			];

			this.messageService.show(Severity.Info, { message, actions });
		});
J
Joao Moreno 已提交
145 146
	}

J
Joao Moreno 已提交
147
	checkLegacy(): TPromise<ILegacyUse[]> {
J
Joao Moreno 已提交
148 149 150 151 152 153 154 155
		const files = [
			path.join(os.homedir(), '.bash_profile'),
			path.join(os.homedir(), '.bashrc'),
			path.join(os.homedir(), '.zshrc')
		];

		return TPromise.join(files.map(f => readOrEmpty(f))).then(result => {
			return result.reduce((result, contents, index) => {
J
Joao Moreno 已提交
156 157
				const file = files[index];
				const lines = contents.split(/\r?\n/);
J
Joao Moreno 已提交
158

J
Joao Moreno 已提交
159
				lines.some((line, index) => {
160
					if (line.indexOf(product.darwinBundleIdentifier) > -1 && !/^\s*#/.test(line)) {
J
Joao Moreno 已提交
161 162 163 164 165 166
						result.push({ file, lineNumber: index + 1 });
						return true;
					}

					return false;
				});
J
Joao Moreno 已提交
167 168

				return result;
J
Joao Moreno 已提交
169
			}, [] as ILegacyUse[]);
J
Joao Moreno 已提交
170 171 172 173 174 175 176
		});
	}
}

class UninstallAction extends Action {

	static ID = 'workbench.action.uninstallCommandLine';
177
	static LABEL = nls.localize('uninstall', "Uninstall '{0}' command from PATH", product.applicationName);
J
Joao Moreno 已提交
178 179 180 181 182 183 184 185 186 187

	constructor(
		id: string,
		label: string,
		@IMessageService private messageService: IMessageService
	) {
		super(id, label);
	}

	private get target(): string {
188
		return `/usr/local/bin/${ product.applicationName }`;
J
Joao Moreno 已提交
189 190 191 192 193
	}

	run(): TPromise<void> {
		return pfs.unlink(this.target)
			.then(null, ignore('ENOENT'))
194
			.then(() => this.messageService.show(Severity.Info, nls.localize('successFrom', "Shell command '{0}' successfully uninstalled from PATH.", product.applicationName)));
J
Joao Moreno 已提交
195 196 197 198 199 200 201 202 203 204 205 206 207
	}
}

class DarwinCLIHelper implements IWorkbenchContribution {

	constructor(
		@IInstantiationService instantiationService: IInstantiationService,
		@IMessageService messageService: IMessageService
	) {
		const installAction = instantiationService.createInstance(InstallAction, InstallAction.ID, InstallAction.LABEL);

		installAction.checkLegacy().done(files => {
			if (files.length > 0) {
208
				const message = nls.localize('update', "Code needs to change the '{0}' shell command. Would you like to do this now?", product.applicationName);
J
Joao Moreno 已提交
209 210
				const now = new Action('changeNow', nls.localize('changeNow', "Change Now"), '', true, () => installAction.run());
				const later = new Action('later', nls.localize('later', "Later"), '', true, () => {
J
casing  
Joao Moreno 已提交
211
					messageService.show(Severity.Info, nls.localize('laterInfo', "Remember you can always run the '{0}' action from the Command Palette.", installAction.label));
J
Joao Moreno 已提交
212 213
					return null;
				});
214
				const actions = [now, later];
J
Joao Moreno 已提交
215 216 217 218 219 220 221 222 223 224 225 226

				messageService.show(Severity.Info, { message, actions });
			}
		});
	}

	getId(): string {
		return 'darwin.cli';
	}
}

if (isAvailable && process.platform === 'darwin') {
J
Joao Moreno 已提交
227
	const category = nls.localize('shellCommand', "Shell Command");
J
Joao Moreno 已提交
228 229

	const workbenchActionsRegistry = <IWorkbenchActionRegistry>Registry.as(ActionExtensions.WorkbenchActions);
230 231
	workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(InstallAction, InstallAction.ID, InstallAction.LABEL), 'Shell Command: Install \'code\' command in PATH', category);
	workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(UninstallAction, UninstallAction.ID, UninstallAction.LABEL), 'Shell Command: Uninstall \'code\' command from PATH', category);
J
Joao Moreno 已提交
232 233 234 235

	const workbenchRegistry = <IWorkbenchContributionsRegistry>Registry.as(WorkbenchExtensions.Workbench);
	workbenchRegistry.registerWorkbenchContribution(DarwinCLIHelper);
}