💄 main side

This commit is contained in:
Benjamin Pasero
2017-06-08 09:48:37 +02:00
parent 7ceab4ec6e
commit 4aa3f05d08
14 changed files with 94 additions and 93 deletions
+141
View File
@@ -0,0 +1,141 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as fs from 'original-fs';
import * as path from 'path';
import * as arrays from 'vs/base/common/arrays';
import * as strings from 'vs/base/common/strings';
import * as paths from 'vs/base/common/paths';
import * as platform from 'vs/base/common/platform';
import * as types from 'vs/base/common/types';
import { ParsedArgs } from 'vs/platform/environment/common/environment';
export function validatePaths(args: ParsedArgs): ParsedArgs {
// Realpath/normalize paths and watch out for goto line mode
const paths = doValidatePaths(args._, args.goto);
// Update environment
args._ = paths;
args.diff = args.diff && paths.length === 2;
return args;
}
function doValidatePaths(args: string[], gotoLineMode?: boolean): string[] {
const cwd = process.env['VSCODE_CWD'] || process.cwd();
const result = args.map(arg => {
let pathCandidate = String(arg);
let parsedPath: IPathWithLineAndColumn;
if (gotoLineMode) {
parsedPath = parseLineAndColumnAware(pathCandidate);
pathCandidate = parsedPath.path;
}
if (pathCandidate) {
pathCandidate = preparePath(cwd, pathCandidate);
}
let realPath: string;
try {
realPath = fs.realpathSync(pathCandidate);
} catch (error) {
// in case of an error, assume the user wants to create this file
// if the path is relative, we join it to the cwd
realPath = path.normalize(path.isAbsolute(pathCandidate) ? pathCandidate : path.join(cwd, pathCandidate));
}
const basename = path.basename(realPath);
if (basename /* can be empty if code is opened on root */ && !paths.isValidBasename(basename)) {
return null; // do not allow invalid file names
}
if (gotoLineMode) {
parsedPath.path = realPath;
return toPath(parsedPath);
}
return realPath;
});
const caseInsensitive = platform.isWindows || platform.isMacintosh;
const distinct = arrays.distinct(result, e => e && caseInsensitive ? e.toLowerCase() : e);
return arrays.coalesce(distinct);
}
function preparePath(cwd: string, p: string): string {
// Trim trailing quotes
if (platform.isWindows) {
p = strings.rtrim(p, '"'); // https://github.com/Microsoft/vscode/issues/1498
}
// Trim whitespaces
p = strings.trim(strings.trim(p, ' '), '\t');
if (platform.isWindows) {
// Resolve the path against cwd if it is relative
p = path.resolve(cwd, p);
// Trim trailing '.' chars on Windows to prevent invalid file names
p = strings.rtrim(p, '.');
}
return p;
}
export interface IPathWithLineAndColumn {
path: string;
line?: number;
column?: number;
}
export function parseLineAndColumnAware(rawPath: string): IPathWithLineAndColumn {
const segments = rawPath.split(':'); // C:\file.txt:<line>:<column>
let path: string;
let line: number = null;
let column: number = null;
segments.forEach(segment => {
const segmentAsNumber = Number(segment);
if (!types.isNumber(segmentAsNumber)) {
path = !!path ? [path, segment].join(':') : segment; // a colon can well be part of a path (e.g. C:\...)
} else if (line === null) {
line = segmentAsNumber;
} else if (column === null) {
column = segmentAsNumber;
}
});
if (!path) {
throw new Error('Format for `--goto` should be: `FILE:LINE(:COLUMN)`');
}
return {
path: path,
line: line !== null ? line : void 0,
column: column !== null ? column : line !== null ? 1 : void 0 // if we have a line, make sure column is also set
};
}
function toPath(p: IPathWithLineAndColumn): string {
const segments = [p.path];
if (types.isNumber(p.line)) {
segments.push(String(p.line));
}
if (types.isNumber(p.column)) {
segments.push(String(p.column));
}
return segments.join(':');
}
+92
View File
@@ -0,0 +1,92 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as cp from 'child_process';
import { assign } from 'vs/base/common/objects';
import { generateUuid } from 'vs/base/common/uuid';
import { TPromise } from 'vs/base/common/winjs.base';
import { isWindows } from 'vs/base/common/platform';
function getUnixShellEnvironment(): TPromise<typeof process.env> {
const promise = new TPromise((c, e) => {
const runAsNode = process.env['ELECTRON_RUN_AS_NODE'];
const noAttach = process.env['ELECTRON_NO_ATTACH_CONSOLE'];
const mark = generateUuid().replace(/-/g, '').substr(0, 12);
const regex = new RegExp(mark + '(.*)' + mark);
const env = assign({}, process.env, {
ELECTRON_RUN_AS_NODE: '1',
ELECTRON_NO_ATTACH_CONSOLE: '1'
});
const command = `'${process.execPath}' -p '"${mark}" + JSON.stringify(process.env) + "${mark}"'`;
const child = cp.spawn(process.env.SHELL, ['-ilc', command], {
detached: true,
stdio: ['ignore', 'pipe', process.stderr],
env
});
const buffers: Buffer[] = [];
child.on('error', () => c({}));
child.stdout.on('data', b => buffers.push(b as Buffer));
child.on('close', (code: number, signal: any) => {
if (code !== 0) {
return e(new Error('Failed to get environment'));
}
const raw = Buffer.concat(buffers).toString('utf8');
const match = regex.exec(raw);
const rawStripped = match ? match[1] : '{}';
try {
const env = JSON.parse(rawStripped);
if (runAsNode) {
env['ELECTRON_RUN_AS_NODE'] = runAsNode;
} else {
delete env['ELECTRON_RUN_AS_NODE'];
}
if (noAttach) {
env['ELECTRON_NO_ATTACH_CONSOLE'] = noAttach;
} else {
delete env['ELECTRON_NO_ATTACH_CONSOLE'];
}
c(env);
} catch (err) {
e(err);
}
});
});
// swallow errors
return promise.then(null, () => ({}));
}
let _shellEnv: TPromise<typeof process.env>;
/**
* We need to get the environment from a user's shell.
* This should only be done when Code itself is not launched
* from within a shell.
*/
export function getShellEnvironment(): TPromise<typeof process.env> {
if (_shellEnv === undefined) {
if (isWindows) {
_shellEnv = TPromise.as({});
} else if (process.env['VSCODE_CLI'] === '1') {
_shellEnv = TPromise.as({});
} else {
_shellEnv = getUnixShellEnvironment();
}
}
return _shellEnv;
}
+94
View File
@@ -0,0 +1,94 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as path from 'path';
import * as fs from 'original-fs';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
export const IStorageService = createDecorator<IStorageService>('storageService');
export interface IStorageService {
_serviceBrand: any;
getItem<T>(key: string, defaultValue?: T): T;
setItem(key: string, data: any): void;
removeItem(key: string): void;
}
export class StorageService implements IStorageService {
_serviceBrand: any;
private dbPath: string;
private database: any = null;
constructor( @IEnvironmentService private environmentService: IEnvironmentService) {
this.dbPath = path.join(environmentService.userDataPath, 'storage.json');
}
public getItem<T>(key: string, defaultValue?: T): T {
if (!this.database) {
this.database = this.load();
}
const res = this.database[key];
if (typeof res === 'undefined') {
return defaultValue;
}
return this.database[key];
}
public setItem(key: string, data: any): void {
if (!this.database) {
this.database = this.load();
}
// Shortcut for primitives that did not change
if (typeof data === 'string' || typeof data === 'number' || typeof data === 'boolean') {
if (this.database[key] === data) {
return;
}
}
this.database[key] = data;
this.save();
}
public removeItem(key: string): void {
if (!this.database) {
this.database = this.load();
}
if (this.database[key]) {
delete this.database[key];
this.save();
}
}
private load(): any {
try {
return JSON.parse(fs.readFileSync(this.dbPath).toString()); // invalid JSON or permission issue can happen here
} catch (error) {
if (this.environmentService.verbose) {
console.error(error);
}
return {};
}
}
private save(): void {
try {
fs.writeFileSync(this.dbPath, JSON.stringify(this.database, null, 4)); // permission issue can happen here
} catch (error) {
if (this.environmentService.verbose) {
console.error(error);
}
}
}
}
+8 -4
View File
@@ -43,6 +43,7 @@ export function findBestWindowOrFolder<SimpleWindow extends ISimpleWindow>({ win
} else if (bestFolder) {
return bestFolder;
}
return !newWindow ? getLastActiveWindow(windows) : null;
}
@@ -51,6 +52,7 @@ function findBestWindow<WINDOW extends ISimpleWindow>(windows: WINDOW[], filePat
if (containers.length) {
return containers.sort((a, b) => -(a.openedWorkspacePath.length - b.openedWorkspacePath.length))[0];
}
return null;
}
@@ -60,6 +62,7 @@ function findBestFolder(filePath: string, userHome?: string, vscodeFolder?: stri
if (!platform.isLinux) {
homeFolder = homeFolder && homeFolder.toLowerCase();
}
let previous = null;
try {
while (folder !== previous) {
@@ -72,22 +75,23 @@ function findBestFolder(filePath: string, userHome?: string, vscodeFolder?: stri
} catch (err) {
// assume impossible to access
}
return null;
}
function isProjectFolder(folder: string, normalizedUserHome?: string, vscodeFolder = '.vscode') {
try {
if ((platform.isLinux ? folder : folder.toLowerCase()) === normalizedUserHome) {
// ~/.vscode/extensions is used for extensions
return fs.statSync(path.join(folder, vscodeFolder, 'settings.json')).isFile();
} else {
return fs.statSync(path.join(folder, vscodeFolder)).isDirectory();
return fs.statSync(path.join(folder, vscodeFolder, 'settings.json')).isFile(); // ~/.vscode/extensions is used for extensions
}
return fs.statSync(path.join(folder, vscodeFolder)).isDirectory();
} catch (err) {
if (!(err && err.code === 'ENOENT')) {
throw err;
}
}
return false;
}