- Use single quotes everywhere
- No more spaces before the colon in a object literal. Why was this ever set to `true` in the first place?
This commit is contained in:
vector-of-bool 2018-03-03 14:39:32 -07:00
Родитель b53b856293
Коммит 26aa452994
33 изменённых файлов: 496 добавлений и 499 удалений

Просмотреть файл

@ -61,9 +61,11 @@ SpacesInAngles: false
SpaceInEmptyParentheses: false
SpacesInCStyleCastParentheses: false
SpaceAfterCStyleCast: false
SpacesInContainerLiterals: true
SpacesInContainerLiterals: false
SpaceBeforeAssignmentOperators: true
ContinuationIndentWidth: 4
SpaceBeforeParens: ControlStatements
JavaScriptWrapImports: true
JavaScriptQuotes: Single
DisableFormat: false
...

Просмотреть файл

@ -75,7 +75,7 @@ export interface RawCompilationInfo {
export interface CompilationInfo {
file: string;
compile?: RawCompilationInfo;
includeDirectories: {path: string; isSystem : boolean;}[];
includeDirectories: {path: string; isSystem: boolean;}[];
compileDefinitions: {[define: string]: string|null};
compileFlags: string[];
compiler?: string;

Просмотреть файл

@ -150,14 +150,14 @@ export class CMakeCache {
} else {
const key = name;
const typemap = {
BOOL : api.CacheEntryType.Bool,
STRING : api.CacheEntryType.String,
PATH : api.CacheEntryType.Path,
FILEPATH : api.CacheEntryType.FilePath,
INTERNAL : api.CacheEntryType.Internal,
UNINITIALIZED : api.CacheEntryType.Uninitialized,
STATIC : api.CacheEntryType.Static,
} as {[type: string] : api.CacheEntryType | undefined};
BOOL: api.CacheEntryType.Bool,
STRING: api.CacheEntryType.String,
PATH: api.CacheEntryType.Path,
FILEPATH: api.CacheEntryType.FilePath,
INTERNAL: api.CacheEntryType.Internal,
UNINITIALIZED: api.CacheEntryType.Uninitialized,
STATIC: api.CacheEntryType.Static,
} as {[type: string]: api.CacheEntryType | undefined};
const type = typemap[typename];
const docs = docs_acc.trim();
docs_acc = '';
@ -182,7 +182,7 @@ export class CMakeCache {
*/
get(key: string): Entry|null {
const ret = this._entries.get(key) || null;
log.trace(`Get cache key ${key}=${ret ? ret.value : "[[Misisng]]"}`);
log.trace(`Get cache key ${key}=${ret ? ret.value : '[[Misisng]]'}`);
return ret;
}
}

Просмотреть файл

@ -7,10 +7,10 @@ import * as vscode from 'vscode';
import * as ws from 'ws';
import * as api from './api';
import {ExecutionOptions, ExecutionResult} from "./api";
import {CacheEditorContentProvider} from "./cache-editor";
import {ExecutionOptions, ExecutionResult} from './api';
import {CacheEditorContentProvider} from './cache-editor';
import {CMakeServerClientDriver} from './cms-driver';
import config from "./config";
import config from './config';
import {CTestDriver} from './ctest';
import * as diags from './diagnostics';
import {populateCollection} from './diagnostics';
@ -18,7 +18,7 @@ import {CMakeDriver} from './driver';
import {KitManager} from './kit';
import {LegacyCMakeDriver} from './legacy-driver';
import * as logging from './logging';
import {NagManager} from "./nag";
import {NagManager} from './nag';
import paths from './paths';
import {fs} from './pr';
import * as proc from './proc';
@ -73,9 +73,9 @@ export class CMakeTools implements vscode.Disposable, api.CMakeToolsAPI {
});
rollbar.takePromise('Setup cache editor server', {}, ready.then(() => {
const websock_server = this._ws_server = ws.createServer({server : editor_server});
const websock_server = this._ws_server = ws.createServer({server: editor_server});
websock_server.on('connection', client => {
const sub = this.onReconfigured(() => { client.send(JSON.stringify({method : 'refreshContent'})); });
const sub = this.onReconfigured(() => { client.send(JSON.stringify({method: 'refreshContent'})); });
client.onclose = () => { sub.dispose(); };
client.onmessage = msg => {
const data = JSON.parse(msg.data);
@ -84,14 +84,14 @@ export class CMakeTools implements vscode.Disposable, api.CMakeToolsAPI {
return this._handleCacheEditorMessage(data.method, data.params)
.then(ret => {
client.send(JSON.stringify({
id : data.id,
result : ret,
id: data.id,
result: ret,
}));
})
.catch(e => {
client.send(JSON.stringify({
id : data.id,
error : (e as Error).message,
id: data.id,
error: (e as Error).message,
}));
});
});
@ -172,7 +172,7 @@ export class CMakeTools implements vscode.Disposable, api.CMakeToolsAPI {
const drv = await (async () => {
log.debug('Starting CMake driver');
const cmake = await paths.cmakePath;
const version_ex = await proc.execute(cmake, [ '--version' ]).result;
const version_ex = await proc.execute(cmake, ['--version']).result;
if (version_ex.retc !== 0 || !version_ex.stdout) {
throw new Error(`Bad CMake executable "${cmake}". Is it installed and a valid executable?`);
}
@ -221,7 +221,7 @@ export class CMakeTools implements vscode.Disposable, api.CMakeToolsAPI {
if (drv) {
return drv.executeCommand(cmake, args, undefined, options).result;
} else {
throw new Error("Unable to execute cmake command, there is no valid cmake driver instance.");
throw new Error('Unable to execute cmake command, there is no valid cmake driver instance.');
}
}
@ -230,7 +230,7 @@ export class CMakeTools implements vscode.Disposable, api.CMakeToolsAPI {
if (drv) {
return drv.executeCommand(program, args, undefined, options).result;
} else {
throw new Error("Unable to execute program, there is no valid cmake driver instance.");
throw new Error('Unable to execute program, there is no valid cmake driver instance.');
}
}
@ -239,7 +239,7 @@ export class CMakeTools implements vscode.Disposable, api.CMakeToolsAPI {
if (drv) {
return drv.compilationInfoForFile(filepath);
} else {
throw new Error("Unable to get compilation information, there is no valid cmake driver instance.");
throw new Error('Unable to get compilation information, there is no valid cmake driver instance.');
}
}
@ -329,7 +329,7 @@ export class CMakeTools implements vscode.Disposable, api.CMakeToolsAPI {
await this._ctestController.reloadTests(cmakeInstance!);
this._statusBar.targetName = this.defaultBuildTarget || await this.allTargetName;
} catch (ex) {
log.debug("Exception on start of cmake driver.", ex.stack);
log.debug('Exception on start of cmake driver.', ex.stack);
this._cmakeDriver = Promise.resolve(null);
}
}
@ -546,18 +546,18 @@ export class CMakeTools implements vscode.Disposable, api.CMakeToolsAPI {
}
if (!drv.targets.length) {
return (await vscode.window.showInputBox({prompt : 'Enter a target name'})) || null;
return (await vscode.window.showInputBox({prompt: 'Enter a target name'})) || null;
} else {
const choices = drv.targets.map((t): vscode.QuickPickItem => {
switch (t.type) {
case 'named': {
return {
label : t.name,
description : 'Target to build',
label: t.name,
description: 'Target to build',
};
}
case 'rich': {
return {label : t.name, description : t.targetType, detail : t.filepath};
return {label: t.name, description: t.targetType, detail: t.filepath};
}
}
});
@ -662,9 +662,9 @@ export class CMakeTools implements vscode.Disposable, api.CMakeToolsAPI {
}
const choices = executableTargets.map(e => ({
label : e.name,
description : '',
detail : e.path,
label: e.name,
description: '',
detail: e.path,
}));
const chosen = await vscode.window.showQuickPick(choices);
if (!chosen) {
@ -729,19 +729,19 @@ export class CMakeTools implements vscode.Disposable, api.CMakeToolsAPI {
= drv.compilerID ? drv.compilerID.includes('MSVC') : (drv.linkerID ? drv.linkerID.includes('MSVC') : false);
const mi_mode = process.platform == 'darwin' ? 'lldb' : 'gdb';
const debug_config: vscode.DebugConfiguration = {
type : is_msvc ? 'cppvsdbg' : 'cppdbg',
name : `Debug ${target_path}`,
request : 'launch',
cwd : '${workspaceRoot}',
args : [],
MIMode : mi_mode,
type: is_msvc ? 'cppvsdbg' : 'cppdbg',
name: `Debug ${target_path}`,
request: 'launch',
cwd: '${workspaceRoot}',
args: [],
MIMode: mi_mode,
};
if (mi_mode == 'gdb') {
debug_config['setupCommands'] = [
{
description : 'Enable pretty-printing for gdb',
text : '-enable-pretty-printing',
ignoreFailures : true,
description: 'Enable pretty-printing for gdb',
text: '-enable-pretty-printing',
ignoreFailures: true,
},
];
}
@ -765,7 +765,7 @@ export class CMakeTools implements vscode.Disposable, api.CMakeToolsAPI {
return null;
}
if (!this._launchTerminal)
this._launchTerminal = vscode.window.createTerminal("CMake/Launch");
this._launchTerminal = vscode.window.createTerminal('CMake/Launch');
this._launchTerminal.sendText(target_path);
this._launchTerminal.show();
return this._launchTerminal;
@ -787,8 +787,8 @@ export class CMakeTools implements vscode.Disposable, api.CMakeToolsAPI {
}
const project_name = await vscode.window.showInputBox({
prompt : 'Enter a name for the new project',
validateInput : (value: string) : string => {
prompt: 'Enter a name for the new project',
validateInput: (value: string): string => {
if (!value.length)
return 'A project name is required';
return '';
@ -799,10 +799,10 @@ export class CMakeTools implements vscode.Disposable, api.CMakeToolsAPI {
const target_type = (await vscode.window.showQuickPick([
{
label : 'Library',
description : 'Create a library',
label: 'Library',
description: 'Create a library',
},
{label : 'Executable', description : 'Create an executable'}
{label: 'Executable', description: 'Create an executable'}
]));
if (!target_type)

Просмотреть файл

@ -7,7 +7,7 @@ import * as cache from './cache';
import config from './config';
import {CMakeGenerator} from './kit';
import {createLogger} from './logging';
import {fs} from "./pr";
import {fs} from './pr';
import * as proc from './proc';
import rollbar from './rollbar';
import * as util from './util';
@ -133,7 +133,7 @@ export interface HandshakeParams {
extraGenerator?: string;
platform?: string;
toolset?: string;
protocolVersion: {major: number; minor : number;};
protocolVersion: {major: number; minor: number;};
}
export interface HandshakeRequest extends CookiedMessage, HandshakeParams {
@ -158,9 +158,9 @@ export interface GlobalSettingsRequest extends CookiedMessage, GlobalSettingsPar
export interface GlobalSettingsContent {
buildDirectory: string;
capabilities: {
generators: {extraGenerators: string[]; name : string; platformSupport : boolean; toolsetSupport : boolean;}[];
serverMode : boolean;
version : {isDirty : boolean; major : number; minor : number; patch : number; string : string; suffix : string;};
generators: {extraGenerators: string[]; name: string; platformSupport: boolean; toolsetSupport: boolean;}[];
serverMode: boolean;
version: {isDirty: boolean; major: number; minor: number; patch: number; string: string; suffix: string;};
};
checkSystemVars: boolean;
extraGenerator: string;
@ -302,7 +302,7 @@ export interface CMakeInputsRequest extends CookiedMessage, CMakeInputsParams {
}
export interface CMakeInputsContent {
buildFiles: {isCMake: boolean; isTemporary : boolean; sources : string[];}[];
buildFiles: {isCMake: boolean; isTemporary: boolean; sources: string[];}[];
cmakeRootDirectory: string;
sourceDirectory: string;
}
@ -326,7 +326,7 @@ export interface CacheContent {
export interface CMakeCacheEntry {
key: string;
properties: {ADVANCED: '0'|'1'; HELPSTRING : string};
properties: {ADVANCED: '0'|'1'; HELPSTRING: string};
type: string;
value: string;
}
@ -473,7 +473,7 @@ export class CMakeServerClient {
await fs.unlink(this._pipeFilePath);
}
});
rollbar.takePromise('Unlink pipe', {pipe : this._pipeFilePath}, unlink_pr);
rollbar.takePromise('Unlink pipe', {pipe: this._pipeFilePath}, unlink_pr);
this._params.onHello(some as HelloMessage).catch(e => { log.error('Unhandled error in onHello', e); });
return;
}
@ -509,7 +509,7 @@ export class CMakeServerClient {
const cp = {type, ...params};
const cookie = cp.cookie = Math.random().toString();
const pr = new Promise(
(resolve, reject) => { this._promisesResolvers.set(cookie, {resolve : resolve, reject : reject}); });
(resolve, reject) => { this._promisesResolvers.set(cookie, {resolve: resolve, reject: reject}); });
const msg = JSON.stringify(cp);
console.log(`Sending message to cmake-server: ${msg}`);
this._pipe.write('\n[== "CMake Server" ==[\n');
@ -550,8 +550,8 @@ export class CMakeServerClient {
this._pipeFilePath = pipe_file;
const final_env = util.mergeEnvironment(process.env as proc.EnvironmentVariables, params.environment);
const child = this._proc
= child_proc.spawn(params.cmakePath, [ '-E', 'server', '--experimental', `--pipe=${pipe_file}` ], {
env : final_env,
= child_proc.spawn(params.cmakePath, ['-E', 'server', '--experimental', `--pipe=${pipe_file}`], {
env: final_env,
});
log.debug(`Started new CMake Server instance with PID ${child.pid}`);
child.stdout.on('data', this._onErrorData.bind(this));
@ -570,11 +570,11 @@ export class CMakeServerClient {
});
});
const exit_promise = new Promise<void>(resolve => { child.on('exit', () => { resolve(); }); });
this._endPromise = Promise.all([ end_promise, exit_promise ]).then(() => {});
this._endPromise = Promise.all([end_promise, exit_promise]).then(() => {});
this._proc = child;
child.on('close', (retc: number, signal: string) => {
if (retc !== 0) {
log.error("The connection to cmake-server was terminated unexpectedly");
log.error('The connection to cmake-server was terminated unexpectedly');
log.error(`cmake-server exited with status ${retc} (${signal})`);
params.onCrash(retc, signal).catch(e => { log.error(`Unhandled error in onCrash ${e}`); });
}
@ -590,24 +590,24 @@ export class CMakeServerClient {
return new Promise<CMakeServerClient>((resolve, reject) => {
const client = new CMakeServerClient({
tmpdir,
sourceDir : params.sourceDir,
binaryDir : params.binaryDir,
onMessage : params.onMessage,
cmakePath : params.cmakePath,
environment : params.environment,
onProgress : params.onProgress,
onDirty : params.onDirty,
pickGenerator : params.pickGenerator,
onCrash : async retc => {
sourceDir: params.sourceDir,
binaryDir: params.binaryDir,
onMessage: params.onMessage,
cmakePath: params.cmakePath,
environment: params.environment,
onProgress: params.onProgress,
onDirty: params.onDirty,
pickGenerator: params.pickGenerator,
onCrash: async retc => {
if (!resolved) {
reject(new StartupError(retc));
}
},
onHello : async (msg: HelloMessage) => {
onHello: async (msg: HelloMessage) => {
// We've gotten the hello message. We need to commense handshake
try {
const hsparams: HandshakeParams
= {buildDirectory : params.binaryDir, protocolVersion : msg.supportedProtocolVersions[0]};
= {buildDirectory: params.binaryDir, protocolVersion: msg.supportedProtocolVersions[0]};
const cache_path = path.join(params.binaryDir, 'CMakeCache.txt');
const have_cache = await fs.exists(cache_path);

Просмотреть файл

@ -2,17 +2,17 @@ import * as path from 'path';
import * as vscode from 'vscode';
import * as api from './api';
import {CacheEntryProperties, ExecutableTarget, RichTarget} from "./api";
import {CacheEntryProperties, ExecutableTarget, RichTarget} from './api';
import * as cache from './cache';
import * as cms from './cms-client';
import {CMakeDriver} from "./driver";
import {Kit} from "./kit";
import {CMakeDriver} from './driver';
import {Kit} from './kit';
import {createLogger} from './logging';
import paths from './paths';
import {fs} from "./pr";
import {fs} from './pr';
import * as proc from './proc';
import rollbar from './rollbar';
import {StateManager} from "./state";
import {StateManager} from './state';
import * as util from './util';
const log = createLogger('cms-driver');
@ -72,7 +72,7 @@ export class CMakeServerClientDriver extends CMakeDriver {
});
try {
await cl.configure({cacheArguments : args});
await cl.configure({cacheArguments: args});
await cl.compute();
this._dirty = false;
} catch (e) {
@ -107,13 +107,13 @@ export class CMakeServerClientDriver extends CMakeDriver {
const clcache = await cl.getCMakeCacheContent();
this._cacheEntries = clcache.cache.reduce((acc, el) => {
const entry_map: {[key: string]: api.CacheEntryType|undefined} = {
BOOL : api.CacheEntryType.Bool,
STRING : api.CacheEntryType.String,
PATH : api.CacheEntryType.Path,
FILEPATH : api.CacheEntryType.FilePath,
INTERNAL : api.CacheEntryType.Internal,
UNINITIALIZED : api.CacheEntryType.Uninitialized,
STATIC : api.CacheEntryType.Static,
BOOL: api.CacheEntryType.Bool,
STRING: api.CacheEntryType.String,
PATH: api.CacheEntryType.Path,
FILEPATH: api.CacheEntryType.FilePath,
INTERNAL: api.CacheEntryType.Internal,
UNINITIALIZED: api.CacheEntryType.Uninitialized,
STATIC: api.CacheEntryType.Static,
};
const type = entry_map[el.type];
if (type === undefined) {
@ -151,25 +151,25 @@ export class CMakeServerClientDriver extends CMakeDriver {
}
return config.projects.reduce<RichTarget[]>((acc, project) => acc.concat(
project.targets.map(t => ({
type : 'rich' as 'rich',
name : t.name,
filepath : t.artifacts && t.artifacts.length
type: 'rich' as 'rich',
name: t.name,
filepath: t.artifacts && t.artifacts.length
? path.normalize(t.artifacts[0])
: 'Utility target',
targetType : t.type,
targetType: t.type,
}))),
[ {
type : 'rich' as 'rich',
name : this.allTargetName,
filepath : 'A special target to build all available targets',
targetType : 'META',
} ]);
[{
type: 'rich' as 'rich',
name: this.allTargetName,
filepath: 'A special target to build all available targets',
targetType: 'META',
}]);
}
get executableTargets(): ExecutableTarget[] {
return this.targets.filter(t => t.targetType === 'EXECUTABLE').map(t => ({
name : t.name,
path : t.filepath,
name: t.name,
path: t.filepath,
}));
}
@ -212,14 +212,14 @@ export class CMakeServerClientDriver extends CMakeDriver {
});
if (found) {
const defs = (group.defines || []).map(util.parseCompileDefinition);
const defs_o = defs.reduce((acc, [ key, value ]) => ({...acc, [key] : value}), {});
const includes = (group.includePath || []).map(p => ({path : p.path, isSystem : p.isSystem || false}));
const defs_o = defs.reduce((acc, [key, value]) => ({...acc, [key]: value}), {});
const includes = (group.includePath || []).map(p => ({path: p.path, isSystem: p.isSystem || false}));
const flags = util.splitCommandLine(group.compileFlags);
return {
file : found,
compileDefinitions : defs_o,
compileFlags : flags,
includeDirectories : includes,
file: found,
compileDefinitions: defs_o,
compileFlags: flags,
includeDirectories: includes,
};
}
}
@ -245,14 +245,14 @@ export class CMakeServerClientDriver extends CMakeDriver {
private async _startNewClient() {
return cms.CMakeServerClient.start({
binaryDir : this.binaryDir,
sourceDir : this.sourceDir,
cmakePath : await paths.cmakePath,
environment : this.getKitEnvironmentVariablesObject(),
onDirty : async () => { this._dirty = true; },
onMessage : async msg => { this._onMessageEmitter.fire(msg.message); },
onProgress : async _prog => {},
pickGenerator : () => this.getBestGenerator(),
binaryDir: this.binaryDir,
sourceDir: this.sourceDir,
cmakePath: await paths.cmakePath,
environment: this.getKitEnvironmentVariablesObject(),
onDirty: async () => { this._dirty = true; },
onMessage: async msg => { this._onMessageEmitter.fire(msg.message); },
onProgress: async _prog => {},
pickGenerator: () => this.getBestGenerator(),
});
}

Просмотреть файл

@ -20,14 +20,14 @@ export function parseRawCompilationInfo(raw: RawCompilationInfo): CompilationInf
path: string;
isSystem: boolean
}[]);
const definitions = {} as {[key: string] : string | null};
const definitions = {} as {[key: string]: string | null};
const include_flags = [ {flag : '-I', isSystem : false}, {flag : '-isystem', isSystem : true} ];
const def_flags = [ '-D' ];
const include_flags = [{flag: '-I', isSystem: false}, {flag: '-isystem', isSystem: true}];
const def_flags = ['-D'];
if (compiler.endsWith('cl.exe')) {
// We are parsing an MSVC-style command line.
// It has options which may appear with a different argument prefix.
include_flags.push({flag : '/I', isSystem : false});
include_flags.push({flag: '/I', isSystem: false});
def_flags.push('/D');
}
@ -40,8 +40,8 @@ export function parseRawCompilationInfo(raw: RawCompilationInfo): CompilationInf
const ipath = arg(i) === flagstr ? arg(++i) : arg(i).substr(flagstr.length);
const abs_ipath = path.isAbsolute(ipath) ? ipath : path.join(raw.directory, ipath);
inc_dirs.push({
path : util.normalizePath(abs_ipath),
isSystem : iflag.isSystem,
path: util.normalizePath(abs_ipath),
isSystem: iflag.isSystem,
});
continue next_arg;
}
@ -65,20 +65,20 @@ export function parseRawCompilationInfo(raw: RawCompilationInfo): CompilationInf
return {
compiler,
compile : raw,
compileDefinitions : definitions,
file : raw.file,
includeDirectories : inc_dirs,
compileFlags : unparsed_args,
compile: raw,
compileDefinitions: definitions,
file: raw.file,
includeDirectories: inc_dirs,
compileFlags: unparsed_args,
};
}
export function parseCompileDefinition(str: string): [ string, string|null ] {
export function parseCompileDefinition(str: string): [string, string|null] {
if (/^\w+$/.test(str)) {
return [ str, null ];
return [str, null];
} else {
const key = str.split('=', 1)[0];
return [ key, str.substr(key.length + 1) ];
return [key, str.substr(key.length + 1)];
}
}

Просмотреть файл

@ -41,10 +41,10 @@ function readPrefixedConfig<T>(key: string): T|null;
function readPrefixedConfig<T>(key: string, default_: T): T;
function readPrefixedConfig<T>(key: string, default_?: T): T|null {
const platmap = {
win32 : 'windows',
darwin : 'osx',
linux : 'linux',
} as {[k: string] : string};
win32: 'windows',
darwin: 'osx',
linux: 'linux',
} as {[k: string]: string};
const platform = platmap[process.platform];
if (default_ === undefined) {
return readConfig(`${platform}.${key}`, readConfig<T>(`${key}`));
@ -104,13 +104,13 @@ class ConfigurationReader {
get debugConfig(): any { return readPrefixedConfig<any>('debugConfig'); }
get environment() { return readPrefixedConfig<{[key: string] : string}>('environment', {}); }
get environment() { return readPrefixedConfig<{[key: string]: string}>('environment', {}); }
get configureEnvironment() { return readPrefixedConfig<{[key: string] : string}>('configureEnvironment', {}); }
get configureEnvironment() { return readPrefixedConfig<{[key: string]: string}>('configureEnvironment', {}); }
get buildEnvironment() { return readPrefixedConfig<{[key: string] : string}>('buildEnvironment', {}); }
get buildEnvironment() { return readPrefixedConfig<{[key: string]: string}>('buildEnvironment', {}); }
get testEnvironment() { return readPrefixedConfig<{[key: string] : string}>('testEnvironment', {}); }
get testEnvironment() { return readPrefixedConfig<{[key: string]: string}>('testEnvironment', {}); }
get defaultVariants(): Object { return readPrefixedConfig<Object>('defaultVariants', {}); }
@ -152,7 +152,7 @@ class ConfigurationReader {
* @param cb A callback when the setting changes
*/
onChange<K extends keyof ConfigurationReader>(setting: K, cb: (value: ConfigurationReader[K]) => void) {
const state = {value : this[setting]};
const state = {value: this[setting]};
return vscode.workspace.onDidChangeConfiguration(() => {
rollbar.invoke(`Callback changing setting: cmake.${setting}`, () => {
const new_value = this[setting];

Просмотреть файл

@ -115,20 +115,19 @@ function decodeOutputMeasurement(node: EncodedMeasurementValue|string): string {
function cleanupResultsXML(messy: MessyResults): CTestResults {
return {
Site : {
$ : messy.Site.$,
Testing : {
TestList : messy.Site.Testing[0].TestList.map(l => l.Test[0]),
Test :
messy.Site.Testing[0].Test.map((test): Test => ({
FullName : test.FullName[0],
FullCommandLine : test.FullCommandLine[0],
Name : test.Name[0],
Path : test.Path[0],
Status : test.$.Status,
Measurements : new Map<string, TestMeasurement>(),
Output : decodeOutputMeasurement(test.Results[0].Measurement[0].Value[0]),
}))
Site: {
$: messy.Site.$,
Testing: {
TestList: messy.Site.Testing[0].TestList.map(l => l.Test[0]),
Test: messy.Site.Testing[0].Test.map((test): Test => ({
FullName: test.FullName[0],
FullCommandLine: test.FullCommandLine[0],
Name: test.Name[0],
Path: test.Path[0],
Status: test.$.Status,
Measurements: new Map<string, TestMeasurement>(),
Output: decodeOutputMeasurement(test.Results[0].Measurement[0].Value[0]),
}))
}
}
};
@ -165,9 +164,9 @@ export function parseCatchTestOutput(output: string): FailingTestDecoration[] {
}
decorations.push({
fileName : file,
lineNumber : lineno,
hoverMessage : `${message}\n~~~`,
fileName: file,
lineNumber: lineno,
hoverMessage: `${message}\n~~~`,
});
}
}
@ -188,7 +187,7 @@ export class DecorationManager {
}
private readonly _failingTestDecorationType = vscode.window.createTextEditorDecorationType({
borderColor : 'rgba(255, 0, 0, 0.2)',
borderColor: 'rgba(255, 0, 0, 0.2)',
borderWidth: '1px',
borderRadius: '3px',
borderStyle: 'solid',
@ -246,8 +245,8 @@ export class DecorationManager {
decor.lineNumber,
file_line.range.end.character);
fails_acc.push({
hoverMessage : decor.hoverMessage,
range : range,
hoverMessage: decor.hoverMessage,
range: range,
});
}
editor.setDecorations(this._failingTestDecorationType, fails_acc);
@ -335,10 +334,10 @@ export class CTestDriver implements vscode.Disposable {
const configuration = driver.currentBuildType;
const child
= driver.executeCommand(await paths.ctestPath,
[ `-j${config.numCTestJobs}`, '-C', configuration, '-T', 'test', '--output-on-failure' ]
[`-j${config.numCTestJobs}`, '-C', configuration, '-T', 'test', '--output-on-failure']
.concat(config.ctestArgs),
new CTestOutputLogger(),
{environment : config.testEnvironment, cwd : driver.binaryDir});
{environment: config.testEnvironment, cwd: driver.binaryDir});
const res = await child.result;
await this.reloadTests(driver);
@ -366,7 +365,7 @@ export class CTestDriver implements vscode.Disposable {
const build_config = driver.currentBuildType;
const result
= await driver
.executeCommand('ctest', [ '-N', '-C', build_config ], undefined, {cwd : driver.binaryDir, silent : true})
.executeCommand('ctest', ['-N', '-C', build_config], undefined, {cwd: driver.binaryDir, silent: true})
.result;
if (result.retc !== 0) {
// There was an error running CTest. Odd...
@ -377,7 +376,7 @@ export class CTestDriver implements vscode.Disposable {
.map(l => l.trim())
.filter(l => /^Test\s*#(\d+):\s(.*)/.test(l))
.map(l => /^Test\s*#(\d+):\s(.*)/.exec(l)!)
.map(([ _, id, tname ]) => ({id : parseInt(id!), name : tname!}));
.map(([_, id, tname]) => ({id: parseInt(id!), name: tname!}));
const tagfile = path.join(driver.binaryDir, 'Testing', 'TAG');
const tag = (await fs.exists(tagfile)) ? (await fs.readFile(tagfile)).toString().split('\n')[0].trim() : null;
const tagdir = tag ? path.join(driver.binaryDir, 'Testing', tag) : null;

Просмотреть файл

@ -9,7 +9,7 @@ import {RawDiagnostic} from './diagnostics';
import * as logging from './logging';
import * as proc from './proc';
import {OutputConsumer} from './proc';
import * as util from "./util";
import * as util from './util';
const cmake_logger = logging.createLogger('cmake');
const build_logger = logging.createLogger('build');
@ -110,7 +110,7 @@ export class CMakeOutputConsumer implements OutputConsumer {
blankLines: number,
}
= {
state : 'init',
state: 'init',
diag: null,
blankLines: 0,
};
@ -139,15 +139,15 @@ export class CMakeOutputConsumer implements OutputConsumer {
_full; // unused
const lineno = Number.parseInt(linestr) - 1;
const diagmap: {[k: string]: vscode.DiagnosticSeverity} = {
'Warning' : vscode.DiagnosticSeverity.Warning,
'Error' : vscode.DiagnosticSeverity.Error,
'Warning': vscode.DiagnosticSeverity.Warning,
'Error': vscode.DiagnosticSeverity.Error,
};
const vsdiag = new vscode.Diagnostic(new vscode.Range(lineno, 0, lineno, 9999), '', diagmap[level]);
vsdiag.source = `CMake (${command})`;
const filepath = path.isAbsolute(filename) ? filename : util.normalizePath(path.join(this.sourceDir, filename));
this._errorState.diag = {
filepath,
diag : vsdiag,
diag: vsdiag,
};
this._errorState.state = 'diag';
this._errorState.blankLines = 0;
@ -254,11 +254,11 @@ export class CompileOutputConsumer implements OutputConsumer {
const [full, file, lineno, message] = res;
if (file && lineno && message) {
return {
full : full,
file : file,
location : new vscode.Range(parseInt(lineno) - 1, 0, parseInt(lineno) - 1, 999),
severity : 'error',
message : message,
full: full,
file: file,
location: new vscode.Range(parseInt(lineno) - 1, 0, parseInt(lineno) - 1, 999),
severity: 'error',
message: message,
};
} else {
return null;
@ -288,12 +288,12 @@ export class CompileOutputConsumer implements OutputConsumer {
throw new Error('Unable to determine location of MSVC diagnostic');
})();
return {
full : full,
file : file,
location : range,
severity : severity,
message : message,
code : code,
full: full,
file: file,
location: range,
severity: severity,
message: message,
code: code,
};
}
@ -305,11 +305,11 @@ export class CompileOutputConsumer implements OutputConsumer {
const [full, file, lineno, column, severity, message] = gcc_mat;
if (file && lineno && column && severity && message) {
this._gccDiagnostics.push({
full : full,
file : file,
location : new vscode.Range(parseInt(lineno) - 1, parseInt(column) - 1, parseInt(lineno) - 1, 999),
severity : severity,
message : message,
full: full,
file: file,
location: new vscode.Range(parseInt(lineno) - 1, parseInt(column) - 1, parseInt(lineno) - 1, 999),
severity: severity,
message: message,
});
return;
}
@ -323,11 +323,11 @@ export class CompileOutputConsumer implements OutputConsumer {
const [full, file, lineno = '1', column = '1', severity, message] = ghs_mat;
if (file && severity && message) {
this._ghsDiagnostics.push({
full : full,
file : file,
location : new vscode.Range(parseInt(lineno) - 1, parseInt(column) - 1, parseInt(lineno) - 1, 999),
severity : severity,
message : message
full: full,
file: file,
location: new vscode.Range(parseInt(lineno) - 1, parseInt(column) - 1, parseInt(lineno) - 1, 999),
severity: severity,
message: message
});
return;
}
@ -371,12 +371,12 @@ export class CompileOutputConsumer implements OutputConsumer {
};
const by_source = {
GCC : this.gccDiagnostics,
MSVC : this.msvcDiagnostics,
GHS : this.ghsDiagnostics,
link : this.gnuLDDiagnostics,
GCC: this.gccDiagnostics,
MSVC: this.msvcDiagnostics,
GHS: this.ghsDiagnostics,
link: this.gnuLDDiagnostics,
};
const arrs = util.objectPairs(by_source).map(([ source, diags ]) => {
const arrs = util.objectPairs(by_source).map(([source, diags]) => {
return diags.map(raw_diag => {
const filepath = make_abs(raw_diag.file);
const diag = new vscode.Diagnostic(raw_diag.location, raw_diag.message, severity_of(raw_diag.severity));
@ -389,8 +389,8 @@ export class CompileOutputConsumer implements OutputConsumer {
}
diags_by_file.get(filepath)!.push(diag);
return {
filepath : filepath,
diag : diag,
filepath: filepath,
diag: diag,
};
});
});
@ -430,9 +430,9 @@ export class CMakeBuildConsumer implements OutputConsumer, vscode.Disposable {
if (progress) {
const percent = progress[1];
this._onProgressEmitter.fire({
minimum : 0,
maximum : 100,
value : Number.parseInt(percent),
minimum: 0,
maximum: 100,
value: Number.parseInt(percent),
});
}
}

Просмотреть файл

@ -13,9 +13,9 @@ import paths from './paths';
import {fs} from './pr';
import * as proc from './proc';
import rollbar from './rollbar';
import {StateManager} from "./state";
import {StateManager} from './state';
import * as util from './util';
import {ConfigureArguments, VariantConfigurationOptions} from "./variant";
import {ConfigureArguments, VariantConfigurationOptions} from './variant';
const log = logging.createLogger('driver');
@ -96,7 +96,7 @@ export abstract class CMakeDriver implements vscode.Disposable {
* Get the environment variables required by the current Kit
*/
getKitEnvironmentVariablesObject(): proc.EnvironmentVariables {
return util.reduce(this._kitEnvironmentVariables.entries(), {}, (acc, [ key, value ]) => ({...acc, [key] : value}));
return util.reduce(this._kitEnvironmentVariables.entries(), {}, (acc, [key, value]) => ({...acc, [key]: value}));
}
/**
@ -161,15 +161,15 @@ export abstract class CMakeDriver implements vscode.Disposable {
*/
async expandString(instr: string): Promise<string> {
const ws_root = util.normalizePath(vscode.workspace.rootPath || '.');
type StringObject = {[key: string] : string | undefined};
type StringObject = {[key: string]: string | undefined};
const user_dir = process.platform === 'win32' ? process.env['PROFILE']! : process.env['HOME']!;
const replacements: StringObject = {
workspaceRoot : vscode.workspace.rootPath,
buildType : this.currentBuildType,
workspaceRootFolderName : path.basename(ws_root),
generator : this.generatorName || 'null',
projectName : this.projectName,
userHome : user_dir,
workspaceRoot: vscode.workspace.rootPath,
buildType: this.currentBuildType,
workspaceRootFolderName: path.basename(ws_root),
generator: this.generatorName || 'null',
projectName: this.projectName,
userHome: user_dir,
};
// We accumulate a list of substitutions that we need to make, preventing
@ -221,7 +221,7 @@ export abstract class CMakeDriver implements vscode.Disposable {
const env = util.mergeEnvironment(cur_env,
this.getKitEnvironmentVariablesObject(),
(options && options.environment) ? options.environment : {});
const exec_options = {...options, environment : env};
const exec_options = {...options, environment: env};
return proc.execute(command, args, consumer, exec_options);
}
@ -364,7 +364,7 @@ export abstract class CMakeDriver implements vscode.Disposable {
*/
get compilerID(): string|null {
const entries = this.cmakeCacheEntries;
const languages = [ 'CXX', 'C', 'CUDA' ];
const languages = ['CXX', 'C', 'CUDA'];
for (const lang of languages) {
const entry = entries.get(`CMAKE_${lang}_COMPILER`);
if (!entry) {
@ -397,8 +397,8 @@ export abstract class CMakeDriver implements vscode.Disposable {
return null;
}
private async testHaveCommand(program: string, args: string[] = [ '--version' ]): Promise<boolean> {
const child = this.executeCommand(program, args, undefined, {silent : true});
private async testHaveCommand(program: string, args: string[] = ['--version']): Promise<boolean> {
const child = this.executeCommand(program, args, undefined, {silent: true});
try {
await child.result;
return true;
@ -412,7 +412,7 @@ export abstract class CMakeDriver implements vscode.Disposable {
}
getPreferredGenerators(): CMakeGenerator[] {
const user_preferred = config.preferredGenerators.map(g => ({name : g}));
const user_preferred = config.preferredGenerators.map(g => ({name: g}));
if (this._kit && this._kit.preferredGenerator) {
// The kit has a preferred generator attached as well
user_preferred.push(this._kit.preferredGenerator);
@ -429,12 +429,12 @@ export abstract class CMakeDriver implements vscode.Disposable {
if (user_generator) {
log.debug(`Using generator from user configuration: ${user_generator}`);
return {
name : user_generator,
platform : config.platform || undefined,
toolset : config.toolset || undefined,
name: user_generator,
platform: config.platform || undefined,
toolset: config.toolset || undefined,
};
}
log.debug("Trying to detect generator supported by system");
log.debug('Trying to detect generator supported by system');
const platform = process.platform;
const candidates = this.getPreferredGenerators();
for (const gen of candidates) {
@ -447,7 +447,7 @@ export abstract class CMakeDriver implements vscode.Disposable {
return platform === 'win32' && await this.testHaveCommand('make') || this.testHaveCommand('mingw32-make');
}
if (gen_name == 'NMake Makefiles') {
return platform === 'win32' && this.testHaveCommand('nmake', [ '/?' ]);
return platform === 'win32' && this.testHaveCommand('nmake', ['/?']);
}
if (gen_name == 'Unix Makefiles') {
return platform !== 'win32' && this.testHaveCommand('make');
@ -458,9 +458,9 @@ export abstract class CMakeDriver implements vscode.Disposable {
const vsMatch = /^(Visual Studio \d{2} \d{4})($|\sWin64$|\sARM$)/.exec(gen.name);
if (platform === 'win32' && vsMatch) {
return {
name : vsMatch[1],
platform : gen.platform || vsMatch[2],
toolset : gen.toolset,
name: vsMatch[1],
platform: gen.platform || vsMatch[2],
toolset: gen.toolset,
};
}
if (gen.name.toLowerCase().startsWith('xcode') && platform === 'darwin') {
@ -495,7 +495,7 @@ export abstract class CMakeDriver implements vscode.Disposable {
}
};
util.objectPairs(this._variantConfigureSettings).forEach(([ key, value ]) => settings[key] = value);
util.objectPairs(this._variantConfigureSettings).forEach(([key, value]) => settings[key] = value);
if (this._variantLinkage !== null) {
settings.BUILD_SHARED_LIBS = this._variantLinkage === 'shared';
}
@ -509,8 +509,8 @@ export abstract class CMakeDriver implements vscode.Disposable {
}
const settings_flags
= util.objectPairs(settings).map(([ key, value ]) => _makeFlag(key, util.cmakeify(value as string)));
const flags = [ '--no-warn-unused-cli' ].concat(extra_args);
= util.objectPairs(settings).map(([key, value]) => _makeFlag(key, util.cmakeify(value as string)));
const flags = ['--no-warn-unused-cli'].concat(extra_args);
console.assert(!!this._kit);
if (!this._kit) {
@ -520,8 +520,7 @@ export abstract class CMakeDriver implements vscode.Disposable {
case 'compilerKit': {
log.debug('Using compilerKit', this._kit.name, 'for usage');
flags.push(
...util.objectPairs(this._kit.compilers).map(([ lang,
comp ]) => `-DCMAKE_${lang}_COMPILER:FILEPATH=${comp}`));
...util.objectPairs(this._kit.compilers).map(([lang, comp]) => `-DCMAKE_${lang}_COMPILER:FILEPATH=${comp}`));
} break;
case 'toolchainKit': {
log.debug('Using CMake toolchain', this._kit.name, 'for configuring');
@ -532,8 +531,7 @@ export abstract class CMakeDriver implements vscode.Disposable {
}
if (this._kit.cmakeSettings) {
flags.push(
...util.objectPairs(this._kit.cmakeSettings).map(([ key, val ]) => _makeFlag(key, util.cmakeify(val))));
flags.push(...util.objectPairs(this._kit.cmakeSettings).map(([key, val]) => _makeFlag(key, util.cmakeify(val))));
}
const final_flags = flags.concat(settings_flags);
@ -600,12 +598,12 @@ export abstract class CMakeDriver implements vscode.Disposable {
const chosen = await vscode.window.showErrorMessage<
vscode.MessageItem>('Not all open documents were saved. Would you like to continue anyway?',
{
title : 'Yes',
isCloseAffordance : false,
title: 'Yes',
isCloseAffordance: false,
},
{
title : 'No',
isCloseAffordance : true,
title: 'No',
isCloseAffordance: true,
});
return chosen !== undefined && (chosen.title === 'Yes');
}
@ -630,7 +628,7 @@ export abstract class CMakeDriver implements vscode.Disposable {
if (!gen)
return [];
else if (/(Unix|MinGW) Makefiles|Ninja/.test(gen) && target !== 'clean')
return [ '-j', config.numJobs.toString() ];
return ['-j', config.numJobs.toString()];
else if (gen.includes('Visual Studio'))
return [
'/m',
@ -639,8 +637,8 @@ export abstract class CMakeDriver implements vscode.Disposable {
else
return [];
})();
const args = [ '--build', this.binaryDir, '--config', this.currentBuildType, '--target', target, '--' ].concat(
generator_args);
const args =
['--build', this.binaryDir, '--config', this.currentBuildType, '--target', target, '--'].concat(generator_args);
const cmake = await paths.cmakePath;
const child = this.executeCommand(cmake, args, consumer);
this._currentProcess = child;

Просмотреть файл

@ -10,9 +10,9 @@ import * as logging from './logging';
import paths from './paths';
import {fs} from './pr';
import * as proc from './proc';
import {loadSchema} from "./schema";
import {loadSchema} from './schema';
import {StateManager} from './state';
import {dropNulls, thisExtensionPath} from "./util";
import {dropNulls, thisExtensionPath} from './util';
const log = logging.createLogger('kit');
@ -119,8 +119,8 @@ export async function kitIfCompiler(bin: string, pr?: ProgressReporter): MaybeCo
if (gcc_res) {
log.debug('Testing GCC-ish binary:', bin);
if (pr)
pr.report({message : `Getting GCC version for ${bin}`});
const exec = await proc.execute(bin, [ '-v' ]).result;
pr.report({message: `Getting GCC version for ${bin}`});
const exec = await proc.execute(bin, ['-v']).result;
if (exec.retc != 0) {
return null;
}
@ -137,27 +137,27 @@ export async function kitIfCompiler(bin: string, pr?: ProgressReporter): MaybeCo
log.debug('Detected GCC compiler kit:', bin);
if (await fs.exists(gxx_bin)) {
return {
type : 'compilerKit',
name : name,
compilers : {
'CXX' : gxx_bin,
'C' : bin,
type: 'compilerKit',
name: name,
compilers: {
'CXX': gxx_bin,
'C': bin,
}
};
} else {
return {
type : 'compilerKit',
name : name,
compilers : {
'C' : bin,
type: 'compilerKit',
name: name,
compilers: {
'C': bin,
}
};
}
} else if (clang_res) {
log.debug('Testing Clang-ish binary:', bin);
if (pr)
pr.report({message : `Getting Clang version for ${bin}`});
const exec = await proc.execute(bin, [ '-v' ]).result;
pr.report({message: `Getting Clang version for ${bin}`});
const exec = await proc.execute(bin, ['-v']).result;
if (exec.retc != 0) {
return null;
}
@ -174,19 +174,19 @@ export async function kitIfCompiler(bin: string, pr?: ProgressReporter): MaybeCo
log.debug('Detected Clang compiler kit:', bin);
if (await fs.exists(clangxx_bin)) {
return {
type : 'compilerKit',
name : name,
compilers : {
'C' : bin,
'CXX' : clangxx_bin,
type: 'compilerKit',
name: name,
compilers: {
'C': bin,
'CXX': clangxx_bin,
},
};
} else {
return {
type : 'compilerKit',
name : name,
compilers : {
'C' : bin,
type: 'compilerKit',
name: name,
compilers: {
'C': bin,
},
};
}
@ -223,7 +223,7 @@ export async function scanDirForCompilerKits(dir: string, pr?: ProgressReporter)
}
// Get files in the directory
if (pr)
pr.report({message : `Checking ${dir} for compilers...`});
pr.report({message: `Checking ${dir} for compilers...`});
const bins = (await fs.readdir(dir)).map(f => path.join(dir, f));
// Scan each binary in parallel
const prs = bins.map(async bin => {
@ -235,14 +235,14 @@ export async function scanDirForCompilerKits(dir: string, pr?: ProgressReporter)
log.warning('Failed to check binary', bin, 'by exception:', e);
const stat = await fs.stat(bin);
log.debug("File infos: ",
"Mode",
log.debug('File infos: ',
'Mode',
stat.mode,
"isFile",
'isFile',
stat.isFile(),
"isDirectory",
'isDirectory',
stat.isDirectory(),
"isSymbolicLink",
'isSymbolicLink',
stat.isSymbolicLink());
if (e.code == 'EACCES') {
// The binary may not be executable by this user...
@ -250,7 +250,7 @@ export async function scanDirForCompilerKits(dir: string, pr?: ProgressReporter)
} else if (e.code == 'ENOENT') {
// This will happen on Windows if we try to "execute" a directory
return null;
} else if (e.code == "UNKNOWN" && process.platform == "win32") {
} else if (e.code == 'UNKNOWN' && process.platform == 'win32') {
// This is when file is not executable (in windows)
return null;
}
@ -285,7 +285,7 @@ export async function vsInstallations(): Promise<VSInstallation[]> {
const installs = [] as VSInstallation[];
const inst_ids = [] as string[];
const vswhere_exe = path.join(thisExtensionPath(), 'res/vswhere.exe');
const vswhere_args = [ '-all', '-format', 'json', '-products', '*', '-legacy', '-prerelease' ];
const vswhere_args = ['-all', '-format', 'json', '-products', '*', '-legacy', '-prerelease'];
const vswhere_res = await proc.execute(vswhere_exe, vswhere_args).result;
if (vswhere_res.retc !== 0) {
log.error('Failed to execute vswhere.exe:', vswhere_res.stdout);
@ -338,7 +338,7 @@ const MSVC_ENVIRONMENT_VARIABLES = [
async function collectDevBatVars(devbat: string, args: string[]): Promise<Map<string, string>|undefined> {
const bat = [
`@echo off`,
`call "${devbat}" ${args.join(" ")} || exit`,
`call "${devbat}" ${args.join(' ')} || exit`,
];
for (const envvar of MSVC_ENVIRONMENT_VARIABLES) {
bat.push(`echo ${envvar} := %${envvar}%`);
@ -346,14 +346,14 @@ async function collectDevBatVars(devbat: string, args: string[]): Promise<Map<st
const fname = Math.random().toString() + '.bat';
const batpath = path.join(paths.tmpDir, `vs-cmt-${fname}`);
await fs.writeFile(batpath, bat.join('\r\n'));
const res = await proc.execute(batpath, [], null, {shell : true}).result;
const res = await proc.execute(batpath, [], null, {shell: true}).result;
await fs.unlink(batpath);
const output = res.stdout;
if (res.retc !== 0) {
console.log(`Error running ${devbat}`, output);
return;
}
if (output.includes("Invalid host architecture") || output.includes("Error in script usage")) {
if (output.includes('Invalid host architecture') || output.includes('Error in script usage')) {
return;
}
if (!output) {
@ -377,25 +377,25 @@ async function collectDevBatVars(devbat: string, args: string[]): Promise<Map<st
* Platform arguments for VS Generators
*/
const VsArchitectures: {[key: string]: string} = {
'amd64' : 'x64',
'arm' : 'ARM',
'amd64_arm' : 'ARM',
'amd64': 'x64',
'arm': 'ARM',
'amd64_arm': 'ARM',
};
/**
* Preferred CMake VS generators by VS version
*/
const VsGenerators: {[key: string]: string} = {
'14' : 'Visual Studio 14 2015',
'15' : 'Visual Studio 15 2017',
'VS120COMNTOOLS' : 'Visual Studio 12 2013',
'VS140COMNTOOLS' : 'Visual Studio 14 2015',
'14': 'Visual Studio 14 2015',
'15': 'Visual Studio 15 2017',
'VS120COMNTOOLS': 'Visual Studio 12 2013',
'VS140COMNTOOLS': 'Visual Studio 14 2015',
};
async function varsForVSInstallation(inst: VSInstallation, arch: string): Promise<Map<string, string>|null> {
const common_dir = path.join(inst.installationPath, 'Common7', 'Tools');
const devbat = path.join(common_dir, 'VsDevCmd.bat');
const variables = await collectDevBatVars(devbat, [ '-no_logo', `-arch=${arch}` ]);
const variables = await collectDevBatVars(devbat, ['-no_logo', `-arch=${arch}`]);
if (!variables) {
return null;
} else {
@ -414,17 +414,17 @@ async function tryCreateNewVCEnvironment(inst: VSInstallation, arch: string, pr?
const name = installName + ' - ' + arch;
log.debug('Checking for kit: ' + name);
if (pr) {
pr.report({message : `Checking ${installName} with ${arch}`});
pr.report({message: `Checking ${installName} with ${arch}`});
}
const variables = await varsForVSInstallation(inst, arch);
if (!variables)
return null;
const kit: VSKit = {
type : 'vsKit',
name : name,
visualStudio : inst.instanceId,
visualStudioArchitecture : arch,
type: 'vsKit',
name: name,
visualStudio: inst.instanceId,
visualStudioArchitecture: arch,
};
const version = /^(\d+)+./.exec(inst.installationVersion);
@ -432,8 +432,8 @@ async function tryCreateNewVCEnvironment(inst: VSInstallation, arch: string, pr?
const generatorName: string|undefined = VsGenerators[version[1]];
if (generatorName) {
kit.preferredGenerator = {
name : generatorName,
platform : VsArchitectures[arch] as string || undefined,
name: generatorName,
platform: VsArchitectures[arch] as string || undefined,
};
}
}
@ -448,7 +448,7 @@ export async function scanForVSKits(pr?: ProgressReporter): Promise<VSKit[]> {
const installs = await vsInstallations();
const prs = installs.map(async(inst): Promise<VSKit[]> => {
const ret = [] as VSKit[];
const arches = [ 'x86', 'amd64', 'x86_amd64', 'x86_arm', 'amd64_arm', 'amd64_x86' ];
const arches = ['x86', 'amd64', 'x86_amd64', 'x86_arm', 'amd64_arm', 'amd64_x86'];
const sub_prs = arches.map(arch => tryCreateNewVCEnvironment(inst, arch, pr));
const maybe_kits = await Promise.all(sub_prs);
maybe_kits.map(k => k ? ret.push(k) : null);
@ -473,10 +473,10 @@ export async function getVSKitEnvironment(kit: VSKit): Promise<Map<string, strin
*/
export async function scanForKits() {
log.debug('Scanning for Kits on system');
return vscode.window.withProgress({location : vscode.ProgressLocation.Window, title : 'Scanning for kits'},
return vscode.window.withProgress({location: vscode.ProgressLocation.Window, title: 'Scanning for kits'},
async pr => {
const isWin32 = process.platform === 'win32';
pr.report({message : 'Scanning for CMake kits...'});
pr.report({message: 'Scanning for CMake kits...'});
// Search directories on `PATH` for compiler binaries
const pathvar = process.env['PATH']!;
const sep = isWin32 ? ';' : ':';
@ -619,13 +619,13 @@ export class KitManager implements vscode.Disposable {
log.debug('Opening kit selection QuickPick');
const items = this._kits.map((kit): KitItem => {
return {
label : kit.name,
description : descriptionForKit(kit),
kit : kit,
label: kit.name,
description: descriptionForKit(kit),
kit: kit,
};
});
const chosen = await vscode.window.showQuickPick(items, {
placeHolder : 'Select a Kit',
placeHolder: 'Select a Kit',
});
if (chosen === undefined) {
log.debug('User cancelled Kit selection');
@ -723,30 +723,30 @@ export class KitManager implements vscode.Disposable {
if ('compilers' in item_) {
const item = item_ as CompilerKit;
return {
type : 'compilerKit',
name : item.name,
compilers : item.compilers,
preferredGenerator : item.preferredGenerator,
cmakeSettings : item.cmakeSettings,
type: 'compilerKit',
name: item.name,
compilers: item.compilers,
preferredGenerator: item.preferredGenerator,
cmakeSettings: item.cmakeSettings,
};
} else if ('toolchainFile' in item_) {
const item = item_ as ToolchainKit;
return {
type : 'toolchainKit',
name : item.name,
toolchainFile : item.toolchainFile,
preferredGenerator : item.preferredGenerator,
cmakeSettings : item.cmakeSettings,
type: 'toolchainKit',
name: item.name,
toolchainFile: item.toolchainFile,
preferredGenerator: item.preferredGenerator,
cmakeSettings: item.cmakeSettings,
};
} else if ('visualStudio' in item_) {
const item = item_ as VSKit;
return {
type : 'vsKit',
name : item.name,
visualStudio : item.visualStudio,
visualStudioArchitecture : item.visualStudioArchitecture,
preferredGenerator : item.preferredGenerator,
cmakeSettings : item.cmakeSettings,
type: 'vsKit',
name: item.name,
visualStudio: item.visualStudio,
visualStudioArchitecture: item.visualStudioArchitecture,
preferredGenerator: item.preferredGenerator,
cmakeSettings: item.cmakeSettings,
};
} else {
vscode.window.showErrorMessage('Your cmake-kits.json file contains one or more invalid entries.');
@ -777,8 +777,8 @@ export class KitManager implements vscode.Disposable {
const item = await vscode.window.showInformationMessage<DoOpen>(
'CMake Tools has scanned for available kits and saved them to a file. Would you like to edit the Kits file?',
{},
{title : "Yes", doOpen : true},
{title : "No", isCloseAffordance : true, doOpen : false});
{title: 'Yes', doOpen: true},
{title: 'No', isCloseAffordance: true, doOpen: false});
if (item === undefined) {
return;
}

Просмотреть файл

@ -7,10 +7,10 @@ import * as path from 'path';
import * as vscode from 'vscode';
import * as api from './api';
import {CMakeCache} from "./cache";
import {CMakeCache} from './cache';
import {CompilationDatabase} from './compdb';
import {CMakeDriver} from './driver';
import {Kit} from "./kit";
import {Kit} from './kit';
// import * as proc from './proc';
import * as logging from './logging';
import paths from './paths';

Просмотреть файл

@ -119,9 +119,9 @@ async function _openLogFile() {
const logfilepath = path.join(paths.dataDir, 'log.txt');
await fs.mkdir_p(path.dirname(logfilepath));
if (await fs.exists(logfilepath)) {
return node_fs.createWriteStream(logfilepath, {flags : 'r+'});
return node_fs.createWriteStream(logfilepath, {flags: 'r+'});
} else {
return node_fs.createWriteStream(logfilepath, {flags : 'w'});
return node_fs.createWriteStream(logfilepath, {flags: 'w'});
}
})();
}
@ -150,17 +150,17 @@ class SingletonLogger {
case LogLevel.Note:
if (process.env['CMT_QUIET_CONSOLE'] !== '1') {
// tslint:disable-next-line
console.info("[CMakeTools]", raw_message);
console.info('[CMakeTools]', raw_message);
}
break;
case LogLevel.Warning:
// tslint:disable-next-line
console.warn("[CMakeTools]", raw_message);
console.warn('[CMakeTools]', raw_message);
break;
case LogLevel.Error:
case LogLevel.Fatal:
// tslint:disable-next-line
console.error("[CMakeTools]", raw_message);
console.error('[CMakeTools]', raw_message);
break;
}
// Write to the logfile asynchronously.

Просмотреть файл

@ -29,36 +29,36 @@ export interface Nag {
}
export function parseNagData(items: any): Nag[]|null {
const validator = new ajv({allErrors : true, format : 'full'}).compile({
type : 'object',
properties : {
nags : {
type : 'array',
items : {
type : 'object',
properties : {
message : {type : 'string'},
id : {type : 'string'},
resetSeconds : {type : 'number'},
items : {
type : 'array',
items : {
type : 'object',
properties : {
title : {type : 'string'},
isCloseAffordance : {type : 'boolean'},
openLink : {type : 'string'},
askLater : {type : 'boolean'},
neverAgain : {type : 'boolean'},
const validator = new ajv({allErrors: true, format: 'full'}).compile({
type: 'object',
properties: {
nags: {
type: 'array',
items: {
type: 'object',
properties: {
message: {type: 'string'},
id: {type: 'string'},
resetSeconds: {type: 'number'},
items: {
type: 'array',
items: {
type: 'object',
properties: {
title: {type: 'string'},
isCloseAffordance: {type: 'boolean'},
openLink: {type: 'string'},
askLater: {type: 'boolean'},
neverAgain: {type: 'boolean'},
},
required : [
required: [
'title',
'isCloseAffordance',
],
},
},
},
required : [
required: [
'message',
'items',
'id',
@ -67,7 +67,7 @@ export function parseNagData(items: any): Nag[]|null {
},
},
},
required : [
required: [
'nags',
],
});
@ -97,7 +97,7 @@ export function parseNagYAML(str: string): Nag[]|null {
interface NagState {
nagsByID: {
[id: string]: undefined|{
nextShowTimeMS : number,
nextShowTimeMS: number,
neverAgain: boolean,
};
};
@ -112,7 +112,7 @@ function getOrInitNagState(ext: vscode.ExtensionContext): NagState {
return state;
}
const init_state: NagState = {
nagsByID : {
nagsByID: {
}
};
@ -190,14 +190,14 @@ export class NagManager {
if (chosen.askLater) {
// We'll ask again when the reset timer is met
state.nagsByID[nag.id] = {
neverAgain : false,
nextShowTimeMS : next_time_ms,
neverAgain: false,
nextShowTimeMS: next_time_ms,
};
} else if (chosen.neverAgain) {
// User doesn't want to be bothered again
state.nagsByID[nag.id] = {
neverAgain : true, // Prevents this nag from ever reappearing
nextShowTimeMS : next_time_ms,
neverAgain: true, // Prevents this nag from ever reappearing
nextShowTimeMS: next_time_ms,
};
}
if (chosen.openLink) {

Просмотреть файл

@ -25,7 +25,7 @@ class Paths {
if (process.platform == 'win32') {
return process.env['AppData']!;
} else {
const xdg_dir = process.env["XDG_DATA_HOME"];
const xdg_dir = process.env['XDG_DATA_HOME'];
if (xdg_dir) {
return xdg_dir;
}
@ -57,7 +57,7 @@ class Paths {
if (err) {
resolve(null);
} else {
console.assert(resolved, "`which` didn't do what it should have.");
console.assert(resolved, '`which` didn\'t do what it should have.');
resolve(resolved!);
}
});

Просмотреть файл

@ -56,14 +56,14 @@ export async function mkdir_p(fspath: string): Promise<void> {
await mkdir_p(parent);
} else {
if (!(await stat(parent)).isDirectory()) {
throw new Error("Cannot create ${fspath}: ${parent} is a non-directory");
throw new Error('Cannot create ${fspath}: ${parent} is a non-directory');
}
}
if (!await exists(fspath)) {
await mkdir(fspath);
} else {
if (!(await stat(fspath)).isDirectory()) {
throw new Error("Cannot mkdir_p on ${fspath}. It exists, and is not a directory!");
throw new Error('Cannot mkdir_p on ${fspath}. It exists, and is not a directory!');
}
}
}

Просмотреть файл

@ -93,7 +93,7 @@ export function execute(command: string,
// We do simple quoting of arguments with spaces.
// This is only shown to the user,
// and doesn't have to be 100% correct.
+ [ command ]
+ [command]
.concat(args)
.map(a => a.replace('"', '\"'))
.map(a => /[ \n\r\f;\t]/.test(a) ? `"${a}"` : a)
@ -104,8 +104,8 @@ export function execute(command: string,
}
const final_env = util.mergeEnvironment(process.env as EnvironmentVariables, options.environment || {});
const spawn_opts: proc.SpawnOptions = {
env : final_env,
shell : !!options.shell,
env: final_env,
shell: !!options.shell,
};
if (options && options.cwd) {
spawn_opts.cwd = options.cwd;
@ -158,7 +158,7 @@ export function execute(command: string,
if (stderr_line_acc && outputConsumer) {
outputConsumer.error(stderr_line_acc);
}
resolve({retc : retc, stdout : stdout_acc, stderr : stderr_acc});
resolve({retc: retc, stdout: stdout_acc, stderr: stderr_acc});
});
});
return {child, result};

Просмотреть файл

@ -16,13 +16,13 @@ class RollbarController {
/**
* The payload to send with any messages. Can be updated via `updatePayload`.
*/
private readonly _payload: object = {platform : 'client'};
private readonly _payload: object = {platform: 'client'};
/**
* The Rollbar client instance we use to communicate.
*/
private readonly _rollbar = new Rollbar({
accessToken : '14d411d713be4a5a9f9d57660534cac7',
accessToken: '14d411d713be4a5a9f9d57660534cac7',
reportLevel: 'error',
payload: this._payload,
});
@ -59,14 +59,14 @@ class RollbarController {
log.debug('Asking user for permission to user Rollbar...');
// We haven't asked yet. Ask them now:
const item = await vscode.window.showInformationMessage(
"Would you like to opt-in to send anonymous error and exception data to help improve CMake Tools?",
'Would you like to opt-in to send anonymous error and exception data to help improve CMake Tools?',
{
title : 'Yes!',
isCloseAffordance : false,
title: 'Yes!',
isCloseAffordance: false,
} as vscode.MessageItem,
{
title : 'No Thanks',
isCloseAffordance : true,
title: 'No Thanks',
isCloseAffordance: true,
} as vscode.MessageItem);
if (item === undefined) {
@ -109,7 +109,7 @@ class RollbarController {
debugger;
if (this._enabled) {
const stack = new Error().stack;
return this._rollbar.error(what, additional, {stack : stack});
return this._rollbar.error(what, additional, {stack: stack});
}
return null;
}
@ -121,7 +121,7 @@ class RollbarController {
*/
updatePayload(data: object) {
Object.assign(this._payload, data);
this._rollbar.configure({payload : this._payload});
this._rollbar.configure({payload: this._payload});
log.debug('Updated Rollbar payload', JSON.stringify(data));
}

Просмотреть файл

@ -1,11 +1,11 @@
import * as ajv from 'ajv';
import * as path from 'path';
import {fs} from "./pr";
import {thisExtensionPath} from "./util";
import {fs} from './pr';
import {thisExtensionPath} from './util';
export async function loadSchema(filepath: string): Promise<ajv.ValidateFunction> {
const schema_path = path.isAbsolute(filepath) ? filepath : path.join(thisExtensionPath(), filepath);
const schema_data = JSON.parse((await fs.readFile(schema_path)).toString());
return new ajv({allErrors : true, format : 'full'}).compile(schema_data);
return new ajv({allErrors: true, format: 'full'}).compile(schema_data);
}

Просмотреть файл

@ -41,7 +41,7 @@ export class StateManager {
* The keyword settings for the build variant
*/
get activeVariantSettings(): Map<string, string>|null {
const pairs = this.extensionContext.workspaceState.get<[ string, string ][]>('activeVariantSettings');
const pairs = this.extensionContext.workspaceState.get<[string, string][]>('activeVariantSettings');
if (pairs) {
return new Map<string, string>(pairs);
} else {
@ -50,7 +50,7 @@ export class StateManager {
}
set activeVariantSettings(settings: Map<string, string>|null) {
if (settings) {
const pairs: [ string, string ][] = Array.from(settings.entries());
const pairs: [string, string][] = Array.from(settings.entries());
this.extensionContext.workspaceState.update('activeVariantSettings', pairs);
} else {
this.extensionContext.workspaceState.update('activeVariantSettings', null);

Просмотреть файл

@ -1,5 +1,5 @@
import * as vscode from 'vscode';
import {BasicTestResults} from "./ctest";
import {BasicTestResults} from './ctest';
interface Hideable {
show(): void;

Просмотреть файл

@ -63,7 +63,7 @@ export function normalizePath(p: string, normalize_case = true): string {
*/
export function isTruthy(value: (boolean|string|null|undefined|number)) {
if (typeof value === 'string') {
return !([ '', 'FALSE', 'OFF', '0', 'NOTFOUND', 'NO', 'N', 'IGNORE' ].indexOf(value) >= 0
return !(['', 'FALSE', 'OFF', '0', 'NOTFOUND', 'NO', 'N', 'IGNORE'].indexOf(value) >= 0
|| value.endsWith('-NOTFOUND'));
}
// Numbers/bools/etc. follow common C-style truthiness
@ -75,8 +75,8 @@ export function isTruthy(value: (boolean|string|null|undefined|number)) {
* `getOwnPropertyNames`
* @param obj The object to iterate
*/
export function objectPairs<V>(obj: {[key: string]: V}): [ string, V ][] {
return Object.getOwnPropertyNames(obj).map(key => ([ key, obj[key] ] as [string, V]));
export function objectPairs<V>(obj: {[key: string]: V}): [string, V][] {
return Object.getOwnPropertyNames(obj).map(key => ([key, obj[key]] as [string, V]));
}
/**
@ -132,8 +132,8 @@ export interface CMakeValue {
export function cmakeify(value: (string|boolean|number|string[])): CMakeValue {
const ret: CMakeValue = {
type : 'UNKNOWN',
value : '',
type: 'UNKNOWN',
value: '',
};
if (value === true || value === false) {
ret.type = 'BOOL';
@ -166,7 +166,7 @@ export async function termProc(child: child_process.ChildProcess) {
async function _killTree(pid: number) {
if (process.platform !== 'win32') {
let children: number[] = [];
const stdout = (await execute('pgrep', [ '-P', pid.toString() ], null, {silent : true}).result).stdout.trim();
const stdout = (await execute('pgrep', ['-P', pid.toString()], null, {silent: true}).result).stdout.trim();
if (!!stdout.length) {
children = stdout.split('\n').map(line => Number.parseInt(line));
}
@ -217,9 +217,9 @@ export function parseVersion(str: string): Version {
}
const [, major, minor, patch] = mat;
return {
major : parseInt(major),
minor : parseInt(minor),
patch : parseInt(patch),
major: parseInt(major),
minor: parseInt(minor),
patch: parseInt(patch),
};
}
@ -266,12 +266,12 @@ export function mergeEnvironment(...env: EnvironmentVariables[]) {
}, {});
}
export function parseCompileDefinition(str: string): [ string, string|null ] {
export function parseCompileDefinition(str: string): [string, string|null] {
if (/^\w+$/.test(str)) {
return [ str, null ];
return [str, null];
} else {
const key = str.split('=', 1)[0];
return [ key, str.substr(key.length + 1) ];
return [key, str.substr(key.length + 1)];
}
}

Просмотреть файл

@ -5,9 +5,9 @@ import * as path from 'path';
import * as vscode from 'vscode';
import * as logging from './logging';
import {fs} from "./pr";
import {fs} from './pr';
import rollbar from './rollbar';
import {loadSchema} from "./schema";
import {loadSchema} from './schema';
import {StateManager} from './state';
import * as util from './util';
import {MultiWatcher} from './watcher';
@ -42,33 +42,33 @@ export interface VariantCombination extends vscode.QuickPickItem {
}
export interface VariantFileContent {
[key: string]: {default: string; description : string; choices : {[name: string] : VariantConfigurationOptions;};};
[key: string]: {default: string; description: string; choices: {[name: string]: VariantConfigurationOptions;};};
}
export const DEFAULT_VARIANTS: VariantFileContent = {
buildType : {
default : 'debug',
description : 'The build type',
choices : {
debug : {
short : 'Debug',
long : 'Emit debug information without performing optimizations',
buildType : 'Debug',
buildType: {
default: 'debug',
description: 'The build type',
choices: {
debug: {
short: 'Debug',
long: 'Emit debug information without performing optimizations',
buildType: 'Debug',
},
release : {
short : 'Release',
long : 'Enable optimizations, omit debug info',
buildType : 'Release',
release: {
short: 'Release',
long: 'Enable optimizations, omit debug info',
buildType: 'Release',
},
minsize : {
short : 'MinSizeRel',
long : 'Optimize for smallest binary size',
buildType : 'MinSizeRel',
minsize: {
short: 'MinSizeRel',
long: 'Optimize for smallest binary size',
buildType: 'MinSizeRel',
},
reldeb : {
short : 'RelWithDebInfo',
long : 'Perform optimizations AND include debugging information',
buildType : 'RelWithDebInfo',
reldeb: {
short: 'RelWithDebInfo',
long: 'Perform optimizations AND include debugging information',
buildType: 'RelWithDebInfo',
}
}
}
@ -186,16 +186,16 @@ export class VariantManager implements vscode.Disposable {
}
sets.set(setting_name, {
default_ : def,
description : desc,
choices : choices,
default_: def,
description: desc,
choices: choices,
});
}
if (loaded_default) {
log.info("Loaded default variants");
log.info('Loaded default variants');
} else {
log.info("Loaded new set of variants");
log.info('Loaded new set of variants');
}
@ -207,8 +207,8 @@ export class VariantManager implements vscode.Disposable {
variantConfigurationOptionsForKWs(keywordSetting: Map<string, string>): VariantConfigurationOptions[]|string {
const vars = this._variants;
let error: string|undefined = undefined;
const data = Array.from(keywordSetting.entries()).map(([ param, setting ]): VariantConfigurationOptions => {
let choice: VariantConfigurationOptions = {short : 'Unknown'};
const data = Array.from(keywordSetting.entries()).map(([param, setting]): VariantConfigurationOptions => {
let choice: VariantConfigurationOptions = {short: 'Unknown'};
if (vars.has(param)) {
const choices = vars.get(param)!.choices;
@ -231,23 +231,23 @@ export class VariantManager implements vscode.Disposable {
}
mergeVariantConfigurations(options: VariantConfigurationOptions[]): VariantConfigurationOptions {
const init: VariantConfigurationOptions = {short : '', long : '', settings : {}};
const init: VariantConfigurationOptions = {short: '', long: '', settings: {}};
return options.reduce((acc, el) => ({
buildType : el.buildType || acc.buildType,
generator : el.generator || acc.generator,
linkage : el.linkage || acc.linkage,
toolset : el.toolset || acc.toolset,
settings : {...acc.settings, ...el.settings},
short : [ acc.short, el.short ].join(' ').trim(),
long : [ acc.long, el.long ].join(', '),
buildType: el.buildType || acc.buildType,
generator: el.generator || acc.generator,
linkage: el.linkage || acc.linkage,
toolset: el.toolset || acc.toolset,
settings: {...acc.settings, ...el.settings},
short: [acc.short, el.short].join(' ').trim(),
long: [acc.long, el.long].join(', '),
}),
init);
}
get activeVariantOptions(): VariantConfigurationOptions {
const invalid_variant = {
short : 'Unknown',
long : 'Unknwon',
short: 'Unknown',
long: 'Unknwon',
};
const kws = this.stateManager.activeVariantSettings;
if (!kws) {
@ -260,10 +260,10 @@ export class VariantManager implements vscode.Disposable {
let options_or_error = this.variantConfigurationOptionsForKWs(kws);
if (typeof options_or_error === 'string') {
log.warning("Last variant selection is incompatible with present variant definition.");
log.warning(">> " + options_or_error);
log.warning('Last variant selection is incompatible with present variant definition.');
log.warning('>> ' + options_or_error);
log.warning("Using default variant choices from variant definition.");
log.warning('Using default variant choices from variant definition.');
const defaultKws = this.findDefaultChoiceCombination();
options_or_error = this.variantConfigurationOptionsForKWs(defaultKws);
}
@ -279,16 +279,15 @@ export class VariantManager implements vscode.Disposable {
async selectVariant() {
const variants
= Array.from(this._variants.entries())
.map(
([ key, variant ]) => Array.from(variant.choices.entries())
.map(([ value_name, value ]) => (
{settingKey : key, settingValue : value_name, settings : value})));
.map(([key, variant]) => Array.from(variant.choices.entries())
.map(([value_name, value]) => (
{settingKey: key, settingValue: value_name, settings: value})));
const product = util.product(variants);
const items: VariantCombination[]
= product.map(optionset => ({
label : optionset.map(o => o.settings.short).join(' + '),
keywordSettings : this.transformChoiceCombinationToKeywordSettings(optionset),
description : optionset.map(o => o.settings.long).join(' + '),
label: optionset.map(o => o.settings.short).join(' + '),
keywordSettings: this.transformChoiceCombinationToKeywordSettings(optionset),
description: optionset.map(o => o.settings.long).join(' + '),
}));
const chosen = await vscode.window.showQuickPick(items);
if (!chosen) {
@ -311,9 +310,9 @@ export class VariantManager implements vscode.Disposable {
}
findDefaultChoiceCombination(): Map<string, string> {
const defaults = util.map(this._variants.entries(), ([ option, definition ]) => ({
settingKey : option,
settingValue : definition.default_,
const defaults = util.map(this._variants.entries(), ([option, definition]) => ({
settingKey: option,
settingValue: definition.default_,
}));
return this.transformChoiceCombinationToKeywordSettings(Array.from(defaults));
}

Просмотреть файл

@ -15,8 +15,8 @@ let testRunner = require('vscode/lib/testrunner');
// You can directly control Mocha options by uncommenting the following lines
// See https://github.com/mochajs/mocha/wiki/Using-mocha-programmatically#set-options for more info
testRunner.configure({
ui : 'tdd', // the TDD UI is being used in extension.test.ts (suite, test, etc.)
useColors : true // colored output from test results
ui: 'tdd', // the TDD UI is being used in extension.test.ts (suite, test, etc.)
useColors: true // colored output from test results
});
module.exports = testRunner;

Просмотреть файл

@ -15,8 +15,8 @@ let testRunner = require('vscode/lib/testrunner');
// You can directly control Mocha options by uncommenting the following lines
// See https://github.com/mochajs/mocha/wiki/Using-mocha-programmatically#set-options for more info
testRunner.configure({
ui : 'tdd', // the TDD UI is being used in extension.test.ts (suite, test, etc.)
useColors : true // colored output from test results
ui: 'tdd', // the TDD UI is being used in extension.test.ts (suite, test, etc.)
useColors: true // colored output from test results
});
module.exports = testRunner;

Просмотреть файл

@ -7,13 +7,13 @@ import paths from '../src/paths';
import {fs} from '../src/pr';
export async function clearExistingKitConfigurationFile() {
await fs.writeFile(path.join(paths.dataDir, 'cmake-kits.json'), "[]");
await fs.writeFile(path.join(paths.dataDir, 'cmake-kits.json'), '[]');
}
export async function getExtension() {
const cmt = vscode.extensions.getExtension<CMakeTools>('vector-of-bool.cmake-tools');
if (!cmt) {
throw new Error("Extension doesn't exist");
throw new Error('Extension doesn\'t exist');
}
return cmt.isActive ? Promise.resolve(cmt.exports) : cmt.activate();
}

Просмотреть файл

@ -17,9 +17,9 @@ function getTestResourceFilePath(filename: string): string {
}
suite('Cache test', async () => {
test("Read CMake Cache", async () => {
test('Read CMake Cache', async () => {
const cache = await CMakeCache.fromPath(getTestResourceFilePath('TestCMakeCache.txt'));
const generator = cache.get("CMAKE_GENERATOR") as api.CacheEntry;
const generator = cache.get('CMAKE_GENERATOR') as api.CacheEntry;
expect(generator.type).to.eq(api.CacheEntryType.Internal);
expect(generator.key).to.eq('CMAKE_GENERATOR');
expect(generator.as<string>()).to.eq('Ninja');
@ -29,9 +29,9 @@ suite('Cache test', async () => {
expect(build_testing.type).to.eq(api.CacheEntryType.Bool);
expect(build_testing.as<boolean>()).to.be.true;
});
test("Read cache with various newlines", async () => {
test('Read cache with various newlines', async () => {
for (const newline of ['\n', '\r\n', '\r']) {
const str = [ '# This line is ignored', '// This line is docs', 'SOMETHING:STRING=foo', '' ].join(newline);
const str = ['# This line is ignored', '// This line is docs', 'SOMETHING:STRING=foo', ''].join(newline);
const entries = CMakeCache.parseCache(str);
expect(entries.size).to.eq(1);
expect(entries.has('SOMETHING')).to.be.true;
@ -60,7 +60,7 @@ suite('Cache test', async () => {
}
});
test('Truthy values', () => {
const true_things = [ '1', 'ON', 'YES', 'Y', '112', 12, 'SOMETHING' ];
const true_things = ['1', 'ON', 'YES', 'Y', '112', 12, 'SOMETHING'];
for (const thing of true_things) {
expect(util.isTruthy(thing), `Check truthiness of ${thing}`).to.be.true;
}

Просмотреть файл

@ -21,21 +21,21 @@ suite('Compilation info', () => {
const dbpath = getTestResourceFilePath('test_compdb.json');
const db = (await compdb.CompilationDatabase.fromFilePath(dbpath))!;
expect(db).to.not.be.null;
const source_path = "/home/clang-languageservice/main.cpp";
const source_path = '/home/clang-languageservice/main.cpp';
const info = db.getCompilationInfoForUri(vscode.Uri.file(source_path))!;
expect(info).to.not.be.null;
expect(info.file).to.eq(source_path);
expect(info.compile!.directory).to.eq('/home/clang-languageservice/build');
expect(info.compile!.command)
.to.eq(
"/usr/local/bin/clang++ -DBOOST_THREAD_VERSION=3 -isystem ../extern/nlohmann-json/src -g -std=gnu++11 -o CMakeFiles/clang-languageservice.dir/main.cpp.o -c /home/clang-languageservice/main.cpp");
'/usr/local/bin/clang++ -DBOOST_THREAD_VERSION=3 -isystem ../extern/nlohmann-json/src -g -std=gnu++11 -o CMakeFiles/clang-languageservice.dir/main.cpp.o -c /home/clang-languageservice/main.cpp');
});
test('Parsing gnu-style compile info', () => {
const raw: api.RawCompilationInfo = {
command :
command:
'clang++ -I/foo/bar -isystem /system/path -fsome-compile-flag -DMACRO=DEFINITION -I ../relative/path "-I/path\\"with\\" embedded quotes/foo"',
directory : '/some/dir',
file : 'meow.cpp'
directory: '/some/dir',
file: 'meow.cpp'
};
const info = compdb.parseRawCompilationInfo(raw);
expect(raw.command).to.eq(info.compile!.command);
@ -59,10 +59,10 @@ suite('Compilation info', () => {
test('Parsing MSVC-style compile info', () => {
const raw: api.RawCompilationInfo = {
command :
command:
'cl.exe -I/foo/bar /I/system/path /Z+:some-compile-flag /DMACRO=DEFINITION -I ../relative/path "/I/path\\"with\\" embedded quotes/foo"',
directory : '/some/dir',
file : 'meow.cpp'
directory: '/some/dir',
file: 'meow.cpp'
};
const info = compdb.parseRawCompilationInfo(raw);
expect(raw.command).to.eq(info.compile!.command);

Просмотреть файл

@ -21,7 +21,7 @@ function feedLines(consumer: OutputConsumer, output: string[], error: string[])
}
function toLowerCaseForWindows(str: string): string {
if (process.platform == "win32") {
if (process.platform == 'win32') {
return str.toLowerCase();
} else {
return str;
@ -29,11 +29,11 @@ function toLowerCaseForWindows(str: string): string {
}
suite('Diagnostics', async () => {
let consumer = new diags.CMakeOutputConsumer("dummyPath");
let consumer = new diags.CMakeOutputConsumer('dummyPath');
let build_consumer = new diags.CompileOutputConsumer();
setup(() => {
// FIXME: SETUP IS NOT BEING CALLED
consumer = new diags.CMakeOutputConsumer("dummyPath");
consumer = new diags.CMakeOutputConsumer('dummyPath');
build_consumer = new diags.CompileOutputConsumer();
});
test('Waring-free CMake output', async () => {
@ -103,7 +103,7 @@ suite('Diagnostics', async () => {
expect(consumer.diagnostics.length).to.eq(1);
const warning = consumer.diagnostics[0];
expect(warning.diag.severity).to.eq(vscode.DiagnosticSeverity.Warning);
expect(warning.diag.message).to.eq("I'm an inner warning");
expect(warning.diag.message).to.eq('I\'m an inner warning');
expect(warning.diag.range.start.line).to.eq(14);
expect(warning.diag.source).to.eq('CMake (message)');
});
@ -122,7 +122,7 @@ suite('Diagnostics', async () => {
expect(consumer.diagnostics.length).to.eq(1);
const warning = consumer.diagnostics[0];
expect(warning.diag.severity).to.eq(vscode.DiagnosticSeverity.Warning);
expect(warning.diag.message).to.eq("I'm an inner warning");
expect(warning.diag.message).to.eq('I\'m an inner warning');
expect(warning.diag.range.start.line).to.eq(14);
expect(warning.diag.source).to.eq('CMake (message)');
});
@ -166,7 +166,7 @@ suite('Diagnostics', async () => {
});
test('Parse more GCC diagnostics', () => {
const lines = [ `/Users/Tobias/Code/QUIT/Source/qidespot1.cpp:303:49: error: expected ';' after expression` ];
const lines = [`/Users/Tobias/Code/QUIT/Source/qidespot1.cpp:303:49: error: expected ';' after expression`];
feedLines(build_consumer, [], lines);
expect(build_consumer.gccDiagnostics).to.have.length(1);
const diag = build_consumer.gccDiagnostics[0];
@ -178,7 +178,7 @@ suite('Diagnostics', async () => {
});
test('Parsing fatal error diagnostics', () => {
const lines = [ '/some/path/here:4:26: fatal error: some_header.h: No such file or directory' ];
const lines = ['/some/path/here:4:26: fatal error: some_header.h: No such file or directory'];
feedLines(build_consumer, [], lines);
expect(build_consumer.gccDiagnostics).to.have.length(1);
const diag = build_consumer.gccDiagnostics[0];
@ -193,8 +193,7 @@ suite('Diagnostics', async () => {
});
test('Parsing fatal error diagnostics in french', () => {
const lines =
[ '/home/romain/TL/test/base.c:2:21: erreur fatale : bonjour.h : Aucun fichier ou dossier de ce type' ];
const lines = ['/home/romain/TL/test/base.c:2:21: erreur fatale : bonjour.h : Aucun fichier ou dossier de ce type'];
feedLines(build_consumer, [], lines);
expect(build_consumer.gccDiagnostics).to.have.length(1);
const diag = build_consumer.gccDiagnostics[0];
@ -208,13 +207,13 @@ suite('Diagnostics', async () => {
expect(path.posix.isAbsolute(diag.file)).to.be.true;
});
test('Parsing warning diagnostics', () => {
const lines = [ "/some/path/here:4:26: warning: unused parameter 'data'" ];
const lines = ['/some/path/here:4:26: warning: unused parameter \'data\''];
feedLines(build_consumer, [], lines);
expect(build_consumer.gccDiagnostics).to.have.length(1);
const diag = build_consumer.gccDiagnostics[0];
expect(diag.location.start.line).to.eq(3);
expect(diag.message).to.eq("unused parameter 'data'");
expect(diag.message).to.eq('unused parameter \'data\'');
expect(diag.location.start.character).to.eq(25);
expect(diag.file).to.eq('/some/path/here');
expect(diag.severity).to.eq('warning');
@ -222,7 +221,7 @@ suite('Diagnostics', async () => {
expect(path.posix.isAbsolute(diag.file)).to.be.true;
});
test('Parsing warning diagnostics 2', () => {
const lines = [ `/test/main.cpp:21:14: warning: unused parameter v [-Wunused-parameter]` ];
const lines = [`/test/main.cpp:21:14: warning: unused parameter v [-Wunused-parameter]`];
feedLines(build_consumer, [], lines);
expect(build_consumer.gccDiagnostics).to.have.length(1);
const diag = build_consumer.gccDiagnostics[0];
@ -234,7 +233,7 @@ suite('Diagnostics', async () => {
expect(diag.severity).to.eq('warning');
});
test('Parsing warning diagnostics in french', () => {
const lines = [ '/home/romain/TL/test/base.c:155:2: attention : déclaration implicite de la fonction create' ];
const lines = ['/home/romain/TL/test/base.c:155:2: attention : déclaration implicite de la fonction create'];
feedLines(build_consumer, [], lines);
expect(build_consumer.gccDiagnostics).to.have.length(1);
const diag = build_consumer.gccDiagnostics[0];
@ -248,26 +247,26 @@ suite('Diagnostics', async () => {
expect(path.posix.isAbsolute(diag.file)).to.be.true;
});
test('Parsing linker error', () => {
const lines = [ "/some/path/here:101: undefined reference to `some_function'" ];
const lines = ['/some/path/here:101: undefined reference to `some_function\''];
feedLines(build_consumer, [], lines);
expect(build_consumer.gnuLDDiagnostics).to.have.length(1);
const diag = build_consumer.gnuLDDiagnostics[0];
expect(diag.location.start.line).to.eq(100);
expect(diag.message).to.eq("undefined reference to `some_function'");
expect(diag.message).to.eq('undefined reference to `some_function\'');
expect(diag.file).to.eq('/some/path/here');
expect(diag.severity).to.eq('error');
expect(path.posix.normalize(diag.file)).to.eq(diag.file);
expect(path.posix.isAbsolute(diag.file)).to.be.true;
});
test('Parsing linker error in french', () => {
const lines = [ "/home/romain/TL/test/test_fa_tp4.c:9 : référence indéfinie vers « create_automaton_product56 »" ];
const lines = ['/home/romain/TL/test/test_fa_tp4.c:9 : référence indéfinie vers « create_automaton_product56 »'];
feedLines(build_consumer, [], lines);
expect(build_consumer.gnuLDDiagnostics).to.have.length(1);
const diag = build_consumer.gnuLDDiagnostics[0];
expect(diag.location.start.line).to.eq(8);
expect(diag.message).to.eq("référence indéfinie vers « create_automaton_product56 »");
expect(diag.message).to.eq('référence indéfinie vers « create_automaton_product56 »');
expect(diag.file).to.eq('/home/romain/TL/test/test_fa_tp4.c');
expect(diag.severity).to.eq('error');
expect(path.posix.normalize(diag.file)).to.eq(diag.file);
@ -306,7 +305,7 @@ suite('Diagnostics', async () => {
expect(path.win32.isAbsolute(diag.file)).to.be.true;
});
test('Parsing GHS Diagnostics fatal error', () => {
const lines = [ '"C:\\path\\source\\debug\\debug.c", line 631 (col. 3): fatal error #68: some fatal error' ];
const lines = ['"C:\\path\\source\\debug\\debug.c", line 631 (col. 3): fatal error #68: some fatal error'];
feedLines(build_consumer, [], lines);
expect(build_consumer.ghsDiagnostics).to.have.length(1);
const diag = build_consumer.ghsDiagnostics[0];

Просмотреть файл

@ -15,8 +15,8 @@ let testRunner = require('vscode/lib/testrunner');
// You can directly control Mocha options by uncommenting the following lines
// See https://github.com/mochajs/mocha/wiki/Using-mocha-programmatically#set-options for more info
testRunner.configure({
ui : 'tdd', // the TDD UI is being used in extension.test.ts (suite, test, etc.)
useColors : true // colored output from test results
ui: 'tdd', // the TDD UI is being used in extension.test.ts (suite, test, etc.)
useColors: true // colored output from test results
});
module.exports = testRunner;

Просмотреть файл

@ -30,10 +30,10 @@ function getTestResourceFilePath(filename: string): string {
function getResourcePath(filename: string): string { return path.normalize(path.join(here, '../../..', filename)); }
function getPathWithoutCompilers() {
if (process.arch == "win32") {
return "C:\\TMP";
if (process.arch == 'win32') {
return 'C:\\TMP';
} else {
return "/tmp";
return '/tmp';
}
}
@ -84,7 +84,7 @@ suite('Kits scan test', async () => {
suite('Scan directory', async () => {
let path_with_compilername = '';
setup(async () => { path_with_compilername = path.join(fakebin, "gcc-4.3.2"); });
setup(async () => { path_with_compilername = path.join(fakebin, 'gcc-4.3.2'); });
teardown(async () => {
if (await fs.exists(path_with_compilername)) {
await fs.rmdir(path_with_compilername);
@ -117,8 +117,8 @@ suite('Kits scan test', async () => {
km = new kit.KitManager(stateMock, path_rescan_kit);
// Mock showInformationMessage to suppress needed user choice
sandbox.stub(vscode.window, "showInformationMessage")
.callsFake(() => ({title : "No", isCloseAffordance : true, doOpen : false}));
sandbox.stub(vscode.window, 'showInformationMessage')
.callsFake(() => ({title: 'No', isCloseAffordance: true, doOpen: false}));
path_backup = process.env.PATH;
});
@ -137,7 +137,7 @@ suite('Kits scan test', async () => {
const kitFile = json5.parse(rawKitsFromFile);
const schema = json5.parse(await fs.readFile(getResourcePath('schemas/kits-schema.json'), 'utf8'));
const validator = new ajv({allErrors : true, format : 'full'}).compile(schema);
const validator = new ajv({allErrors: true, format: 'full'}).compile(schema);
expect(validator(kitFile)).to.be.true;
return kitFile;
@ -179,7 +179,7 @@ suite('Kits scan test', async () => {
});
test('check fake compilers in kit file', async () => {
process.env['PATH'] = getTestRootFilePath("fakebin");
process.env['PATH'] = getTestRootFilePath('fakebin');
await km.initialize();
@ -189,7 +189,7 @@ suite('Kits scan test', async () => {
}).timeout(10000);
test('check check combination of scan and old kits', async () => {
process.env['PATH'] = getTestRootFilePath("fakebin");
process.env['PATH'] = getTestRootFilePath('fakebin');
await fs.copyFile(getTestResourceFilePath('test_kit.json'), path_rescan_kit);
await km.initialize();
@ -197,14 +197,14 @@ suite('Kits scan test', async () => {
const names = km.kits.map(item => item.name);
expect(names).to.contains("CompilerKit 1");
expect(names).to.contains("CompilerKit 2");
expect(names).to.contains("CompilerKit 3 with PreferedGenerator");
expect(names).to.contains("ToolchainKit 1");
expect(names).to.contains("VSCode Kit 1");
expect(names).to.contains("VSCode Kit 2");
expect(names).to.contains("Clang 0.25");
expect(names).to.contains("GCC 42.1");
expect(names).to.contains('CompilerKit 1');
expect(names).to.contains('CompilerKit 2');
expect(names).to.contains('CompilerKit 3 with PreferedGenerator');
expect(names).to.contains('ToolchainKit 1');
expect(names).to.contains('VSCode Kit 1');
expect(names).to.contains('VSCode Kit 2');
expect(names).to.contains('Clang 0.25');
expect(names).to.contains('GCC 42.1');
}).timeout(10000);
});
});

Просмотреть файл

@ -35,9 +35,9 @@ suite('Kits test', async () => {
test('KitManager tests opening of kit file', async () => {
let text: vscode.TextDocument|undefined;
gui_sandbox.stub(vscode.window, "showTextDocument").callsFake(textDoc => {
gui_sandbox.stub(vscode.window, 'showTextDocument').callsFake(textDoc => {
text = textDoc;
return {document : textDoc};
return {document: textDoc};
});
await km.initialize();
@ -81,12 +81,12 @@ suite('Kits test', async () => {
await km.initialize();
expect(km.kits.length).to.eq(6);
expect(km.kits[0].name).to.eq("CompilerKit 1");
expect(km.kits[1].name).to.eq("CompilerKit 2");
expect(km.kits[2].name).to.eq("CompilerKit 3 with PreferedGenerator");
expect(km.kits[3].name).to.eq("ToolchainKit 1");
expect(km.kits[4].name).to.eq("VSCode Kit 1");
expect(km.kits[5].name).to.eq("VSCode Kit 2");
expect(km.kits[0].name).to.eq('CompilerKit 1');
expect(km.kits[1].name).to.eq('CompilerKit 2');
expect(km.kits[2].name).to.eq('CompilerKit 3 with PreferedGenerator');
expect(km.kits[3].name).to.eq('ToolchainKit 1');
expect(km.kits[4].name).to.eq('VSCode Kit 1');
expect(km.kits[5].name).to.eq('VSCode Kit 2');
km.dispose();
});
@ -94,14 +94,14 @@ suite('Kits test', async () => {
test('KitManager test selection of last activated kit', async () => {
const stateMock = sinon.createStubInstance(state.StateManager);
sinon.stub(stateMock, 'activeKitName').get(() => "ToolchainKit 1").set(() => {});
sinon.stub(stateMock, 'activeKitName').get(() => 'ToolchainKit 1').set(() => {});
const km = new kit.KitManager(stateMock, getTestResourceFilePath('test_kit.json'));
await km.initialize();
expect(km.activeKit).to.be.not.null;
if (km.activeKit)
expect(km.activeKit.name).to.eq("ToolchainKit 1");
expect(km.activeKit.name).to.eq('ToolchainKit 1');
km.dispose();
});
@ -119,8 +119,8 @@ suite('Kits test', async () => {
test('KitManager test selection of default kit if last activated kit is invalid', async () => {
const stateMock = sinon.createStubInstance(state.StateManager);
let storedActivatedKitName = "not replaced";
sinon.stub(stateMock, 'activeKitName').get(() => "Unknown").set(kit_ => storedActivatedKitName = kit_);
let storedActivatedKitName = 'not replaced';
sinon.stub(stateMock, 'activeKitName').get(() => 'Unknown').set(kit_ => storedActivatedKitName = kit_);
const km = new kit.KitManager(stateMock, getTestResourceFilePath('test_kit.json'));
await km.initialize();