From 068289254906177d4e2c8905e08c6890cacc39e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20de=20Campredon?= Date: Mon, 21 Apr 2014 09:48:51 +0200 Subject: [PATCH] add tslint in build and conform code to defined rules --- .brackets.json | 1 + Gruntfile.js | 14 ++- package.json | 2 +- src/commons/collections.ts | 18 +-- src/commons/definition.ts | 6 +- src/commons/errorService.ts | 2 +- src/commons/fileSystem.ts | 8 +- src/commons/immediate.ts | 4 +- src/commons/lexicalStructure.ts | 8 +- src/commons/preferencesManager.ts | 2 +- src/commons/projectConfig.ts | 2 +- src/commons/promiseQueue.ts | 12 +- src/commons/signal.ts | 1 - src/commons/typeScriptUtils.ts | 10 +- src/commons/workerBridge.ts | 40 +++---- src/commons/workingSet.ts | 4 +- src/declarations/brackets.d.ts | 64 +++++------ src/declarations/codemirror.d.ts | 84 +++++++------- src/declarations/es6-promises.d.ts | 20 ++-- src/declarations/jquery.d.ts | 5 +- src/declarations/minimatch.d.ts | 8 +- src/declarations/mustache.d.ts | 4 +- src/declarations/path.d.ts | 2 +- src/main/codeHintProvider.ts | 37 +++---- src/main/configErrorReporter.ts | 32 +++--- src/main/errorReporter.ts | 6 +- src/main/fileSystem.ts | 60 +++++----- src/main/index.ts | 12 +- src/main/mode.ts | 103 +++++++++--------- src/main/preferencesManager.ts | 8 +- src/main/quickEdit.ts | 20 ++-- src/main/quickFindDefinition.ts | 25 ++--- src/main/quickJump.ts | 10 +- src/main/serviceConsumer.ts | 8 +- src/main/workingSet.ts | 22 ++-- src/test-declarations/jasmine.d.ts | 3 +- src/test-declarations/sinon.d.ts | 4 +- src/test/bracketsMock.ts | 91 ++++++++-------- src/test/collectionsTest.ts | 14 ++- src/test/fileSystemMock.ts | 6 +- src/test/fileSystemTest.ts | 88 +++++++-------- src/test/languageServiceHostTest.ts | 16 +-- src/test/preferencesManagerTest.ts | 16 +-- src/test/projectManagerTest.ts | 93 +++++++--------- src/test/projectTest.ts | 133 +++++++++++------------ src/test/signalTest.ts | 2 +- src/test/workerBridgeTest.ts | 68 ++++++------ src/test/workingSetMock.ts | 6 +- src/test/workingSetTest.ts | 33 +++--- src/ts-worker/completionService.ts | 29 +++-- src/ts-worker/definitionService.ts | 10 +- src/ts-worker/errorService.ts | 18 +-- src/ts-worker/index.ts | 18 +-- src/ts-worker/languageServiceHost.ts | 25 +++-- src/ts-worker/lexicalStructureService.ts | 4 +- src/ts-worker/project.ts | 43 ++++---- src/ts-worker/projectManager.ts | 24 ++-- tslint.json | 29 ++--- 58 files changed, 728 insertions(+), 709 deletions(-) diff --git a/.brackets.json b/.brackets.json index e65f8fb..f42a77f 100644 --- a/.brackets.json +++ b/.brackets.json @@ -1,4 +1,5 @@ { + "spaceUnits": 4, "typescript": { "target": "ES5", "module": "AMD", diff --git a/Gruntfile.js b/Gruntfile.js index 9e17db0..a9fdda4 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -129,6 +129,18 @@ module.exports = function (grunt) { } }, + tslint: { + options: { + configuration: grunt.file.readJSON('tslint.json') + }, + all: { + src: [ + 'src/**/*.ts', + '!src/declarations/typescriptServices.d.ts' + ] + } + }, + jasmine: { test: { @@ -189,7 +201,7 @@ module.exports = function (grunt) { grunt.registerTask('build-main',['clean:tmp', 'typescript:main', 'browserify:main','clean:tmp']); grunt.registerTask('build-worker',['clean:tmp', 'typescript:worker', 'browserify:worker', 'clean:tmp']); grunt.registerTask('build-test', ['clean:tmp', 'typescript:test', 'browserify:test']); - grunt.registerTask('test', ['build-test', 'jasmine', 'clean:tmp']); + grunt.registerTask('test', ['tslint', 'build-test', 'jasmine', 'clean:tmp']); grunt.registerTask('build',['clean:local', 'build-main', 'build-worker']); grunt.registerTask('default', ['test', 'build']); grunt.registerTask('release', ['test', 'build', 'clean:release', 'copy:release','compress']); diff --git a/package.json b/package.json index 9f543cb..aa63ae7 100644 --- a/package.json +++ b/package.json @@ -19,7 +19,7 @@ "grunt-contrib-clean": "~0.5.0", "grunt-contrib-jasmine": "~0.5.2", "grunt-contrib-copy": "~0.4.1", - "grunt-tslint": "~0.4.0", + "grunt-tslint": "~0.4.1", "grunt-contrib-compress": "~0.5.3", "grunt-browserify": "~1.3.0", "istanbulify": "~0.1.0", diff --git a/src/commons/collections.ts b/src/commons/collections.ts index 1b1535d..493fa3a 100644 --- a/src/commons/collections.ts +++ b/src/commons/collections.ts @@ -36,8 +36,8 @@ export class StringSet { */ constructor(array?: string[]) { this.map = Object.create(null); - if (array) { - for (var i = 0, l= array.length; i < l;i ++) { + if (array) { + for (var i = 0, l = array.length; i < l; i ++) { this.add(array[i]); } } @@ -108,7 +108,7 @@ export class StringMap { constructor(obj?: {[index: string]: T}) { this.map = Object.create(null); this.mascot = {}; - if (obj) { + if (obj) { Object.keys(obj).forEach(key => this.map[key] = obj[key]); } } @@ -172,11 +172,11 @@ export class StringMap { * return an array containing the entries of the map */ get entries(): MapEntry[] { - return Object.keys(this.map).map(key => {  - return {  - key: key, - value: this.map[key] - } + return Object.keys(this.map).map(key => { + return { + key: key, + value: this.map[key] + }; }); } @@ -197,4 +197,4 @@ export class StringMap { clone(): StringMap { return new StringMap(this.toObject()); } -} \ No newline at end of file +} diff --git a/src/commons/definition.ts b/src/commons/definition.ts index fc5193c..7136c60 100644 --- a/src/commons/definition.ts +++ b/src/commons/definition.ts @@ -14,7 +14,7 @@ export interface DefinitionInfo { /** * line at which the symbol definition start */ - lineStart : number; + lineStart: number; /** * charachter at which the symbol definition start @@ -24,7 +24,7 @@ export interface DefinitionInfo { /** * line at which the symbol definition end */ - lineEnd : number; + lineEnd: number; /** * charachter at which the symbol definition end @@ -50,4 +50,4 @@ export interface IDefinitionService { * @return a promise resolving to a list of definition info */ getDefinitionForFile(fileName: string, position: CodeMirror.Position): Promise; -} \ No newline at end of file +} diff --git a/src/commons/errorService.ts b/src/commons/errorService.ts index 01de9ff..c3cdce6 100644 --- a/src/commons/errorService.ts +++ b/src/commons/errorService.ts @@ -14,4 +14,4 @@ interface IErrorService { getErrorsForFile(fileName: string): Promise<{ errors: brackets.LintingError[]; aborted: boolean }> } -export = IErrorService; \ No newline at end of file +export = IErrorService; diff --git a/src/commons/fileSystem.ts b/src/commons/fileSystem.ts index 1907575..5cc310f 100644 --- a/src/commons/fileSystem.ts +++ b/src/commons/fileSystem.ts @@ -33,12 +33,12 @@ export interface IFileSystem { /** * return a promise resolving to the project root folder path */ - getProjectRoot(): Promise + getProjectRoot(): Promise; /** * a signal dispatching fine grained change reflecting the change that happens in the working set */ - projectFilesChanged: signal.Signal + projectFilesChanged: signal.Signal; /** * return a promise that resolve with an array of string containing all the files of the projects @@ -103,12 +103,12 @@ export interface FileChangeRecord { /** * kind of change */ - kind : FileChangeKind; + kind: FileChangeKind; /** * name of the file that have changed */ - fileName : string; + fileName: string; } diff --git a/src/commons/immediate.ts b/src/commons/immediate.ts index 6992865..20d529c 100644 --- a/src/commons/immediate.ts +++ b/src/commons/immediate.ts @@ -81,7 +81,7 @@ if (typeof window.setImmediate !== 'undefined') { uidHelper++; setImmediateQueue.push({ handle: uidHelper, - callBack : typeof expression === 'string' ? new Function(expression): expression, + callBack : typeof expression === 'string' ? new Function(expression) : expression, parameters: args }); window.postMessage(sentinel, '*'); @@ -90,7 +90,7 @@ if (typeof window.setImmediate !== 'undefined') { clearImmediate(handle: number): void { canceledImmediate[handle] = true; } - } + }; Object.freeze(immediateImpl); } diff --git a/src/commons/lexicalStructure.ts b/src/commons/lexicalStructure.ts index 8848161..b7885a6 100644 --- a/src/commons/lexicalStructure.ts +++ b/src/commons/lexicalStructure.ts @@ -22,21 +22,21 @@ import Promise = es6Promise.Promise; /** * Represent a Lexical Structure item */ -export interface LexicalStructureItem { +export interface LexicalStructureItem { /** * Name of the item */ - name: string; + name: string; /** * Name of the item container */ - containerName:string; + containerName: string; /** * Position of the item in the file */ - position: CodeMirror.Position; + position: CodeMirror.Position; } /** diff --git a/src/commons/preferencesManager.ts b/src/commons/preferencesManager.ts index 9266123..b15c87c 100644 --- a/src/commons/preferencesManager.ts +++ b/src/commons/preferencesManager.ts @@ -15,7 +15,7 @@ 'use strict'; import TypeScriptProjectConfig = require('./projectConfig'); -import signal = require('./signal') +import signal = require('./signal'); import es6Promise = require('es6-promise'); import Promise = es6Promise.Promise; diff --git a/src/commons/projectConfig.ts b/src/commons/projectConfig.ts index 1749f69..86aee52 100644 --- a/src/commons/projectConfig.ts +++ b/src/commons/projectConfig.ts @@ -64,4 +64,4 @@ interface TypeScriptProjectConfig { noImplicitAny?: boolean; } -export = TypeScriptProjectConfig \ No newline at end of file +export = TypeScriptProjectConfig; diff --git a/src/commons/promiseQueue.ts b/src/commons/promiseQueue.ts index 6f724d0..ef62589 100644 --- a/src/commons/promiseQueue.ts +++ b/src/commons/promiseQueue.ts @@ -41,7 +41,7 @@ class PromiseQueue { constructor() { this.promise = new Promise(resolve => { this.initializer = resolve; - }) + }); } /** @@ -49,7 +49,7 @@ class PromiseQueue { * * @param val the value passed as initialial result */ - init(val: Promise):Promise + init(val: Promise): Promise; /** * initialize the queue subsequent call reset the queue @@ -69,11 +69,11 @@ class PromiseQueue { /** * enqueue an action */ - then(action: () => Promise):Promise + then(action: () => Promise): Promise; /** * enqueue an action */ - then(action: () => T): Promise + then(action: () => T): Promise; /** * enqueue an action */ @@ -81,8 +81,8 @@ class PromiseQueue { return this.promise = this.promise.then( () => action(), () => action() - ) + ); } } -export = PromiseQueue; \ No newline at end of file +export = PromiseQueue; diff --git a/src/commons/signal.ts b/src/commons/signal.ts index 190708f..2fabc0b 100644 --- a/src/commons/signal.ts +++ b/src/commons/signal.ts @@ -108,7 +108,6 @@ export class Signal implements ISignal { * @params parameter the parameter attached to the event dispatching */ dispatch(parameter?: T): boolean { - var indexesToRemove: number[]; var hasBeenCanceled = this.listeners.every((listener: (parameter: T) => any) => { var result = listener(parameter); return result !== false; diff --git a/src/commons/typeScriptUtils.ts b/src/commons/typeScriptUtils.ts index 161aa99..964d3ae 100644 --- a/src/commons/typeScriptUtils.ts +++ b/src/commons/typeScriptUtils.ts @@ -20,18 +20,18 @@ import TypeScriptProjectConfig = require('./projectConfig'); * helper function that valid a config file * @param config the config object to validate */ -export function validateTypeScriptProjectConfig(config : TypeScriptProjectConfig): boolean { +export function validateTypeScriptProjectConfig(config: TypeScriptProjectConfig): boolean { if (!config) { return false; } if (config.target && ['es3', 'es5'].indexOf(config.target.toLowerCase()) === -1) { - return false + return false; } if (config.module && ['none', 'amd', 'commonjs'].indexOf(config.module.toLowerCase()) === -1) { - return false + return false; } if (config.sourceRoot && typeof config.sourceRoot !== 'string') { - return false + return false; } if (!config.sources || !Array.isArray(config.sources) || !config.sources.every(pattern => typeof pattern === 'string')) { return false; @@ -49,4 +49,4 @@ export var typeScriptProjectConfigDefault: TypeScriptProjectConfig = { target: 'es3', module: 'none', noImplicitAny: false -} \ No newline at end of file +}; diff --git a/src/commons/workerBridge.ts b/src/commons/workerBridge.ts index 4304224..25ac590 100644 --- a/src/commons/workerBridge.ts +++ b/src/commons/workerBridge.ts @@ -48,7 +48,7 @@ enum Type { interface Resolver { resolve(result: any): any; - reject(error: any):any; + reject(error: any): any; } /** @@ -59,7 +59,7 @@ interface Resolver { * @param baseKeys */ function createProxyDescriptor(services: any, signals: { [index: string]: signal.Signal }, baseKeys: string[] = []) { - if (baseKeys.length> 5) { + if (baseKeys.length > 5) { return {}; } return utils.getEnumerablePropertyNames(services) @@ -73,20 +73,20 @@ function createProxyDescriptor(services: any, signals: { [index: string]: signal descriptor[key] = Type.SIGNAL; signals[keys.join('.')] = value; } else if (!Array.isArray(value)) { - descriptor[key] = createProxyDescriptor(value, signals, keys) + descriptor[key] = createProxyDescriptor(value, signals, keys); } } return descriptor; }, {}); } -var uidHelper = 0 +var uidHelper = 0; /** * create a query factory for a proxied service method */ function newQuery(chain: string[], sendMessage: (args: any) => void, resolverMap: collections.StringMap): any { return (...args: any []) => { - var uid = "operation" + (uidHelper++); + var uid = 'operation' + (uidHelper++); sendMessage({ operation: Operation.REQUEST, chain: chain, @@ -99,7 +99,7 @@ function newQuery(chain: string[], sendMessage: (args: any) => void, resolverMap reject: reject }); }); - } + }; } @@ -117,7 +117,7 @@ function createProxy(descriptor: any, sendMessage: (args: any) => void, } else if (value === Type.SIGNAL) { proxy[key] = new signal.Signal(); } else if (typeof value === 'object') { - proxy[key] = createProxy(descriptor[key], sendMessage, resolverMap, keys) + proxy[key] = createProxy(descriptor[key], sendMessage, resolverMap, keys); } return proxy; }, {}); @@ -138,7 +138,7 @@ class WorkerBridge { /** * deffered tracking sate */ - private initResolver: Resolver + private initResolver: Resolver; /** * @private @@ -149,7 +149,7 @@ class WorkerBridge { /** * build proxy of the bridge */ - proxy: any + proxy: any; constructor( /** @@ -166,7 +166,7 @@ class WorkerBridge { this.services = services; return new Promise((resolve, reject) => { var target = this.target; - target.onmessage = this.messageHandler + target.onmessage = this.messageHandler; var signals: { [index: string]: signal.Signal } = {}; target.postMessage({ @@ -183,8 +183,8 @@ class WorkerBridge { operation: Operation.SIGNAL, chain: key.split('.') , value: value - }) - } + }); + }; signal.add(handler); return { signal: signal, @@ -193,7 +193,7 @@ class WorkerBridge { }); this.initResolver = {resolve: resolve, reject: reject}; - }) + }); } @@ -210,7 +210,7 @@ class WorkerBridge { */ private messageHandler = (message: WorkerBridge.Message) => { var data = message.data; - switch(data.operation) { + switch (data.operation) { case Operation.EXPOSE: this.proxy = createProxy( data.descriptor, @@ -242,7 +242,7 @@ class WorkerBridge { this.target.postMessage({ operation: Operation.ERROR, chain: data.chain, - errorMessage: error instanceof Error? error.message : error, + errorMessage: error instanceof Error ? error.message : error, uid: data.uid }); }); @@ -250,14 +250,14 @@ class WorkerBridge { break; case Operation.RESPONSE: - var deferred = this.resolverMap.get(data.uid); - deferred.resolve(data.result); + var responseDeferred = this.resolverMap.get(data.uid); + responseDeferred.resolve(data.result); this.resolverMap.delete(data.uid); break; case Operation.ERROR: - var deferred = this.resolverMap.get(data.uid); - deferred.reject(new Error(data.errorMessage)); + var errorDeferred = this.resolverMap.get(data.uid); + errorDeferred.reject(new Error(data.errorMessage)); this.resolverMap.delete(data.uid); break; @@ -269,7 +269,7 @@ class WorkerBridge { } signal.dispatch(data.value); } - } + }; } diff --git a/src/commons/workingSet.ts b/src/commons/workingSet.ts index c529d61..1fa04cc 100644 --- a/src/commons/workingSet.ts +++ b/src/commons/workingSet.ts @@ -71,7 +71,7 @@ export interface WorkingSetChangeRecord { /** * list of paths that has been added or removed from the working set */ - paths : string[]; + paths: string[]; } @@ -133,4 +133,4 @@ export interface DocumentChangeRecord { * documentText */ documentText: string -} \ No newline at end of file +} diff --git a/src/declarations/brackets.d.ts b/src/declarations/brackets.d.ts index 386734d..3cd7791 100644 --- a/src/declarations/brackets.d.ts +++ b/src/declarations/brackets.d.ts @@ -101,7 +101,7 @@ declare module brackets { * @param path The path to resolve * @param callback Callback resolved with a FileSystemError string or with the entry for the provided path. */ - resolve(path: string, callback:(err: string, entry: FileSystemEntry, stat: FileSystemStats) => any): void; + resolve(path: string, callback: (err: string, entry: FileSystemEntry, stat: FileSystemStats) => any): void; /** @@ -190,8 +190,8 @@ declare module brackets { /** * This is an abstract representation of a FileSystem entry, and the base class for the File and Directory classes. - * FileSystemEntry objects are never created directly by client code. Use FileSystem.getFileForPath(), FileSystem.getDirectoryForPath(), - * or Directory.getContents() to create the entry. + * FileSystemEntry objects are never created directly by client code. Use FileSystem.getFileForPath(), + * FileSystem.getDirectoryForPath(), or Directory.getContents() to create the entry. */ interface FileSystemEntry { fullPath: string; @@ -228,7 +228,7 @@ declare module brackets { * @param {string} newFullPath New path & name for this entry. * @param {function (?string)=} callback Callback with a single FileSystemError string parameter. */ - rename(newFullPath:string, callback?: (err: string) => any):void; + rename(newFullPath: string, callback?: (err: string) => any): void; /** @@ -274,7 +274,8 @@ declare module brackets { * and their stat errors. If there are no stat errors then the last * parameter shall remain undefined. */ - getContents(callback: (err: string, files: FileSystemEntry[], stats: FileSystemStats, errors: { [path: string]: string; }) => any): void + getContents(callback: (err: string, files: FileSystemEntry[], + stats: FileSystemStats, errors: { [path: string]: string; }) => any): void; /** @@ -305,7 +306,7 @@ declare module brackets { * @param options Currently unused. * @param callback Callback that is passed the FileSystemError string or the file's new stats. */ - write(data: string, options? : {}, callback?: (err: string, stat: FileSystemStats) => any ) : void; + write(data: string, options?: {}, callback?: (err: string, stat: FileSystemStats) => any ): void; @@ -422,7 +423,7 @@ declare module brackets { * * @return {$.Promise} Promise that is resolved with an Array of File objects. */ - getAllFiles(filter?: (file: File) => boolean, includeWorkingSet?: boolean):JQueryPromise; + getAllFiles(filter?: (file: File) => boolean, includeWorkingSet?: boolean): JQueryPromise; /* TODO @@ -700,7 +701,7 @@ declare module brackets { * (Note that this is a higher level of batching than batchOperation(), which already batches all * edits within it for undo. Origin batching works across operations.) */ - replaceRange(text: string, start: CodeMirror.Position, end?: CodeMirror.Position, origin? :string):void; + replaceRange(text: string, start: CodeMirror.Position, end?: CodeMirror.Position, origin?: string): void; /** * Returns the text of the given line (excluding any line ending characters) @@ -754,14 +755,14 @@ declare module brackets { * $(editorInstance).on("eventname", handler); */ interface Editor { - _codeMirror: CodeMirror.Editor - document:Document; - getCursorPos():CodeMirror.Position; + _codeMirror: CodeMirror.Editor; + document: Document; + getCursorPos(): CodeMirror.Position; getModeForSelection(): string; getSelection(boolean: boolean): { start: CodeMirror.Position; end: CodeMirror.Position - } + }; setCursorPos(line: number, ch: number, center: boolean, expandTabs: boolean): void ; } @@ -769,7 +770,7 @@ declare module brackets { interface EditorManager { registerInlineEditProvider(provider: InlineEditProvider, priority?: number): void; registerInlineDocsProvider(provider: InlineDocsProvider, priority?: number): void; - registerJumpToDefProvider(provider:JumpDoDefProvider): void; + registerJumpToDefProvider(provider: JumpDoDefProvider): void; getFocusedEditor(): Editor; /** * Returns the current active editor (full-sized OR inline editor). This editor may not @@ -778,7 +779,7 @@ declare module brackets { * @see getFocusedEditor() * @returns {?Editor} */ - getActiveEditor():Editor; + getActiveEditor(): Editor; getCurrentFullEditor(): Editor; } @@ -868,7 +869,7 @@ declare module brackets { * @param options Specific location in which to set the value or the context to use when setting the value * @return true if a value was set */ - set(id:string, value: any, options?: {location: any; context?: any; }): boolean; + set(id: string, value: any, options?: {location: any; context?: any; }): boolean; /** @@ -990,9 +991,9 @@ declare module brackets { } interface CodeHintProvider { - hasHints(editor:Editor, implicitChar:string): boolean; - getHints(implicitChar:string): JQueryDeferred; - insertHint(hint: any):void; + hasHints(editor: Editor, implicitChar: string): boolean; + getHints(implicitChar: string): JQueryDeferred; + insertHint(hint: any): void; } @@ -1019,8 +1020,8 @@ declare module brackets { interface InspectionProvider { name: string; - scanFile?(content: string, path: string):{ errors: LintingError[]; aborted: boolean }; - scanFileAsync?(content: string, path: string):JQueryPromise<{ errors: LintingError[]; aborted: boolean }>; + scanFile?(content: string, path: string): { errors: LintingError[]; aborted: boolean }; + scanFileAsync?(content: string, path: string): JQueryPromise<{ errors: LintingError[]; aborted: boolean }>; } @@ -1080,16 +1081,17 @@ declare module brackets { /** * performs an action when a result is chosen. */ - itemSelect: (result: S) => void; + itemSelect: (result: S) => void; /** * takes a query string and an item string and returns * a
  • item to insert into the displayed search results. Optional. */ resultsFormatter?: (result: S) => string; + /** * options to pass along to the StringMatcher (see StringMatch.StringMatcher for available options). */ - matcherOptions? : StringMatcherOptions; + matcherOptions?: StringMatcherOptions; /** * if provided, the label to show before the query field. Optional. */ @@ -1102,8 +1104,8 @@ declare module brackets { } interface StringMatcher { - match(target:string, query: string):{ - ranges:{ text: string; matched: boolean; includesLastSegment: boolean}[]; + match(target: string, query: string): { + ranges: { text: string; matched: boolean; includesLastSegment: boolean}[]; matchGoodness: number; scoreDebug: any; } @@ -1135,21 +1137,21 @@ declare module brackets { module MultiRangeInlineEditor { class MultiRangeInlineEditor implements InlineWidget { constructor(ranges: MultiRangeInlineEditorRange[]); - load(editor: Editor): void + load(editor: Editor): void; } } interface MultiRangeInlineEditorRange { name: string; - document : brackets.Document; - lineStart:number; - lineEnd:number; + document: brackets.Document; + lineStart: number; + lineEnd: number; } - function getModule(module: 'filesystem/FileSystem'): FileSystem + function getModule(module: 'filesystem/FileSystem'): FileSystem; function getModule(module: 'document/DocumentManager'): brackets.DocumentManager; function getModule(module: 'project/ProjectManager'): brackets.ProjectManager; - function getModule(module: 'editor/CodeHintManager'):CodeHintManager; + function getModule(module: 'editor/CodeHintManager'): CodeHintManager; function getModule(module: 'editor/EditorManager'): EditorManager; function getModule(module: 'editor/MultiRangeInlineEditor'): typeof MultiRangeInlineEditor; function getModule(module: 'language/CodeInspection'): CodeInspection; @@ -1159,4 +1161,4 @@ declare module brackets { function getModule(module: 'preferences/PreferencesManager'): PreferencesManager; function getModule(module: string): any; -} \ No newline at end of file +} diff --git a/src/declarations/codemirror.d.ts b/src/declarations/codemirror.d.ts index e7e2bfa..e984557 100644 --- a/src/declarations/codemirror.d.ts +++ b/src/declarations/codemirror.d.ts @@ -1,48 +1,50 @@ +/*tslint:disable unused*/ + declare function CodeMirror(host: HTMLElement, options?: CodeMirror.EditorConfiguration): CodeMirror.Editor; declare function CodeMirror(callback: (host: HTMLElement) => void , options?: CodeMirror.EditorConfiguration): CodeMirror.Editor; declare module CodeMirror { interface CodeMirrorStream { - eol() : boolean; - sol() : boolean; - peek() : string; - next() : string; - eat(match: string) : string; - eat(match: RegExp) : string; - eat(match:(char: string) =>boolean) : string; - eatWhile(match: string) : string; - eatWhile(match: RegExp) : string; - eatWhile(match:(char: string) =>boolean) : string; - eatSpace() : boolean; + eol(): boolean; + sol(): boolean; + peek(): string; + next(): string; + eat(match: string): string; + eat(match: RegExp): string; + eat(match: (char: string) => boolean): string; + eatWhile(match: string): string; + eatWhile(match: RegExp): string; + eatWhile(match: (char: string) => boolean): string; + eatSpace(): boolean; skipToEnd(): void; - skipTo(ch: string) : boolean; - match(pattern: string, consume?: boolean, caseFold?: boolean) : boolean; - match(pattern: RegExp, consume?: boolean) : string[]; + skipTo(ch: string): boolean; + match(pattern: string, consume?: boolean, caseFold?: boolean): boolean; + match(pattern: RegExp, consume?: boolean): string[]; backUp(n: number): void; - column() : number; - indentation() : number; - current() : string; + column(): number; + indentation(): number; + current(): string; - pos:number; - string:string; + pos: number; + string: string; } interface CodeMirrorMode { - token(stream:CodeMirrorStream, state:T): void + token(stream: CodeMirrorStream, state: T): void; - startState?:() => T; - blankLine?:(state : T) => void; - copyState?:(state: T) => T; + startState?: () => T; + blankLine?: (state: T) => void; + copyState?: (state: T) => T; - indent?:(state: T, textAfter : string) => number - - lineComment? : string; - blockCommentStart ? : string; - blockCommentEnd ? : string; - blockCommentLead ? : string; - - electricChars ? : string + indent?: (state: T, textAfter: string) => number; + + lineComment?: string; + blockCommentStart?: string; + blockCommentEnd?: string; + blockCommentLead?: string; + + electricChars?: string } @@ -52,11 +54,11 @@ declare module CodeMirror { } interface CodeMirrorModeFactory { - (options:CodeMirror.EditorConfiguration, spec: any):CodeMirrorMode + (options: CodeMirror.EditorConfiguration, spec: any): CodeMirrorMode } function defineMode(id: string, modefactory: CodeMirrorModeFactory): void; - function defineMIME(mime:string, modeId:string): void; + function defineMIME(mime: string, modeId: string): void; var Pass: any; @@ -120,9 +122,11 @@ declare module CodeMirror { function on(marker: TextMarker, eventName: 'beforeCursorEnter', handler: () => void ): void; function off(marker: TextMarker, eventName: 'beforeCursorEnter', handler: () => void ): void; - /** Fired when the range is cleared, either through cursor movement in combination with clearOnEnter or through a call to its clear() method. - Will only be fired once per handle. Note that deleting the range through text editing does not fire this event, - because an undo action might bring the range back into existence. */ + /** Fired when the range is cleared, either through cursor movement in combination with clearOnEnter or + * through a call to its clear() method. + * Will only be fired once per handle. Note that deleting the range through text editing does not fire this event, + * because an undo action might bring the range back into existence. + */ function on(marker: TextMarker, eventName: 'clear', handler: () => void ): void; function off(marker: TextMarker, eventName: 'clear', handler: () => void ): void; @@ -264,7 +268,7 @@ declare module CodeMirror { height: any; clientWidth: any; clientHeight: any; - } + }; /** Scrolls the given element into view. pos is a { line , ch } position, referring to a given character, null, to refer to the cursor. The margin parameter is optional. When given, it indicates the amount of pixels around the given area that should be made visible as well. */ @@ -489,7 +493,7 @@ declare module CodeMirror { /** Replace the selection with the given string. By default, the new selection will span the inserted text. The optional collapse argument can be used to change this � passing "start" or "end" will collapse the selection to the start or end of the inserted text. */ - replaceSelection(replacement: string, collapse?: string): void + replaceSelection(replacement: string, collapse?: string): void; /** start is a an optional string indicating which end of the selection to return. It may be "start" , "end" , "head"(the side of the selection that moves when you press shift + arrow), @@ -778,7 +782,7 @@ declare module CodeMirror { /** Indicates how quickly CodeMirror should poll its input textarea for changes(when focused). Most input is captured by events, but some things, like IME input on some browsers, don't generate events that allow CodeMirror to properly detect it. Thus, it polls. Default is 100 milliseconds. */ - pollInterval?: number + pollInterval?: number; /** By default, CodeMirror will combine adjacent tokens into a single span if they have the same class. This will result in a simpler DOM tree, and thus perform better. With some kinds of styling(such as rounded corners), @@ -842,4 +846,4 @@ declare module CodeMirror { By default, a marker appears only in its target document. */ shared?: boolean; } -} \ No newline at end of file +} diff --git a/src/declarations/es6-promises.d.ts b/src/declarations/es6-promises.d.ts index 93e9210..4f2e8d8 100644 --- a/src/declarations/es6-promises.d.ts +++ b/src/declarations/es6-promises.d.ts @@ -3,6 +3,7 @@ // Definitions by: François de Campredon // Definitions: https://github.com/borisyankov/DefinitelyTyped +/*tslint:disable unused*/ declare module 'es6-promise' { export interface Thenable { then(onFulfilled: (value: R) => Thenable, onRejected: (error: any) => Thenable): Thenable; @@ -19,7 +20,7 @@ declare module 'es6-promise' { * For consistency and debugging (eg stack traces), obj should be an instanceof Error. * Any errors thrown in the constructor callback will be implicitly passed to reject(). */ - constructor(callback: (resolve : (result: R) => void, reject: (error: any) => void) => void); + constructor(callback: (resolve: (result: R) => void, reject: (error: any) => void) => void); /** * If you call resolve in the body of the callback passed to the constructor, * your promise will be fulfilled/rejected with the outcome of thenable passed to resolve. @@ -27,14 +28,15 @@ declare module 'es6-promise' { * For consistency and debugging (eg stack traces), obj should be an instanceof Error. * Any errors thrown in the constructor callback will be implicitly passed to reject(). */ - constructor(callback: (resolve : (thenable: Thenable) => void, reject: (error: any) => void) => void); + constructor(callback: (resolve: (thenable: Thenable) => void, reject: (error: any) => void) => void); /** * onFulFill is called when/if "promise" resolves. onRejected is called when/if "promise" rejects. * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called. * Both callbacks have a single parameter , the fulfillment value or rejection reason. - * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve. + * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after + * being passed through Promise.resolve. * If an error is thrown in the callback, the returned promise rejects with that error. * * @param onFulFill called when/if "promise" resolves @@ -45,7 +47,8 @@ declare module 'es6-promise' { * onFulFill is called when/if "promise" resolves. onRejected is called when/if "promise" rejects. * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called. * Both callbacks have a single parameter , the fulfillment value or rejection reason. - * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve. + * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after + * being passed through Promise.resolve. * If an error is thrown in the callback, the returned promise rejects with that error. * * @param onFulFill called when/if "promise" resolves @@ -56,7 +59,8 @@ declare module 'es6-promise' { * onFulFill is called when/if "promise" resolves. onRejected is called when/if "promise" rejects. * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called. * Both callbacks have a single parameter , the fulfillment value or rejection reason. - * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve. + * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after + * being passed through Promise.resolve. * If an error is thrown in the callback, the returned promise rejects with that error. * * @param onFulFill called when/if "promise" resolves @@ -67,7 +71,8 @@ declare module 'es6-promise' { * onFulFill is called when/if "promise" resolves. onRejected is called when/if "promise" rejects. * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called. * Both callbacks have a single parameter , the fulfillment value or rejection reason. - * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve. + * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after + * being passed through Promise.resolve. * If an error is thrown in the callback, the returned promise rejects with that error. * * @param onFulFill called when/if "promise" resolves @@ -105,7 +110,8 @@ declare module 'es6-promise' { /** * Make a new promise from the thenable. * A thenable is promise-like in as far as it has a "then" method. - * This also creates a new promise if you pass it a genuine JavaScript promise, making it less efficient for casting than Promise.cast. + * This also creates a new promise if you pass it a genuine JavaScript promise, + * making it less efficient for casting than Promise.cast. */ function resolve(thenable: Thenable): Promise; /** diff --git a/src/declarations/jquery.d.ts b/src/declarations/jquery.d.ts index 0b4ebaf..d80efe5 100644 --- a/src/declarations/jquery.d.ts +++ b/src/declarations/jquery.d.ts @@ -12,12 +12,15 @@ MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ +/*tslint:disable unused, max-line-length*/ // Typing for the jQuery library, version 1.10.x / 2.0.x // Project: http://jquery.com/ // Definitions by: Boris Yankov , Christian Hoffmeister , Steve Fenton, Diullei Gomes , Tass Iliopoulos , Jason Swearingen, Sean Hill , Guus Goossens , Kelly Summerlin , Basarat Ali Syed , Nicholas Wolverson , Derek Cicerone , Andrew Gaspar , James Harrison Fisher , Seikichi Kondo , Benjamin Jackman , Poul Sorensen , Josh Strobl , John Reilly // Definitions: https://github.com/borisyankov/DefinitelyTyped +/*tslint:disable unused*/ + /* Interface for the AJAX setting that will configure the AJAX request */ @@ -1644,4 +1647,4 @@ declare module "jquery" { export = $; } declare var jQuery: JQueryStatic; -declare var $: JQueryStatic; \ No newline at end of file +declare var $: JQueryStatic; diff --git a/src/declarations/minimatch.d.ts b/src/declarations/minimatch.d.ts index 2b68b36..684e0a0 100644 --- a/src/declarations/minimatch.d.ts +++ b/src/declarations/minimatch.d.ts @@ -50,13 +50,15 @@ interface MiniMatchOptions { /** - * When a match is not found by minimatch.match, return a list containing the pattern itself. When set, an empty list is returned if there are no matches. + * When a match is not found by minimatch.match, return a list containing the pattern itself. + * When set, an empty list is returned if there are no matches. */ nonull?: boolean; /** - * If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. For example, a?b would match the path /xyz/123/acb, but not /xyz/acb/123. + * If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. + * For example, a?b would match the path /xyz/123/acb, but not /xyz/acb/123. */ matchBase?: boolean; @@ -85,7 +87,7 @@ interface MiniMatchStatic { filter(pattern: string, options?: MiniMatchOptions): { (path: string): boolean }; } -declare module "minimatch" { +declare module 'minimatch' { var minimatch: MiniMatchStatic; export = minimatch; } diff --git a/src/declarations/mustache.d.ts b/src/declarations/mustache.d.ts index ab879e2..46f16df 100644 --- a/src/declarations/mustache.d.ts +++ b/src/declarations/mustache.d.ts @@ -4,8 +4,8 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped - +/*tslint:disable unused*/ declare var Mustache: { render(template: string, data: any): string; -}; \ No newline at end of file +}; diff --git a/src/declarations/path.d.ts b/src/declarations/path.d.ts index 18c0b56..9448680 100644 --- a/src/declarations/path.d.ts +++ b/src/declarations/path.d.ts @@ -1,4 +1,4 @@ -declare module "path" { +declare module 'path' { export function normalize(p: string): string; export function join(...paths: any[]): string; export function resolve(from: string, to: string): string; diff --git a/src/main/codeHintProvider.ts b/src/main/codeHintProvider.ts index 07008b6..1a01101 100644 --- a/src/main/codeHintProvider.ts +++ b/src/main/codeHintProvider.ts @@ -18,12 +18,11 @@ import ServiceConsumer = require('./serviceConsumer'); import completion = require('../commons/completion'); - -var CompletionKind = completion.CompletionKind; +import CompletionKind = completion.CompletionKind; var HINT_TEMPLATE = [ '', - ' ', + ' ', ' {{match}}{{suffix}}', ' ', '' @@ -45,7 +44,7 @@ class CodeHintProvider extends ServiceConsumer im * @param implicitChar determine whether the hinting request is explicit or implicit, * null if implicit, contains the last character inserted */ - hasHints(editor: brackets.Editor, implicitChar:string): boolean { + hasHints(editor: brackets.Editor, implicitChar: string): boolean { //TODO we should find a better test here that limits more the implicit request if (!implicitChar || /[\w.\($_]/.test(implicitChar)) { this.editor = editor; @@ -54,7 +53,7 @@ class CodeHintProvider extends ServiceConsumer im return false; } - getHints(implicitChar:string): JQueryDeferred { + getHints(implicitChar: string): JQueryDeferred { var currentFileName: string = this.editor.document.file.fullPath, position = this.editor.getCursorPos(), deferred = $.Deferred(); @@ -72,9 +71,9 @@ class CodeHintProvider extends ServiceConsumer im var text = entry.name, match: string, suffix: string, - class_type= ''; + classType = ''; - switch(entry.kind) { + switch (entry.kind) { case CompletionKind.KEYWORD: switch (entry.name) { case 'static': @@ -83,16 +82,16 @@ class CodeHintProvider extends ServiceConsumer im case 'export': case 'get': case 'set': - class_type = 'cm-qualifier'; + classType = 'cm-qualifier'; break; case 'class': case 'function': case 'module': case 'var': - class_type = 'cm-def'; + classType = 'cm-def'; break; default: - class_type = 'cm-keyword'; + classType = 'cm-keyword'; break; } break; @@ -107,28 +106,28 @@ class CodeHintProvider extends ServiceConsumer im // highlight the matched portion of each hint if (result.match) { - match= text.slice(0, result.match.length); + match = text.slice(0, result.match.length); suffix = text.slice(result.match.length); } else { match = ''; - suffix = text + suffix = text; } var jqueryObj = $(Mustache.render(HINT_TEMPLATE, { match: match, suffix: suffix, - class_type: class_type + classType: classType })); - jqueryObj.data('entry', entry) - jqueryObj.data('match', result.match) + jqueryObj.data('entry', entry); + jqueryObj.data('match', result.match); return jqueryObj; }), selectInitial: !!implicitChar - }) - }).catch(error => deferred.reject(error)) + }); + }).catch(error => deferred.reject(error)); }); } return deferred; @@ -136,7 +135,7 @@ class CodeHintProvider extends ServiceConsumer im - insertHint($hintObj: JQuery):void { + insertHint($hintObj: JQuery): void { var entry: completion.CompletionEntry = $hintObj.data('entry'), match: string = $hintObj.data('match'), position = this.editor.getCursorPos(), @@ -154,4 +153,4 @@ class CodeHintProvider extends ServiceConsumer im } -export = CodeHintProvider; \ No newline at end of file +export = CodeHintProvider; diff --git a/src/main/configErrorReporter.ts b/src/main/configErrorReporter.ts index 0c1ca84..7be99d1 100644 --- a/src/main/configErrorReporter.ts +++ b/src/main/configErrorReporter.ts @@ -23,24 +23,28 @@ // //-------------------------------------------------------------------------- -var BRACKETS_CONFIG_FILE_NAME = '.brackets.json' +var BRACKETS_CONFIG_FILE_NAME = '.brackets.json'; function isBracketsPreferenceFile(path: string): boolean { return path && path.substr(path.lastIndexOf('/') + 1, path.length) === BRACKETS_CONFIG_FILE_NAME; } + + /** * brackets Error message type */ var Type = { /** Unambiguous error, such as a syntax error */ - ERROR: "problem_type_error", + ERROR: 'problem_type_error', /** Maintainability issue, probable error / bad smell, etc. */ - WARNING: "problem_type_warning", + WARNING: 'problem_type_warning', /** Inspector unable to continue, code too complex for static analysis, etc. Not counted in error/warning tally. */ - META: "problem_type_meta" + META: 'problem_type_meta' }; + + /** * TypeScript Inspection Provider */ @@ -54,7 +58,7 @@ class TypeScriptConfigErrorReporter implements brackets.InspectionProvider { /** * scan file */ - scanFile(content: string, path: string) : { errors: brackets.LintingError[]; aborted: boolean; } { + scanFile(content: string, path: string): { errors: brackets.LintingError[]; aborted: boolean; } { if (!isBracketsPreferenceFile(path)) { return null; } @@ -65,7 +69,7 @@ class TypeScriptConfigErrorReporter implements brackets.InspectionProvider { return { errors: [], aborted: true - } + }; } var typescript = data.typescript; @@ -73,7 +77,7 @@ class TypeScriptConfigErrorReporter implements brackets.InspectionProvider { return { errors: [], aborted: false - } + }; } var errors: string[] = []; @@ -93,7 +97,7 @@ class TypeScriptConfigErrorReporter implements brackets.InspectionProvider { } return { - errors: errors.map(message =>({ + errors: errors.map(message => ({ message: message, type: Type.ERROR, pos: {line: -1, ch: -1} @@ -104,15 +108,15 @@ class TypeScriptConfigErrorReporter implements brackets.InspectionProvider { } function validateSection(sectionName: string, config: any, mustHaveSources: boolean, errors: string[] ) { - var prefix = sectionName? sectionName + ': ' : ''; + var prefix = sectionName ? sectionName + ': ' : ''; if (config.target && ['es3', 'es5'].indexOf(config.target.toLowerCase()) === -1) { - errors.push('the target section has invalid value authorized values are \'es3\' or \'es5\''); + errors.push(prefix + 'the target section has invalid value authorized values are \'es3\' or \'es5\''); } if (config.module && ['none', 'amd', 'commonjs'].indexOf(config.module.toLowerCase()) === -1) { - errors.push('the module section has invalid value authorized values are \'none\', \'amd\' or \'commonjs\''); + errors.push(prefix + 'the module section has invalid value authorized values are \'none\', \'amd\' or \'commonjs\''); } if (config.sourceRoot && typeof config.sourceRoot !== 'string') { - errors.push('the sourceRoot section must be a string'); + errors.push(prefix + 'the sourceRoot section must be a string'); } if (mustHaveSources) { if ( @@ -120,10 +124,10 @@ function validateSection(sectionName: string, config: any, mustHaveSources: bool !Array.isArray(config.sources) || !config.sources.every((pattern: string) => typeof pattern === 'string') ) { - errors.push('invalid sources section it must be an array of string'); + errors.push(prefix + 'invalid sources section it must be an array of string'); } } } -export = TypeScriptConfigErrorReporter; \ No newline at end of file +export = TypeScriptConfigErrorReporter; diff --git a/src/main/errorReporter.ts b/src/main/errorReporter.ts index cd0faa5..4bd8536 100644 --- a/src/main/errorReporter.ts +++ b/src/main/errorReporter.ts @@ -55,10 +55,10 @@ class TypeScriptErrorReporter extends ServiceConsumer implements }); } ); - }) - }) + }); + }); }).promise(); } } -export = TypeScriptErrorReporter \ No newline at end of file +export = TypeScriptErrorReporter; diff --git a/src/main/fileSystem.ts b/src/main/fileSystem.ts index b719b19..987ffac 100644 --- a/src/main/fileSystem.ts +++ b/src/main/fileSystem.ts @@ -19,7 +19,7 @@ import collections = require('../commons/collections'); import signal = require('../commons/signal'); import es6Promise = require('es6-promise'); -import Promise = es6Promise.Promise;; +import Promise = es6Promise.Promise; import fs = require('../commons/fileSystem'); @@ -97,7 +97,7 @@ class FileSystem implements fs.IFileSystem { getProjectFiles(): Promise { return new Promise(resolve => { this.addToInitializatioStack(() => resolve(this.filesPath)); - }) + }); } /** @@ -109,7 +109,7 @@ class FileSystem implements fs.IFileSystem { return new Promise((resolve, reject) => { this.addToInitializatioStack(() => { if (this.filesContent.has(path)) { - resolve(this.filesContent.get(path)) + resolve(this.filesContent.get(path)); } else { var file = this.nativeFileSystem.getFileForPath(path); if (file.isDirectory) { @@ -127,7 +127,7 @@ class FileSystem implements fs.IFileSystem { }); } }); - }) + }); } /** @@ -163,7 +163,7 @@ class FileSystem implements fs.IFileSystem { */ private init() { this.projectManager.getAllFiles().then((files: brackets.File[]) => { - this.filesPath = files? files.map(file => file.fullPath) : []; + this.filesPath = files ? files.map(file => file.fullPath) : []; this.initialized = true; this.resolveInitializationStack(); }); @@ -178,7 +178,7 @@ class FileSystem implements fs.IFileSystem { if (this.initialized) { callback(); } else { - this.initializationStack.push(callback) + this.initializationStack.push(callback); } } @@ -201,7 +201,7 @@ class FileSystem implements fs.IFileSystem { }, {} , (err) => { resolve(files); }); - }) + }); } /** @@ -209,7 +209,7 @@ class FileSystem implements fs.IFileSystem { * @param text */ private normalizeText(text: string) { - return text.replace(/\r\n/g, "\n"); + return text.replace(/\r\n/g, '\n'); } //------------------------------- @@ -219,7 +219,7 @@ class FileSystem implements fs.IFileSystem { /** * handle project workspaces changes */ - private changesHandler = (event: any, file? : brackets.FileSystemEntry) => { + private changesHandler = (event: any, file?: brackets.FileSystemEntry) => { if (!file) { // a refresh event var oldPathsSet = new collections.StringSet(), @@ -249,7 +249,7 @@ class FileSystem implements fs.IFileSystem { promises.push(new Promise((resolve, reject) => { file.read({}, (err: string, content: string) => { if (!err) { - this.filesContent.set(file.fullPath, content) + this.filesContent.set(file.fullPath, content); } if (err || content !== oldFilesContent.get(file.fullPath)) { fileUpdated.push(file.fullPath); @@ -265,7 +265,7 @@ class FileSystem implements fs.IFileSystem { oldPaths.forEach(path => { if (!newPathsSet.has(path)) { - fileDeleted.push(path) + fileDeleted.push(path); } }); @@ -302,7 +302,7 @@ class FileSystem implements fs.IFileSystem { }); }, () => { - this.reset() + this.reset(); }); } else if (file.isFile) { @@ -319,16 +319,15 @@ class FileSystem implements fs.IFileSystem { // if the file content has been cached update the cache this.filesContent.delete(file.fullPath); this.readFile(file.fullPath).then((content) => { - this.filesContent.set(file.fullPath, content) + this.filesContent.set(file.fullPath, content); }).catch().then(dispatchUpdate); } else { - dispatchUpdate() + dispatchUpdate(); } - } else if(file.isDirectory) { + } else if (file.isDirectory) { // a directory content has been changed need to make diff between cache an directory - var directory = file, - children: brackets.FileSystemEntry; + var directory = file; directory.getContents((err: string, files: brackets.FileSystemEntry[]) => { if (err) { @@ -340,7 +339,7 @@ class FileSystem implements fs.IFileSystem { //collect all the paths in the cache this.filesPath.forEach(path => { - var index = path.indexOf(directory.fullPath) + var index = path.indexOf(directory.fullPath); if (index !== -1) { var index2 = path.indexOf('/', index + directory.fullPath.length); if (index2 === -1) { @@ -361,8 +360,9 @@ class FileSystem implements fs.IFileSystem { newFiles[file.fullPath] = file; }); - var changes: fs.FileChangeRecord[] = []; - for (var path in oldFiles) { + var changes: fs.FileChangeRecord[] = [], + path: string; + for (path in oldFiles) { if (!newFiles.hasOwnProperty(path) && oldFiles.hasOwnProperty(path)) { //for each files that has been deleted add a DELETE record oldFiles[path].forEach(path => { @@ -379,8 +379,8 @@ class FileSystem implements fs.IFileSystem { } } - var promises: Promise[] = [] - for (var path in newFiles) { + var promises: Promise[] = []; + for (path in newFiles) { if (newFiles.hasOwnProperty(path) && !oldFiles.hasOwnProperty(path)) { //if a file has been added just add a ADD record if (newFiles[path].isFile) { @@ -399,8 +399,8 @@ class FileSystem implements fs.IFileSystem { kind: fs.FileChangeKind.ADD, fileName : file.fullPath }); - }) - })) + }); + })); } } }; @@ -412,18 +412,18 @@ class FileSystem implements fs.IFileSystem { } }, () => { //in case of error reset - this.reset() + this.reset(); }); }); } - } + }; /** * handle file renaming event */ - private renameHandler = (event: any, oldPath : string, newPath: string) => { - var isDirectory = oldPath[oldPath.length -1] === '/'; + private renameHandler = (event: any, oldPath: string, newPath: string) => { + var isDirectory = oldPath[oldPath.length - 1] === '/'; var changes: fs.FileChangeRecord[]; if (isDirectory) { changes = []; @@ -439,7 +439,7 @@ class FileSystem implements fs.IFileSystem { if (changes.length > 0) { this._projectFilesChanged.dispatch(changes); } - } + }; /** * dispatch events when a file has been renamed @@ -466,4 +466,4 @@ class FileSystem implements fs.IFileSystem { } } -export = FileSystem; \ No newline at end of file +export = FileSystem; diff --git a/src/main/index.ts b/src/main/index.ts index 88477d7..ec8b849 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -20,7 +20,7 @@ import WorkingSet = require('./workingSet'); import TypeScriptPreferencesManager = require('./preferencesManager'); import WorkerBridge = require('../commons/workerBridge'); import TypeScriptErrorReporter = require('./errorReporter'); -import TypeScriptConfigErrorReporter = require('./configErrorReporter') +import TypeScriptConfigErrorReporter = require('./configErrorReporter'); import TypeScriptQuickEditProvider = require('./quickEdit'); import TypeScriptQuickJumpProvider = require('./quickJump'); import TypeScriptQuickFindDefitionProvider = require('./quickFindDefinition'); @@ -45,11 +45,11 @@ var LanguageManager = brackets.getModule('language/LanguageManager'), EditorManager = brackets.getModule('editor/EditorManager'), QuickOpen = brackets.getModule('search/QuickOpen'), PreferencesManager = brackets.getModule('preferences/PreferencesManager'), - CodeMirror: typeof CodeMirror = brackets.getModule("thirdparty/CodeMirror2/lib/codemirror"); + CodeMirror: typeof CodeMirror = brackets.getModule('thirdparty/CodeMirror2/lib/codemirror'); -var tsErrorReporter : TypeScriptErrorReporter, +var tsErrorReporter: TypeScriptErrorReporter, quickEditProvider: TypeScriptQuickEditProvider, - codeHintProvider : CodeHintProvider, + codeHintProvider: CodeHintProvider, quickJumpProvider: TypeScriptQuickJumpProvider, quickFindDefinitionProvider: TypeScriptQuickFindDefitionProvider; @@ -61,7 +61,7 @@ var fileSystem: FileSystem, preferencesManager: TypeScriptPreferencesManager, bridge: WorkerBridge; -function init(config: { logLevel: string; typeScriptLocation: string; workerLocation: string;}) { +function init(config: { logLevel: string; typeScriptLocation: string; workerLocation: string; }) { logger.setLogLevel(config.logLevel); CodeMirror.defineMode('typescript', typeScriptModeFactory); @@ -84,7 +84,7 @@ function init(config: { logLevel: string; typeScriptLocation: string; workerLoca //Register quickJump quickJumpProvider = new TypeScriptQuickJumpProvider(); - EditorManager.registerJumpToDefProvider(quickJumpProvider.handleJumpToDefinition) + EditorManager.registerJumpToDefProvider(quickJumpProvider.handleJumpToDefinition); //Register error provider diff --git a/src/main/mode.ts b/src/main/mode.ts index 93b4f70..2eba863 100644 --- a/src/main/mode.ts +++ b/src/main/mode.ts @@ -31,7 +31,12 @@ class FormattingOptions { public newLineCharacter: string) { } - public static defaultOptions = new FormattingOptions(/*useTabs:*/ false, /*spacesPerTab:*/ 4, /*indentSpaces:*/ 4, /*newLineCharacter*/ "\r\n"); + public static defaultOptions = new FormattingOptions( + /*useTabs:*/ false, + /*spacesPerTab:*/ 4, + /*indentSpaces:*/ 4, + /*newLineCharacter*/ '\r\n' + ); } import logger = require('../commons/logger'); @@ -39,20 +44,20 @@ import Services = TypeScript.Services; import Formatting = TypeScript.Services.Formatting; class Token { - string:string; + string: string; classification: Services.TokenClass; - length:number; - position:number; + length: number; + position: number; } class LineDescriptor { - tokenMap:{ [position: number]:Token }; + tokenMap: { [position: number]: Token }; eolState: Services.EndOfLineState = Services.EndOfLineState.Start; - text: string = ""; + text: string = ''; - clone():LineDescriptor { - var clone:LineDescriptor = new LineDescriptor(); + clone(): LineDescriptor { + var clone: LineDescriptor = new LineDescriptor(); clone.tokenMap = this.tokenMap; clone.eolState = this.eolState; clone.text = this.text; @@ -63,14 +68,14 @@ class LineDescriptor { class TypeScriptMode implements CodeMirror.CodeMirrorMode { - private options:CodeMirror.EditorConfiguration; + private options: CodeMirror.EditorConfiguration; - lineComment = "//"; - blockCommentStart = "/*"; - blockCommentEnd = "*/"; - electricChars = ":{}[]()"; + lineComment = '//'; + blockCommentStart = '/*'; + blockCommentEnd = '*/'; + electricChars = ':{}[]()'; - constructor(options:CodeMirror.EditorConfiguration) { + constructor(options: CodeMirror.EditorConfiguration) { this.options = options; } @@ -82,20 +87,19 @@ class TypeScriptMode implements CodeMirror.CodeMirrorMode { return lineDescriptor.clone(); } - token(stream:CodeMirror.CodeMirrorStream, lineDescriptor:LineDescriptor) { - if(stream.sol()) { + token(stream: CodeMirror.CodeMirrorStream, lineDescriptor: LineDescriptor) { + if (stream.sol()) { this.initializeLineDescriptor(lineDescriptor, stream.string); } var token = lineDescriptor.tokenMap[stream.pos]; - if(token) { - var textBefore:string = stream.string.substr(0, stream.pos); - for(var i = 0; i < token.length; i++) { + if (token) { + var textBefore: string = stream.string.substr(0, stream.pos); + for (var i = 0; i < token.length; i++) { stream.next(); } return getStyleForToken(token, textBefore); - } - else { + } else { stream.skipToEnd(); } @@ -103,13 +107,13 @@ class TypeScriptMode implements CodeMirror.CodeMirrorMode { } - indent(lineDescriptor:LineDescriptor , textAfter: string):number { - if(lineDescriptor.eolState !== Services.EndOfLineState.Start) { + indent(lineDescriptor: LineDescriptor , textAfter: string): number { + if (lineDescriptor.eolState !== Services.EndOfLineState.Start) { //strange bug preven CodeMirror.Pass - return (CodeMirror).Pass + return (CodeMirror).Pass; } - var text = lineDescriptor.text + "\n" + (textAfter || "fakeIdent"), - position = textAfter? text.length : text.length - 9, + var text = lineDescriptor.text + '\n' + (textAfter || 'fakeIdent'), + position = textAfter ? text.length : text.length - 9, syntaxTree = this.getSyntaxTree(text), options = new FormattingOptions(!this.options.indentWithTabs, this.options.tabSize, this.options.indentUnit, '\n'), textSnapshot = new Formatting.TextSnapshot(TypeScript.SimpleText.fromString(text)), @@ -120,9 +124,9 @@ class TypeScriptMode implements CodeMirror.CodeMirrorMode { options ); - if(indent === null) { + if (indent === null) { //strange bug preven CodeMirror.Pass - return (CodeMirror).Pass + return (CodeMirror).Pass; } return indent; } @@ -130,8 +134,7 @@ class TypeScriptMode implements CodeMirror.CodeMirrorMode { private initializeLineDescriptor(lineDescriptor: LineDescriptor, text: string) { var classificationResult = getClassificationsForLine(text, lineDescriptor.eolState), - tokens = classificationResult.tokens, - prevLine = lineDescriptor.clone(); + tokens = classificationResult.tokens; if (lineDescriptor.text) { lineDescriptor.text += '\n'; @@ -140,7 +143,7 @@ class TypeScriptMode implements CodeMirror.CodeMirrorMode { lineDescriptor.eolState = classificationResult.eolState; lineDescriptor.tokenMap = {}; - for (var i=0, l = tokens.length; i < l; i++) { + for (var i = 0, l = tokens.length; i < l; i++) { lineDescriptor.tokenMap[tokens[i].position] = tokens[i]; } @@ -149,7 +152,7 @@ class TypeScriptMode implements CodeMirror.CodeMirrorMode { private getSyntaxTree(text: string) { return TypeScript.Parser.parse( - "script", + 'script', TypeScript.SimpleText.fromString(text), false, new TypeScript.ParseOptions(TypeScript.LanguageVersion.EcmaScript5, true) @@ -159,12 +162,12 @@ class TypeScriptMode implements CodeMirror.CodeMirrorMode { -var classifier:Services.Classifier = new Services.TypeScriptServicesFactory().createClassifier(new logger.LogingClass()); +var classifier: Services.Classifier = new Services.TypeScriptServicesFactory().createClassifier(new logger.LogingClass()); -function getClassificationsForLine(text:string, eolState:Services.EndOfLineState ) { +function getClassificationsForLine(text: string, eolState: Services.EndOfLineState ) { var classificationResult = classifier.getClassificationsForLine(text, eolState), currentPosition = 0, - tokens:Token[] = []; + tokens: Token[] = []; for (var i = 0, l = classificationResult.entries.length; i < l ; i++) { var entry = classificationResult.entries[i]; @@ -172,7 +175,7 @@ function getClassificationsForLine(text:string, eolState:Services.EndOfLineState string: text.substr(currentPosition, entry.length), length: entry.length, classification: entry.classification, - position:currentPosition + position: currentPosition }; tokens.push(token); currentPosition += entry.length; @@ -181,30 +184,30 @@ function getClassificationsForLine(text:string, eolState:Services.EndOfLineState return { tokens: tokens, eolState: classificationResult.finalLexState - } + }; } -function getStyleForToken(token:Token, textBefore:string):string { +function getStyleForToken(token: Token, textBefore: string): string { var TokenClass = Services.TokenClass; - switch(token.classification) { + switch (token.classification) { case TokenClass.NumberLiteral: - return "number"; + return 'number'; case TokenClass.StringLiteral: - return "string"; + return 'string'; case TokenClass.RegExpLiteral: - return "string-2"; + return 'string-2'; case TokenClass.Operator: - return "operator"; + return 'operator'; case TokenClass.Comment: - return "comment"; + return 'comment'; case TokenClass.Keyword: - switch(token.string) { + switch (token.string) { case 'string': case 'number': case 'void': case 'bool': case 'boolean': - return "variable"; + return 'variable'; case 'static': case 'public': case 'private': @@ -222,17 +225,17 @@ function getStyleForToken(token:Token, textBefore:string):string { } case TokenClass.Identifier: - return "variable"; + return 'variable'; case TokenClass.Punctuation: - return "bracket"; + return 'bracket'; case TokenClass.Whitespace: default: return null; } } -function typeScriptModeFactory(options:CodeMirror.EditorConfiguration, spec: any):CodeMirror.CodeMirrorMode { +function typeScriptModeFactory(options: CodeMirror.EditorConfiguration, spec: any): CodeMirror.CodeMirrorMode { return new TypeScriptMode(options); } -export = typeScriptModeFactory; \ No newline at end of file +export = typeScriptModeFactory; diff --git a/src/main/preferencesManager.ts b/src/main/preferencesManager.ts index 37de8c7..d39f09a 100644 --- a/src/main/preferencesManager.ts +++ b/src/main/preferencesManager.ts @@ -50,7 +50,7 @@ class TypescriptPreferenceManager implements ITypescriptPreferenceManager { */ getProjectsConfig() { if (!this.projectConfigs) { - this.projectConfigs = this.retriveProjectsConfig() + this.projectConfigs = this.retriveProjectsConfig(); } return Promise.cast(this.projectConfigs.toObject()); } @@ -96,7 +96,7 @@ class TypescriptPreferenceManager implements ITypescriptPreferenceManager { Object.keys(configs).forEach(projectId => { var config: TypeScriptProjectConfig = utils.assign({ }, tsUtils.typeScriptProjectConfigDefault, configs[projectId]); - if(!tsUtils.validateTypeScriptProjectConfig(config)) { + if (!tsUtils.validateTypeScriptProjectConfig(config)) { if (logger.warning()) { logger.log('invalid config file for brackets-typescript config file'); } @@ -116,7 +116,7 @@ class TypescriptPreferenceManager implements ITypescriptPreferenceManager { this.projectConfigs = null; this.configChanged.dispatch(); } - } + }; } -export = TypescriptPreferenceManager; \ No newline at end of file +export = TypescriptPreferenceManager; diff --git a/src/main/quickEdit.ts b/src/main/quickEdit.ts index 2ba5400..c51df1e 100644 --- a/src/main/quickEdit.ts +++ b/src/main/quickEdit.ts @@ -35,7 +35,7 @@ class TypeScriptQuickEditProvider extends ServiceConsumer { var fileName = hostEditor.document.file.fullPath; service.getDefinitionForFile(fileName, pos).then(definitions => { @@ -44,7 +44,7 @@ class TypeScriptQuickEditProvider extends ServiceConsumer definition.fileName !== fileName || definition.lineStart !== pos.line) + definitions.filter(definition => definition.fileName !== fileName || definition.lineStart !== pos.line); if (definitions.length === 0) { deferred.reject(); } @@ -60,21 +60,21 @@ class TypeScriptQuickEditProvider extends ServiceConsumer { + return $.when.apply($, promises).then(() => { var inlineEditor = new MultiRangeInlineEditor(ranges); inlineEditor.load(hostEditor); deferred.resolve(inlineEditor); }); }).catch(e => { - deferred.reject() - }) - }) + deferred.reject(); + }); + }); return deferred.promise(); - } + }; } -export = TypeScriptQuickEditProvider; \ No newline at end of file +export = TypeScriptQuickEditProvider; diff --git a/src/main/quickFindDefinition.ts b/src/main/quickFindDefinition.ts index d333669..68cb297 100644 --- a/src/main/quickFindDefinition.ts +++ b/src/main/quickFindDefinition.ts @@ -18,7 +18,6 @@ import ServiceConsumer = require('./serviceConsumer'); import ls = require('../commons/lexicalStructure'); -import WorkingSet = require('./workingSet') var EditorManager = brackets.getModule('editor/EditorManager'), QuickOpen = brackets.getModule('search/QuickOpen'); @@ -27,7 +26,7 @@ var EditorManager = brackets.getModule('editor/EditorManager'), class Session { constructor( public items: ls.LexicalStructureItem[] - ){} + ) {} } @@ -38,45 +37,45 @@ class TypeScriptQuickFindDefitionProvider extends ServiceConsumer { - request = request.slice(request.indexOf("@") + 1, request.length); + request = request.slice(request.indexOf('@') + 1, request.length); return this.getSession().then(session => { return session.items.filter(item => { return !!stringMatcher.match(item.name, request); }); }); - } + }; done = () => { this.session = null; - } + }; itemSelect = (item: TypeScriptQuickFindDefitionProvider.LexicalStructureItem) => { this.itemFocus(item); - } + }; itemFocus = (item: TypeScriptQuickFindDefitionProvider.LexicalStructureItem) => { this.setCurrentPosition(item.position); - } + }; resultsFormatter(item: TypeScriptQuickFindDefitionProvider.LexicalStructureItem) { var displayName = QuickOpen.highlightMatch(item.name); displayName = item.containerName ? item.containerName + '.' + displayName : displayName; - return "
  • " + displayName + "
  • "; + return '
  • ' + displayName + '
  • '; } private getSession(): JQueryPromise { return $.Deferred(deferred => { if (this.session) { - deferred.resolve(this.session) + deferred.resolve(this.session); } else { this.getService().then(lexicalStructureService => { var editor = EditorManager.getActiveEditor(), @@ -91,14 +90,14 @@ class TypeScriptQuickFindDefitionProvider extends ServiceConsumer { @@ -42,7 +42,7 @@ class TypeScriptQuickJumpProvider extends ServiceConsumer definition.fileName !== fileName || definition.lineStart !== pos.line) + definitions.filter(definition => definition.fileName !== fileName || definition.lineStart !== pos.line); if (definitions.length === 0) { deferred.reject(); } @@ -66,7 +66,7 @@ class TypeScriptQuickJumpProvider extends ServiceConsumer deferred.reject()); }); return deferred.promise(); - } + }; } -export = TypeScriptQuickJumpProvider; \ No newline at end of file +export = TypeScriptQuickJumpProvider; diff --git a/src/main/serviceConsumer.ts b/src/main/serviceConsumer.ts index e95517d..c38dc4f 100644 --- a/src/main/serviceConsumer.ts +++ b/src/main/serviceConsumer.ts @@ -15,7 +15,7 @@ 'use strict'; import es6Promise = require('es6-promise'); -import Promise = es6Promise.Promise;; +import Promise = es6Promise.Promise; /** * a class implementing logic to stack operations until a service @@ -31,7 +31,7 @@ class ServiceConsumer { /** * internal promise */ - private promise: Promise + private promise: Promise; /** * constructor @@ -60,8 +60,8 @@ class ServiceConsumer { * reset the injection */ reset() { - this.promise = new Promise(resolve => this.serviceResolver = resolve) + this.promise = new Promise(resolve => this.serviceResolver = resolve); } } -export = ServiceConsumer; \ No newline at end of file +export = ServiceConsumer; diff --git a/src/main/workingSet.ts b/src/main/workingSet.ts index 7393d08..5ab92a6 100644 --- a/src/main/workingSet.ts +++ b/src/main/workingSet.ts @@ -123,7 +123,7 @@ class WorkingSet implements ws.IWorkingSet { * set working set files */ private setFiles(files: string[]) { - this.filesSet.values.forEach(path => this.filesSet.remove(path)) + this.filesSet.values.forEach(path => this.filesSet.remove(path)); if (files) { files.forEach(path => this.filesSet.add(path)); } @@ -142,7 +142,7 @@ class WorkingSet implements ws.IWorkingSet { kind: ws.WorkingSetChangeKind.ADD, paths: [file.fullPath] }); - } + }; /** * handle 'workingSetAddList' event @@ -158,7 +158,7 @@ class WorkingSet implements ws.IWorkingSet { paths: paths }); } - } + }; /** * handle 'workingSetRemove' event @@ -169,7 +169,7 @@ class WorkingSet implements ws.IWorkingSet { kind: ws.WorkingSetChangeKind.REMOVE, paths: [file.fullPath] }); - } + }; /** * handle 'workingSetRemoveList' event @@ -177,7 +177,7 @@ class WorkingSet implements ws.IWorkingSet { private workingSetRemoveListHandler = (event: any, ...files: brackets.File[]) => { var paths = files.map( file => { this.filesSet.remove(file.fullPath); - return file.fullPath + return file.fullPath; }); if (paths.length > 0) { this.workingSetChanged.dispatch({ @@ -185,7 +185,7 @@ class WorkingSet implements ws.IWorkingSet { paths: paths }); } - } + }; /** * attach events to the activeEditor @@ -210,7 +210,7 @@ class WorkingSet implements ws.IWorkingSet { from: change.from, to: change.to, text: change.text && change.text.join('\n'), - removed: change.removed ? change.removed.join("\n") : "" + removed: change.removed ? change.removed.join('\n') : '' })); if (changeList.length > 0) { @@ -220,19 +220,15 @@ class WorkingSet implements ws.IWorkingSet { documentText: document.getText() }); } - } + }; /** * handle active editor change */ private activeEditorChangeHandler = (event: any, current: brackets.Editor, previous: brackets.Editor) => { this.setActiveEditor(current); - } + }; } export = WorkingSet; - - - - \ No newline at end of file diff --git a/src/test-declarations/jasmine.d.ts b/src/test-declarations/jasmine.d.ts index 2582b8a..7008e23 100644 --- a/src/test-declarations/jasmine.d.ts +++ b/src/test-declarations/jasmine.d.ts @@ -3,6 +3,7 @@ // Definitions by: Boris Yankov // DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped +/*tslint:disable unused*/ declare function describe(description: string, specDefinitions: () => void): void; declare function xdescribe(description: string, specDefinitions: () => void): void; @@ -389,4 +390,4 @@ declare module jasmine { } export var HtmlReporter: any; -} \ No newline at end of file +} diff --git a/src/test-declarations/sinon.d.ts b/src/test-declarations/sinon.d.ts index e058d47..f0a60ed 100644 --- a/src/test-declarations/sinon.d.ts +++ b/src/test-declarations/sinon.d.ts @@ -391,6 +391,6 @@ interface SinonStatic { declare var sinon: SinonStatic; -declare module "sinon" { +declare module 'sinon' { export = sinon; -} \ No newline at end of file +} diff --git a/src/test/bracketsMock.ts b/src/test/bracketsMock.ts index 44f1dfb..7ad1e4d 100644 --- a/src/test/bracketsMock.ts +++ b/src/test/bracketsMock.ts @@ -23,17 +23,17 @@ export class FileSystem { root.setParent(null); } - private listeners: { [event : string]: {(...rest: any[]): any }[] } = {}; + private listeners: { [event: string]: {(...rest: any[]): any }[] } = {}; getFileForPath(path: string): File { - var result = this.getEntryForFile(path, 'file') + var result = this.getEntryForFile(path, 'file'); if (!result) { result = new File({ - name: path.substr(path.lastIndexOf('/') +1), + name: path.substr(path.lastIndexOf('/') + 1), content : null }); result.fullPath = path; - result.parentPath = path.substr(0, path.lastIndexOf('/')) + result.parentPath = path.substr(0, path.lastIndexOf('/')); result.id = path; } @@ -45,10 +45,10 @@ export class FileSystem { on(event: string, handler: (...rest: any[]) => any): void { var listeners = this.listeners[event]; if (listeners && listeners.indexOf(handler) !== -1) { - return + return; } if (!listeners) { - listeners = this.listeners[event]= [] + listeners = this.listeners[event] = []; } listeners.push(handler); } @@ -68,7 +68,7 @@ export class FileSystem { dispatch(event: string, ...args: any[]) { var listeners = this.listeners[event]; if (!listeners) { - return + return; } listeners.forEach(listerner => listerner.apply(null, [{}].concat(args))); } @@ -95,19 +95,19 @@ export class FileSystem { var newEntry: FileSystemEntry; if (entry.isFile) { newEntry = new File({ - name: newPath.substr(newPath.lastIndexOf("/") + 1), + name: newPath.substr(newPath.lastIndexOf('/') + 1), content: (entry).content }); } else { newEntry = new Directory({ - name: newPath.substr(newPath.lastIndexOf("/", newPath.length - 2) + 1), + name: newPath.substr(newPath.lastIndexOf('/', newPath.length - 2) + 1), children: (entry).children }); } dir.remove(entry); dir.add(newEntry); newEntry.setParent(dir); - this.dispatch('rename',path, newPath); + this.dispatch('rename', path, newPath); } @@ -119,28 +119,27 @@ export class FileSystem { throw new Error('unknown dir : \'' + path + '\''); } dir.remove(entry); - this.dispatch('change', dir) + this.dispatch('change', dir); } - addEntry(entry:FileSystemEntry) { + addEntry(entry: FileSystemEntry) { var dir = this.getEntryForFile(entry.parentPath, 'directory'); if (!dir) { throw new Error('unknown dir : \'' + entry.parentPath + '\''); } dir.add(entry); - this.dispatch('change', dir) + this.dispatch('change', dir); } - getEntryForFile(path: string, type: 'directory'): Directory - getEntryForFile(path: string, type: 'file'): File - getEntryForFile(path: string, type: string): FileSystemEntry - getEntryForFile(path: string, type: string): FileSystemEntry - { + getEntryForFile(path: string, type: 'directory'): Directory; + getEntryForFile(path: string, type: 'file'): File; + getEntryForFile(path: string, type: string): FileSystemEntry; + getEntryForFile(path: string, type: string): FileSystemEntry { var result: FileSystemEntry; this.root.visit(entry => { - if(entry.fullPath === path ) { + if (entry.fullPath === path ) { if (type === 'file' && !entry.isFile) { - return false + return false; } else if (type === 'directory' && !entry.isDirectory) { return false; } @@ -148,7 +147,7 @@ export class FileSystem { return false; } return true; - }, null, () => 0) + }, null, () => 0); return result; } @@ -158,13 +157,13 @@ export function d(options: DirectoryOptions) { return new Directory(options); } -export function f(options: FileOptions, fullPath?: string, parentPath? : string) { +export function f(options: FileOptions, fullPath?: string, parentPath?: string) { var file = new File(options); if (typeof fullPath !== 'undefined') { file.id = file.fullPath = fullPath; } if (typeof parentPath !== 'undefined') { - file.parentPath = parentPath + file.parentPath = parentPath; } return file; } @@ -191,7 +190,7 @@ export class FileSystemEntry implements brackets.FileSystemEntry { exists(callback: (err: string, exist: boolean) => any): void { - callback(null, true) + callback(null, true); } @@ -201,7 +200,7 @@ export class FileSystemEntry implements brackets.FileSystemEntry { } - rename(newFullPath:string, callback?: (err: string) => any):void { + rename(newFullPath: string, callback?: (err: string) => any): void { callback(null); } unlink(callback?: (err: string) => any): void { @@ -215,17 +214,17 @@ export class FileSystemEntry implements brackets.FileSystemEntry { visit(visitor: (entry: brackets.FileSystemEntry) => boolean, options: {failFast?: boolean; maxDepth?: number; maxEntries?: number}, callbak: (err: string) => any): void { this.internalVisit(visitor); - callbak(null) + callbak(null); } private internalVisit(visitor: (entry: brackets.FileSystemEntry) => boolean): boolean { if (!visitor(this)) { - return false + return false; } if (this.isDirectory) { - var result: boolean + var result: boolean; (this).getContents((err: string, files: FileSystemEntry[]) => { - result = files.every(file => file.internalVisit(visitor)) + result = files.every(file => file.internalVisit(visitor)); }); return result; } else { @@ -236,7 +235,7 @@ export class FileSystemEntry implements brackets.FileSystemEntry { export interface FileOptions { name: string; - content : string; + content: string; } @@ -249,7 +248,7 @@ export class File extends FileSystemEntry implements brackets.File { this.isDirectory = false; this.isFile = true; if (!options) { - throw new Error('options manadatory') + throw new Error('options manadatory'); } this.name = options.name; this.content = options.content; @@ -268,7 +267,7 @@ export class File extends FileSystemEntry implements brackets.File { if (this.content) { callback(null, this.content, null); } else { - callback(FILE_NOT_FOUND, null, null) + callback(FILE_NOT_FOUND, null, null); } }, 0); } @@ -281,7 +280,7 @@ export class File extends FileSystemEntry implements brackets.File { * @param options Currently unused. * @param callback Callback that is passed the FileSystemError string or the file's new stats. */ - write(data: string, options? : {}, callback?: (err: string, stat: brackets.FileSystemStats) => any ) : void { + write(data: string, options?: {}, callback?: (err: string, stat: brackets.FileSystemStats) => any ): void { } @@ -290,17 +289,17 @@ export class File extends FileSystemEntry implements brackets.File { export interface DirectoryOptions { name: string; - children : FileSystemEntry[]; + children: FileSystemEntry[]; } export class Directory extends FileSystemEntry implements brackets.Directory { - children : FileSystemEntry[]; + children: FileSystemEntry[]; constructor(options: DirectoryOptions) { super(); this.isDirectory = true; this.isFile = false; if (!options) { - throw new Error('options manadatory') + throw new Error('options manadatory'); } this.name = options.name; this.fullPath = this.name; @@ -312,14 +311,16 @@ export class Directory extends FileSystemEntry implements brackets.Directory { callback(null, null); } - getContents(callback: (err: string, files: FileSystemEntry[], stats: brackets.FileSystemStats, errors: { [path: string]: string; }) => any) { - callback(null, this.children , null, null) + getContents( + callback: (err: string, files: FileSystemEntry[], stats: brackets.FileSystemStats, errors: { [path: string]: string; }) => any + ) { + callback(null, this.children , null, null); } remove(entry: FileSystemEntry) { var index = this.children.indexOf(entry); if (index !== -1) { - this.children.splice(index, 1) + this.children.splice(index, 1); } } @@ -332,18 +333,18 @@ export class Directory extends FileSystemEntry implements brackets.Directory { export class ProjectManager { constructor( - private fs:FileSystem - ){} + private fs: FileSystem + ) {} async: boolean = false; - getAllFiles(filter? : (file: brackets.File) => boolean, includeWorkingSet? : boolean) { + getAllFiles(filter?: (file: brackets.File) => boolean, includeWorkingSet?: boolean) { var deferred = $.Deferred(), files: brackets.File[] = []; var resolve = () => { this.fs.root.visit(entry => { if (entry.isFile) { - files.push( entry) + files.push( entry); } return true; }, null, () => { @@ -368,12 +369,12 @@ export class Document { getText(useOriginalLineEndings?: boolean): string { return this.lines.join('/n'); } - replaceRange(text: string, start: CodeMirror.Position, end?: CodeMirror.Position, origin? :string):void { + replaceRange(text: string, start: CodeMirror.Position, end?: CodeMirror.Position, origin?: string): void { } getLine(index: number): string { - return this.lines[index] + return this.lines[index]; } } diff --git a/src/test/collectionsTest.ts b/src/test/collectionsTest.ts index 61d67f3..3964364 100644 --- a/src/test/collectionsTest.ts +++ b/src/test/collectionsTest.ts @@ -21,13 +21,14 @@ describe('StringSet', function () { var stringSet: collections.StringSet; beforeEach(function () { stringSet = new collections.StringSet(); - }) + }); + it('should have constructor takes an array of string as argument and add every element of this array to the Set', function () { stringSet = new collections.StringSet(['hello', 'world']); expect(stringSet.has('hello')).toBe(true); expect(stringSet.has('world')).toBe(true); expect(stringSet.has('bla')).toBe(false); - }) + }); it('should allow to add/remove string from the set and check presence', function () { stringSet.add('hello'); @@ -60,7 +61,8 @@ describe('StringMap', function () { stringMap = new collections.StringMap(); }); - it('should have a constructor that takes an object has parameter and and each pair property/value of this object has entry of the map', function () { + it('should have a constructor that takes an object has parameter and and each pair' + + 'property/value of this object has entry of the map', function () { stringMap = new collections.StringMap({ 'foo' : 'bar', 'hello' : 'world' }); expect(stringMap.get('hello')).toBe('world'); expect(stringMap.get('foo')).toBe('bar'); @@ -98,12 +100,12 @@ describe('StringMap', function () { it('should provide a properties \'keys\' returning an array of map key', function () { stringMap = new collections.StringMap({ 'foo' : 'bar', 'hello' : 'world' }); - expect(stringMap.keys.sort()).toEqual(['foo','hello']); + expect(stringMap.keys.sort()).toEqual(['foo', 'hello']); }); it('should provide a properties \'values\' returning an array of map key', function () { stringMap = new collections.StringMap({ 'foo' : 'bar', 'hello' : 'world' }); - expect(stringMap.values.sort()).toEqual(['bar','world']); + expect(stringMap.values.sort()).toEqual(['bar', 'world']); }); it('should provide a properties \'entries\' returning an array of map entrie', function () { @@ -129,4 +131,4 @@ describe('StringMap', function () { expect(stringMap2).toNotBe(stringMap); expect(stringMap.toObject()).toEqual(stringMap2.toObject()); }); -}); \ No newline at end of file +}); diff --git a/src/test/fileSystemMock.ts b/src/test/fileSystemMock.ts index 9b64570..07ee809 100644 --- a/src/test/fileSystemMock.ts +++ b/src/test/fileSystemMock.ts @@ -19,7 +19,7 @@ import fs = require('../commons/fileSystem'); import signal = require('../commons/signal'); import es6Promise = require('es6-promise'); -import Promise = es6Promise.Promise;; +import Promise = es6Promise.Promise; class FileSystem implements fs.IFileSystem { @@ -34,7 +34,7 @@ class FileSystem implements fs.IFileSystem { getProjectFiles(forceRefresh?: boolean): Promise { return new Promise(resolve => { - resolve(Object.keys(this.files)) + resolve(Object.keys(this.files)); }); } @@ -102,4 +102,4 @@ class FileSystem implements fs.IFileSystem { -export = FileSystem; \ No newline at end of file +export = FileSystem; diff --git a/src/test/fileSystemTest.ts b/src/test/fileSystemTest.ts index 0856f43..01940cf 100644 --- a/src/test/fileSystemTest.ts +++ b/src/test/fileSystemTest.ts @@ -25,7 +25,7 @@ import f = bracketsMock.f; describe('FileSystem', function() { var fileSystem: FileSystem, - fileSystemMock : bracketsMock.FileSystem, + fileSystemMock: bracketsMock.FileSystem, rootDir: bracketsMock.Directory, projectManager: bracketsMock.ProjectManager; @@ -83,7 +83,7 @@ describe('FileSystem', function() { ] }); fileSystemMock = new bracketsMock.FileSystem(rootDir); - projectManager= new bracketsMock.ProjectManager(fileSystemMock); + projectManager = new bracketsMock.ProjectManager(fileSystemMock); fileSystem = new FileSystem(fileSystemMock, projectManager); }); @@ -104,7 +104,7 @@ describe('FileSystem', function() { '/subdir2/file5.ts', '/subdir2/subdir3/file6.ts', '/subdir2/subdir3/file7.ts' - ])) + ])); }); }); @@ -112,20 +112,20 @@ describe('FileSystem', function() { it('should return the file content', function () { var content: string; - fileSystem.readFile('/subdir2/subdir3/file6.ts').then(data => content = data) + fileSystem.readFile('/subdir2/subdir3/file6.ts').then(data => content = data); waitsFor(() => !!content, 'file should be read', 20); runs(() => { expect(content).toBe('File6 content'); - }) + }); }); it('should normalize the file content', function () { var content: string; - fileSystem.readFile('/subdir2/subdir3/file7.ts').then(data => content = data) + fileSystem.readFile('/subdir2/subdir3/file7.ts').then(data => content = data); waitsFor(() => !!content, 'file should be read', 20); runs(() => { expect(content).toBe('File7 content\nline2\nline3\nline4'); - }) + }); }); @@ -135,7 +135,7 @@ describe('FileSystem', function() { waitsFor(() => !!error, 'error should be set'); runs(() => { expect(error).toBe(bracketsMock.FILE_NOT_FOUND); - }) + }); }); it('should return an error if the file is a directory', function () { @@ -144,30 +144,30 @@ describe('FileSystem', function() { waitsFor(() => !!error, 'error should be set'); runs(() => { expect(error).toBe(bracketsMock.FILE_NOT_FOUND); - }) + }); }); it('should cache files content', function () { - var spy = spyOn(fileSystemMock,'getFileForPath').andCallThrough(), + var spy = spyOn(fileSystemMock, 'getFileForPath').andCallThrough(), content: string; fileSystem.readFile('/subdir2/subdir3/file6.ts').then(data => content = data); waitsFor(() => !!content, 'file should be read', 20); runs(() => { - fileSystem.readFile('/subdir2/subdir3/file6.ts').then(data => expect(data).toBe(content)) + fileSystem.readFile('/subdir2/subdir3/file6.ts').then(data => expect(data).toBe(content)); expect(spy.callCount).toBe(1); expect(content).toBe('File6 content'); - }) + }); }); it('should update cached files when they are updated', function () { var content: string; fileSystem.readFile('/subdir2/subdir3/file6.ts'); - fileSystemMock.updateFile('/subdir2/subdir3/file6.ts', 'new content') - fileSystem.readFile('/subdir2/subdir3/file6.ts').then(data => content = data) + fileSystemMock.updateFile('/subdir2/subdir3/file6.ts', 'new content'); + fileSystem.readFile('/subdir2/subdir3/file6.ts').then(data => content = data); waitsFor(() => content === 'new content', 'file should be read', 20); runs(() => { expect(content).toBe('new content'); - }) + }); }); }); @@ -209,7 +209,7 @@ describe('FileSystem', function() { kind: fs.FileChangeKind.DELETE, fileName: '/subdir2/file4.ts' }]); - }) + }); }); @@ -225,7 +225,7 @@ describe('FileSystem', function() { kind: fs.FileChangeKind.ADD, fileName: '/subdir2/file8.ts' }]); - }) + }); }); @@ -237,13 +237,13 @@ describe('FileSystem', function() { expect(changeSpy).toHaveBeenCalledWith([{ kind: fs.FileChangeKind.DELETE, fileName: '/subdir2/file4.ts' - },{ + }, { kind: fs.FileChangeKind.DELETE, fileName: '/subdir2/file5.ts' - },{ + }, { kind: fs.FileChangeKind.DELETE, fileName: '/subdir2/subdir3/file6.ts' - },{ + }, { kind: fs.FileChangeKind.DELETE, fileName: '/subdir2/subdir3/file7.ts' }]); @@ -296,14 +296,14 @@ describe('FileSystem', function() { expect(changeSpy).toHaveBeenCalledWith([{ kind: fs.FileChangeKind.ADD, fileName: '/subdir1/subdir5/file8.ts' - },{ + }, { kind: fs.FileChangeKind.ADD, fileName: '/subdir1/subdir5/file9.ts' - },{ + }, { kind: fs.FileChangeKind.ADD, fileName: '/subdir1/subdir5/subdir6/file10.ts' }]); - }) + }); }); @@ -391,22 +391,22 @@ describe('FileSystem', function() { expect(changeSpy).toHaveBeenCalledWith([{ kind: fs.FileChangeKind.DELETE, fileName: '/file1.ts' - },{ + }, { kind: fs.FileChangeKind.DELETE, fileName: '/subdir2/subdir3/file6.ts' - },{ + }, { kind: fs.FileChangeKind.DELETE, fileName: '/subdir2/subdir3/file7.ts' - },{ + }, { kind: fs.FileChangeKind.ADD, fileName: '/file8.ts' - },{ + }, { kind: fs.FileChangeKind.ADD, fileName: '/subdir3/file6.ts' - },{ + }, { kind: fs.FileChangeKind.ADD, fileName: '/subdir3/file7.ts' - },{ + }, { kind: fs.FileChangeKind.UPDATE, fileName: '/subdir2/file5.ts' }]); @@ -422,7 +422,7 @@ describe('FileSystem', function() { expect(changeSpy).toHaveBeenCalledWith([{ kind: fs.FileChangeKind.DELETE, fileName: '/subdir2/file4.ts' - },{ + }, { kind: fs.FileChangeKind.ADD, fileName: '/subdir2/newFile.ts' }]); @@ -437,12 +437,12 @@ describe('FileSystem', function() { '/subdir2/subdir3/file6.ts', '/subdir2/subdir3/file7.ts', '/subdir2/newFile.ts' - ])) + ])); }); it('should update the cache when a file has been renamed', function () { - var spy = spyOn(fileSystemMock,'getFileForPath').andCallThrough(), + var spy = spyOn(fileSystemMock, 'getFileForPath').andCallThrough(), content: string, newContent: string; @@ -451,9 +451,9 @@ describe('FileSystem', function() { runs(() => { fileSystemMock.renameFile('/subdir2/file4.ts', '/subdir2/newFile.ts'); - }) + }); - waits(20);; + waits(20); runs(() => { fileSystem.readFile('/subdir2/newFile.ts').then(result => newContent = result); }); @@ -469,31 +469,31 @@ describe('FileSystem', function() { 'the directory when a directory has been renamed', function () { fileSystemMock.renameFile('/subdir2/', '/subdir4/'); - waits(20);; + waits(20); runs(function () { expect(changeSpy.callCount).toBe(1); expect(changeSpy).toHaveBeenCalledWith([{ kind: fs.FileChangeKind.DELETE, fileName: '/subdir2/file4.ts' - },{ + }, { kind: fs.FileChangeKind.ADD, fileName: '/subdir4/file4.ts' - },{ + }, { kind: fs.FileChangeKind.DELETE, fileName: '/subdir2/file5.ts' - },{ + }, { kind: fs.FileChangeKind.ADD, fileName: '/subdir4/file5.ts' - },{ + }, { kind: fs.FileChangeKind.DELETE, fileName: '/subdir2/subdir3/file6.ts' - },{ + }, { kind: fs.FileChangeKind.ADD, fileName: '/subdir4/subdir3/file6.ts' - },{ + }, { kind: fs.FileChangeKind.DELETE, fileName: '/subdir2/subdir3/file7.ts' - },{ + }, { kind: fs.FileChangeKind.ADD, fileName: '/subdir4/subdir3/file7.ts' }]); @@ -527,8 +527,8 @@ describe('FileSystem', function() { '/subdir2/subdir3/file7.ts' ]); expect(content).toBe('File1 content'); - }) + }); }); }); -}); \ No newline at end of file +}); diff --git a/src/test/languageServiceHostTest.ts b/src/test/languageServiceHostTest.ts index 6c4f96c..5ea3eff 100644 --- a/src/test/languageServiceHostTest.ts +++ b/src/test/languageServiceHostTest.ts @@ -20,7 +20,7 @@ import LanguageServiceHost = require('../ts-worker/languageServiceHost'); import utils = require('../commons/utils'); describe('LanguageServiceHost', function () { - var languageServiceHost: LanguageServiceHost + var languageServiceHost: LanguageServiceHost; beforeEach(function () { languageServiceHost = new LanguageServiceHost(); }); @@ -35,7 +35,7 @@ describe('LanguageServiceHost', function () { expect(languageServiceHost.getCompilationSettings()).toNotBe(compilationSettings); expect(utils.clone(languageServiceHost.getCompilationSettings())).toEqual(compilationSettings); }); - }) + }); describe('Script Management', function () { it('should allows to add and remove script', function () { @@ -52,7 +52,7 @@ describe('LanguageServiceHost', function () { it('should allows to update script content', function () { languageServiceHost.addScript('file1.ts', 'hello world'); languageServiceHost.updateScript('file1.ts', 'foo bar'); - var snapshot = languageServiceHost.getScriptSnapshot('file1.ts') + var snapshot = languageServiceHost.getScriptSnapshot('file1.ts'); expect(snapshot.getText(0, snapshot.getLength())).toBe('foo bar'); expect(languageServiceHost.getScriptVersion('file1.ts')).toBe(2); }); @@ -86,7 +86,7 @@ describe('LanguageServiceHost', function () { languageServiceHost.addScript('file1.ts', 'hello world'); languageServiceHost.editScript('file1.ts', 6, 11, 'bar'); languageServiceHost.editScript('file1.ts', 0, 5, 'foo'); - var snapshot = languageServiceHost.getScriptSnapshot('file1.ts') + var snapshot = languageServiceHost.getScriptSnapshot('file1.ts'); expect(snapshot.getText(0, snapshot.getLength())).toBe('foo bar'); expect(languageServiceHost.getScriptVersion('file1.ts')).toBe(3); expect(snapshot.getTextChangeRangeSinceVersion(1).newLength()).toBe(7); @@ -131,8 +131,8 @@ describe('LanguageServiceHost', function () { expect(languageServiceHost.fileExists('file1.ts')).toBe(false); expect(languageServiceHost.directoryExists('anyDirectory')).toBe(true); - expect(languageServiceHost.resolveRelativePath('../file1.ts', '/dir1/dir2/')).toBe('/dir1/file1.ts') - expect(languageServiceHost.getParentDirectory('/dir1/file1.ts')).toBe('/dir1') + expect(languageServiceHost.resolveRelativePath('../file1.ts', '/dir1/dir2/')).toBe('/dir1/file1.ts'); + expect(languageServiceHost.getParentDirectory('/dir1/file1.ts')).toBe('/dir1'); }); @@ -152,9 +152,9 @@ describe('LanguageServiceHost', function () { it('should returns diagnostic object', function () { //TODO I don't really know what are the spec here expect(languageServiceHost.getDiagnosticsObject()).toNotBe(null); - expect(languageServiceHost.getLocalizedDiagnosticMessages()).toBe(""); + expect(languageServiceHost.getLocalizedDiagnosticMessages()).toBe(''); }); - }) + }); }); diff --git a/src/test/preferencesManagerTest.ts b/src/test/preferencesManagerTest.ts index 27c49ac..69a993a 100644 --- a/src/test/preferencesManagerTest.ts +++ b/src/test/preferencesManagerTest.ts @@ -23,10 +23,10 @@ describe('TypescriptPreferenceManager', function () { preferences: any, bracketsPrefManagerMock = { get() { - return preferences + return preferences; }, on(type: string, callback: () => void) { - this.callback = callback + this.callback = callback; }, notifyChange() { this.callback(null, { ids: ['typescript']}); @@ -38,7 +38,7 @@ describe('TypescriptPreferenceManager', function () { }); afterEach(function () { tsPrefManager.dispose(); - }) + }); function expectProjectConfig(compareValue: any) { var configs: any; @@ -59,7 +59,7 @@ describe('TypescriptPreferenceManager', function () { preferences = { sources: ['src/'], target: 'es5' - } + }; expectProjectConfig({ default: { sources: ['src/'], @@ -73,7 +73,7 @@ describe('TypescriptPreferenceManager', function () { it('should retrieve no project config if the config is not valid', function () { - preferences = { hello:'world' }; + preferences = { hello: 'world' }; expectProjectConfig({}); }); @@ -116,11 +116,11 @@ describe('TypescriptPreferenceManager', function () { var configChangeSpy = jasmine.createSpy('configChangeSpy'); tsPrefManager.configChanged.add(configChangeSpy); preferences = { - sources:['src'] - } + sources: ['src'] + }; bracketsPrefManagerMock.notifyChange(); expect(configChangeSpy).toHaveBeenCalled(); tsPrefManager.dispose(); }); -}); \ No newline at end of file +}); diff --git a/src/test/projectManagerTest.ts b/src/test/projectManagerTest.ts index 7142282..cdca6ef 100644 --- a/src/test/projectManagerTest.ts +++ b/src/test/projectManagerTest.ts @@ -19,13 +19,12 @@ import TypeScriptProjectManager = require('../ts-worker/projectManager'); import TypeScriptProject = require('../ts-worker/project'); import TypeScriptProjectConfig = require('../commons/projectConfig'); -import fs = require('../commons/fileSystem'); import utils = require('../commons/utils'); import collections = require('../commons/collections'); import signal = require('../commons/signal'); import FileSystemMock = require('./fileSystemMock'); import es6Promise = require('es6-promise'); -import Promise = es6Promise.Promise;; +import Promise = es6Promise.Promise; describe('TypeScriptProjectManager', function () { @@ -43,7 +42,7 @@ describe('TypeScriptProjectManager', function () { update: jasmine.Spy; dispose: jasmine.Spy; }, - projectFactorySpy: jasmine.Spy + projectFactorySpy: jasmine.Spy; function initiProjectManager() { typeScriptProjectManager.init('', preferenceManagerMock, fileSystemMock, null, projectFactorySpy); @@ -54,17 +53,16 @@ describe('TypeScriptProjectManager', function () { projectSpy = { init: jasmine.createSpy('init').andCallFake(function () { return new Promise(resolve => { - setTimeout(() => resolve(true), 10) - }) + setTimeout(() => resolve(true), 10); + }); }), update: jasmine.createSpy('update').andCallFake(function () { return new Promise(resolve => { - setTimeout(() => resolve(true), 10) - }) + setTimeout(() => resolve(true), 10); + }); }), dispose: jasmine.createSpy('dispose') }; - var i = 0; projectFactorySpy = jasmine.createSpy('newProject').andReturn(projectSpy); typeScriptProjectManager = new TypeScriptProjectManager(); @@ -79,7 +77,7 @@ describe('TypeScriptProjectManager', function () { projectConfigs = { project1: { }, project2: { } - } + }; initiProjectManager(); @@ -87,7 +85,7 @@ describe('TypeScriptProjectManager', function () { waits(15); runs(function () { expect(projectFactorySpy.callCount).toBe(2); - }) + }); }); @@ -98,23 +96,23 @@ describe('TypeScriptProjectManager', function () { projectConfigs = { default: {} - } + }; initiProjectManager(); typeScriptProjectManager.dispose(); waitsFor(() => projectSpy.dispose.callCount === 1, 'dispose should have been called'); runs(function() { expect(projectSpy.dispose.callCount).toBe(1); - }) + }); }); - }) + }); describe('change handling', function () { it('should dispose projects that have no more config when config changes', function () { projectConfigs = { project1: {}, project2: {} - } + }; initiProjectManager(); @@ -123,7 +121,7 @@ describe('TypeScriptProjectManager', function () { runs(function () { projectConfigs = { project1: {} - } + }; preferenceManagerMock.configChanged.dispatch(); }); @@ -131,7 +129,7 @@ describe('TypeScriptProjectManager', function () { waits(50); runs(function () { expect(projectSpy.dispose.callCount).toBe(1); - }) + }); }); @@ -139,7 +137,7 @@ describe('TypeScriptProjectManager', function () { projectConfigs = { project1: {}, project2: {} - } + }; initiProjectManager(); @@ -148,14 +146,14 @@ describe('TypeScriptProjectManager', function () { project1: {}, project2: {}, project3: {} - } + }; preferenceManagerMock.configChanged.dispatch(); waits(50); runs(function () { expect(projectFactorySpy.callCount).toBe(3); - }) + }); }); @@ -163,7 +161,7 @@ describe('TypeScriptProjectManager', function () { projectConfigs = { project1: {}, project2: {} - } + }; initiProjectManager(); @@ -173,22 +171,22 @@ describe('TypeScriptProjectManager', function () { waits(50); runs(function () { expect(projectSpy.update.callCount).toBe(2); - }) + }); }); - }) + }); describe('getProjectForFiles', function () { beforeEach(function () { - var i = 0. + var i = 0; projectFactorySpy.andCallFake(function () { var project = utils.clone(projectSpy); project.id = i++; project.getProjectFileKind = function (file: string) { - var map: {[index: string]: TypeScriptProject.ProjectFileKind} + var map: {[index: string]: TypeScriptProject.ProjectFileKind}; if (project.id === 0) { map = { '/file1.ts': TypeScriptProject.ProjectFileKind.SOURCE, @@ -209,25 +207,14 @@ describe('TypeScriptProjectManager', function () { return map[file]; }, project.getProjectFilesSet = () => { - var stringSet = new collections.StringSet() + var stringSet = new collections.StringSet(); stringSet.add('/file3.ts'); return stringSet; - } + }; return project; - }) - var dirConfig = { - module: 'amd', - sources: [ - './file1.ts' - ], - outDir: 'bin' - }, dir1Config = { - module: 'commonjs', - sources: [ - './file2.ts' - ], - outFile: 'index.js' - }; + }); + + projectConfigs = { project1: { @@ -244,7 +231,8 @@ describe('TypeScriptProjectManager', function () { ], outFile: 'index.js' } - } + }; + fileSystemMock.setFiles({ '/file1.ts': 'import file1 = require("file2")', '/file2.ts': 'import file4 = require("file4")', @@ -252,7 +240,7 @@ describe('TypeScriptProjectManager', function () { '/file4.ts': '' }); initiProjectManager(); - }) + }); it('should return a project that have the file as source if this project exist ', function () { var project: any; @@ -260,16 +248,17 @@ describe('TypeScriptProjectManager', function () { waitsFor(() => !!project, 'project should have been found'); runs(function () { expect(project.id).toBe(1); - }) + }); }); - it('should return a project that have the file has reference if this project exist and no project has the file as source', function () { + it('should return a project that have the file has reference if this project ' + + 'exist and no project has the file as source', function () { var project: any; typeScriptProjectManager.getProjectForFile('/file4.ts').then(proj => project = proj); waitsFor(() => !!project, 'project should have been found'); runs(function () { expect(project.id).toBe(1); - }) + }); }); @@ -279,28 +268,28 @@ describe('TypeScriptProjectManager', function () { waitsFor(() => !!project, 'project should have been found'); runs(function () { expect(project.id).toBe(2); - }) + }); }); it('should recreate a temp project if no project has file as source or reference nor the temp project', function () { var project: any; - typeScriptProjectManager.getProjectForFile('/file5.ts') + typeScriptProjectManager.getProjectForFile('/file5.ts'); typeScriptProjectManager.getProjectForFile('/file5.ts').then(proj => project = proj); waitsFor(() => !!project, 'project should have been found'); runs(function () { expect(project.id).toBe(3); - }) + }); }); it('should not recreate a temp project if the temp project has file as source or reference', function () { var project: any; - typeScriptProjectManager.getProjectForFile('/file3.ts') + typeScriptProjectManager.getProjectForFile('/file3.ts'); typeScriptProjectManager.getProjectForFile('/file3.ts').then(proj => project = proj); waitsFor(() => !!project, 'project should have been found'); runs(function () { expect(project.id).toBe(2); - }) + }); }); - }) + }); -}); \ No newline at end of file +}); diff --git a/src/test/projectTest.ts b/src/test/projectTest.ts index 60e797c..defe12a 100644 --- a/src/test/projectTest.ts +++ b/src/test/projectTest.ts @@ -22,21 +22,19 @@ import FileSystemMock = require('./fileSystemMock'); import WorkingSetMock = require('./workingSetMock'); import utils = require('../commons/typeScriptUtils'); -declare var __dirname: string; describe('TypeScriptProject', function () { var fileSystemMock: FileSystemMock, - typeScriptProjectSpy: jasmine.Spy, workingSetMock: WorkingSetMock, typeScriptProject: TypeScriptProject; beforeEach(function () { fileSystemMock = new FileSystemMock(), workingSetMock = new WorkingSetMock(); - }) + }); - var defaultLibLocation = '/lib.d.ts' + var defaultLibLocation = '/lib.d.ts'; function createProject(baseDir: string, config: TypeScriptProjectConfig, init = true) { typeScriptProject = new TypeScriptProject( baseDir, @@ -73,8 +71,8 @@ describe('TypeScriptProject', function () { function getProjectFileContent(fileName: string) { - var snapshot = typeScriptProject.getLanguageServiceHost().getScriptSnapshot(fileName) - return snapshot.getText(0, snapshot.getLength()) + var snapshot = typeScriptProject.getLanguageServiceHost().getScriptSnapshot(fileName); + return snapshot.getText(0, snapshot.getLength()); } describe('initialization', function () { @@ -95,7 +93,7 @@ describe('TypeScriptProject', function () { 'src/**/*ts' ] }); - waits(20) + waits(20); runs(function () { expectToBeEqualArray(typeScriptProject.getProjectFilesSet().values, [ '/root/file1.ts', @@ -103,8 +101,7 @@ describe('TypeScriptProject', function () { '/root/project/src/file4.ts', '/root/project/src/dir/file5.ts' ]); - }) - + }); }); it('should collect every files referenced or imported by files in the source ', function () { @@ -121,7 +118,7 @@ describe('TypeScriptProject', function () { 'src/**/*ts' ] }); - waits(20) + waits(20); runs(function () { expectToBeEqualArray(typeScriptProject.getProjectFilesSet().values, [ '/src/file1.ts', @@ -142,12 +139,12 @@ describe('TypeScriptProject', function () { fileSystemMock.addFile('/src/file1.ts', ''); - waits(20) + waits(20); runs(function () { expectToBeEqualArray(typeScriptProject.getProjectFilesSet().values, [ '/src/file1.ts' ]); - }) + }); }); @@ -165,7 +162,7 @@ describe('TypeScriptProject', function () { fileSystemMock.addFile('/src/file1.ts', 'import test = require("../other/file3")'); - waits(20) + waits(20); runs(function () { expectToBeEqualArray(typeScriptProject.getProjectFilesSet().values, [ '/src/file1.ts', @@ -188,14 +185,13 @@ describe('TypeScriptProject', function () { }); fileSystemMock.addFile('/other/file2.ts', ''); - waits(20) + waits(20); runs(function () { expectToBeEqualArray(typeScriptProject.getProjectFilesSet().values, [ '/src/file1.ts', '/other/file2.ts' ]); - }) - + }); }); it('should remove files from project when they are deleted', function () { @@ -211,12 +207,12 @@ describe('TypeScriptProject', function () { }); fileSystemMock.removeFile('/src/file1.ts'); - waits(20) + waits(20); runs(function () { expectToBeEqualArray(typeScriptProject.getProjectFilesSet().values, [ '/src/file2.ts' ]); - }) + }); }); it('should remove referenced files from the project when a source file referencing it is deleted', function () { @@ -234,7 +230,7 @@ describe('TypeScriptProject', function () { }); fileSystemMock.removeFile('/src/file1.ts'); - waits(20) + waits(20); runs(function () { expectToBeEqualArray(typeScriptProject.getProjectFilesSet().values, [ '/src/file2.ts' @@ -258,13 +254,13 @@ describe('TypeScriptProject', function () { }); fileSystemMock.removeFile('/src/file1.ts'); - waits(20) + waits(20); runs(function () { expectToBeEqualArray(typeScriptProject.getProjectFilesSet().values, [ '/src/file2.ts', '/other/file3.ts' ]); - }) + }); }); @@ -282,13 +278,13 @@ describe('TypeScriptProject', function () { }); fileSystemMock.removeFile('/other/file3.ts'); - waits(20) + waits(20); runs(function () { expectToBeEqualArray(typeScriptProject.getProjectFilesSet().values, [ '/src/file1.ts', '/src/file2.ts' ]); - }) + }); }); @@ -306,16 +302,16 @@ describe('TypeScriptProject', function () { }); fileSystemMock.removeFile('/other/file3.ts'); - fileSystemMock.addFile('/other/file3.ts',''); + fileSystemMock.addFile('/other/file3.ts', ''); - waits(20) + waits(20); runs(function () { expectToBeEqualArray(typeScriptProject.getProjectFilesSet().values, [ '/src/file1.ts', '/src/file2.ts', '/other/file3.ts' ]); - }) + }); }); @@ -357,7 +353,7 @@ describe('TypeScriptProject', function () { '/src/file1.ts', '/other/file2.ts' ]); - }) + }); }); @@ -379,7 +375,7 @@ describe('TypeScriptProject', function () { expectToBeEqualArray(typeScriptProject.getProjectFilesSet().values, [ '/src/file1.ts' ]); - }) + }); }); it('should add the default library if noLib is not specified or false', function () { @@ -393,7 +389,7 @@ describe('TypeScriptProject', function () { 'src/**/*ts' ] }); - waits(20) + waits(20); runs(function () { expect(typeScriptProject.getProjectFilesSet().has(defaultLibLocation)).toBe(true); }); @@ -414,7 +410,7 @@ describe('TypeScriptProject', function () { waits(20); runs(function () { expect(typeScriptProject.getProjectFilesSet().has(defaultLibLocation)).toBeFalsy(); - }) + }); }); @@ -443,8 +439,8 @@ describe('TypeScriptProject', function () { waits(50); runs(function () { - expect(typeScriptProject.getLanguageService()).toEqual({id: "hello"}) - }) + expect(typeScriptProject.getLanguageService()).toEqual({id: 'hello'}); + }); }); }); @@ -466,7 +462,7 @@ describe('TypeScriptProject', function () { 'src/file1.ts' ] }); - waits(15); + waits(20); }); function updateProject(config: TypeScriptProjectConfig) { @@ -474,19 +470,19 @@ describe('TypeScriptProject', function () { } it('should update compilerOptions if compiler options does have changed', function () { - expect(typeScriptProject.getLanguageServiceHost().getCompilationSettings().codeGenTarget).toBe(TypeScript.LanguageVersion.EcmaScript5); - updateProject({ + expect(typeScriptProject.getLanguageServiceHost().getCompilationSettings().codeGenTarget) + .toBe(TypeScript.LanguageVersion.EcmaScript5); + + updateProject({ target: 'es3', module: 'commonjs', - sources : [ - 'src/file1.ts' - ] + sources : [ 'src/file1.ts' ] }); - - waits(15); + waits(20); runs(function () { - expect(typeScriptProject.getLanguageServiceHost().getCompilationSettings().codeGenTarget).toBe(TypeScript.LanguageVersion.EcmaScript3) ; + expect(typeScriptProject.getLanguageServiceHost().getCompilationSettings().codeGenTarget) + .toBe(TypeScript.LanguageVersion.EcmaScript3); }); }); @@ -498,7 +494,7 @@ describe('TypeScriptProject', function () { sources : [] }); - waits(15); + waits(20); runs(function () { expect(typeScriptProject.getProjectFilesSet().has('/src/file1.ts')).toBeFalsy(); @@ -516,7 +512,7 @@ describe('TypeScriptProject', function () { ] }); - waits(15); + waits(20); runs(function () { expect(typeScriptProject.getProjectFilesSet().has('/src/file2.ts')).toBe(true); @@ -525,7 +521,7 @@ describe('TypeScriptProject', function () { it('should remove project files that are not referenced anymore in the source', function () { - expect(typeScriptProject.getProjectFilesSet().has('/src/file3.ts')).toBe(true) + expect(typeScriptProject.getProjectFilesSet().has('/src/file3.ts')).toBe(true); updateProject({ target: 'es3', module: 'commonjs', @@ -534,7 +530,7 @@ describe('TypeScriptProject', function () { ] }); - waits(15); + waits(20); runs(function () { expect(typeScriptProject.getProjectFilesSet().has('/src/file3.ts')).toBeFalsy(); @@ -552,7 +548,7 @@ describe('TypeScriptProject', function () { ] }); - waits(15); + waits(20); runs(function () { expect(typeScriptProject.getProjectFilesSet().has('/src/file4.ts')).toBe(true); @@ -568,7 +564,7 @@ describe('TypeScriptProject', function () { sources : [] }); - waits(15); + waits(20); runs(function () { expect(typeScriptProject.getProjectFilesSet().has('/lib.d.ts')).toBeFalsy(); @@ -580,7 +576,8 @@ describe('TypeScriptProject', function () { workingSetMock.files = [ '/src/file1.ts', '/src/file2.ts' - ] + ]; + updateProject({ target: 'es3', module: 'commonjs', @@ -589,7 +586,7 @@ describe('TypeScriptProject', function () { ] }); - waits(15); + waits(20); @@ -600,7 +597,7 @@ describe('TypeScriptProject', function () { it('should reinitialize the project if typeScriptPath has changed', function () { - var spy = spyOn(typeScriptProject,'init').andCallThrough(); + var spy = spyOn(typeScriptProject, 'init').andCallThrough(); expect(typeScriptProject.getProjectFilesSet().has('/src/file2.ts')).toBeFalsy(); updateProject({ @@ -628,10 +625,10 @@ describe('TypeScriptProject', function () { ] }); - waits(20) + waits(20); runs(function () { expect(typeScriptProject.getProjectFileKind('/src/file1.ts')).toBe(TypeScriptProject.ProjectFileKind.SOURCE); - }) + }); }); @@ -647,10 +644,10 @@ describe('TypeScriptProject', function () { ] }); - waits(20) + waits(20); runs(function () { - expect(typeScriptProject.getProjectFileKind('/other/file2.ts')).toBe(TypeScriptProject.ProjectFileKind.REFERENCE) - }) + expect(typeScriptProject.getProjectFileKind('/other/file2.ts')).toBe(TypeScriptProject.ProjectFileKind.REFERENCE); + }); }); it('should return \'NONE\' if the file is a nor a part of the project', function () { @@ -665,10 +662,10 @@ describe('TypeScriptProject', function () { ] }); - waits(20) + waits(20); runs(function () { expect(typeScriptProject.getProjectFileKind('/other/file2.ts')).toBe(TypeScriptProject.ProjectFileKind.NONE); - }) + }); }); }); @@ -681,20 +678,20 @@ describe('TypeScriptProject', function () { '/src/file2.ts': '', '/src/file3.ts': '', '/src/file4.ts': '', - '/src/file5.ts': '', + '/src/file5.ts': '' }); workingSetMock.files = [ '/src/file1.ts', '/src/file2.ts' - ] + ]; createProject('/', { sources : [ 'src/**/*ts' ] }); - waits(15) + waits(20); }); @@ -703,19 +700,19 @@ describe('TypeScriptProject', function () { }); it('should mark as \'open\' every file added to working set', function () { - workingSetMock.addFiles(['/src/file3.ts','/src/file4.ts']); - waits(20) + workingSetMock.addFiles(['/src/file3.ts', '/src/file4.ts']); + waits(20); runs(function () { testWorkingSetOpenCorrespondance(); - }) + }); }); it('should mark as \'closed\' every file removed from the working set', function () { workingSetMock.removeFiles(['/src/file1.ts']); - waits(20) + waits(20); runs(function () { testWorkingSetOpenCorrespondance(); - }) + }); }); }); @@ -730,7 +727,7 @@ describe('TypeScriptProject', function () { workingSetMock.files = [ '/src/file1.ts' - ] + ]; createProject('/', { sources : [ @@ -811,7 +808,7 @@ describe('TypeScriptProject', function () { }], documentText : 'console.warn(\'hello world\')' }); - }) + }); waits(20); @@ -873,4 +870,4 @@ describe('TypeScriptProject', function () { }); -}); \ No newline at end of file +}); diff --git a/src/test/signalTest.ts b/src/test/signalTest.ts index 93cf160..1c34ed8 100644 --- a/src/test/signalTest.ts +++ b/src/test/signalTest.ts @@ -79,4 +79,4 @@ describe('signals', function () { expect(sign.dispatch(null)).toBe(false); expect(spy.callCount).toBe(0); }); -}); \ No newline at end of file +}); diff --git a/src/test/workerBridgeTest.ts b/src/test/workerBridgeTest.ts index 699ab7f..6d15a4b 100644 --- a/src/test/workerBridgeTest.ts +++ b/src/test/workerBridgeTest.ts @@ -19,7 +19,7 @@ import WorkerBridge = require('../commons/workerBridge'); import signal = require('../commons/signal'); import es6Promise = require('es6-promise'); -import Promise = es6Promise.Promise;; +import Promise = es6Promise.Promise; class FakeWorker { private initialized: boolean; @@ -32,7 +32,7 @@ class FakeWorker { } postMessage(message: any): void { - if(!this.initialized) { + if (!this.initialized) { this.init(); } setTimeout(() => { @@ -53,11 +53,11 @@ class FakeWorker { if (this.onmessage) { this.onmessage({ data: JSON.parse(JSON.stringify(message)) }); } - }, 0) - } + }, 0); + }; - var workerContext: any = { postMessage: workerPostMessage } - this.source.call( workerContext , workerPostMessage) + var workerContext: any = { postMessage: workerPostMessage }; + this.source.call( workerContext , workerPostMessage); this.workerOnMessage = workerContext.onmessage; this.initialized = true; } @@ -95,7 +95,7 @@ describe('bridge', function () { } }); - waitsFor(()=> spy.callCount === 1, 'spy should have been called', 100); + waitsFor(() => spy.callCount === 1, 'spy should have been called', 100); }); @@ -107,7 +107,7 @@ describe('bridge', function () { myService: { myMethod: spy } - }) + }); }); @@ -115,7 +115,7 @@ describe('bridge', function () { services.myService.myMethod(); }); - waitsFor(()=> spy.callCount === 1, 'spy should have been called', 100); + waitsFor(() => spy.callCount === 1, 'spy should have been called', 100); }); @@ -129,16 +129,16 @@ describe('bridge', function () { return 10; } } - }) + }); }); var serviceResult: number; createBridge(worker, {}).then(services => { - services.myService.myMethod().then( (result:any) => serviceResult = result); + services.myService.myMethod().then( (result: any) => serviceResult = result); }); - waitsFor(()=> !!serviceResult, 'serviceResult should have been set', 100); + waitsFor(() => !!serviceResult, 'serviceResult should have been set', 100); runs(function () { expect(serviceResult).toBe(10); }); @@ -151,21 +151,21 @@ describe('bridge', function () { createBridge(this, { myService: { myMethod: function () { - return new Promise(resolve =>{ - resolve(10) - }) + return new Promise(resolve => { + resolve(10); + }); } } - }) + }); }); var serviceResult: number; createBridge(worker, {}).then(services => { - services.myService.myMethod().then( (result:any) => serviceResult = result); + services.myService.myMethod().then( (result: any) => serviceResult = result); }); - waitsFor(()=> !!serviceResult, 'serviceResult should have been set', 100); + waitsFor(() => !!serviceResult, 'serviceResult should have been set', 100); runs(function () { expect(serviceResult).toBe(10); }); @@ -181,16 +181,16 @@ describe('bridge', function () { return a + b; } } - }) + }); }); var serviceResult: number; createBridge(worker, {}).then(services => { - services.myService.myMethod(2, 3).then( (result:any) => serviceResult = result); + services.myService.myMethod(2, 3).then( (result: any) => serviceResult = result); }); - waitsFor(()=> !!serviceResult, 'serviceResult should have been set', 100); + waitsFor(() => !!serviceResult, 'serviceResult should have been set', 100); runs(function () { expect(serviceResult).toBe(5); }); @@ -206,7 +206,7 @@ describe('bridge', function () { throw new Error('my error message'); } } - }) + }); }); var serviceError: Error; @@ -215,7 +215,7 @@ describe('bridge', function () { services.myService.myMethod().then( undefined, (error: any) => serviceError = error); }); - waitsFor(()=> !!serviceError, 'errorMessage should have been set', 100); + waitsFor(() => !!serviceError, 'errorMessage should have been set', 100); runs(function () { expect(serviceError instanceof Error).toBe(true); expect(serviceError.message).toBe('my error message'); @@ -231,7 +231,7 @@ describe('bridge', function () { return new Promise((resolve, reject) => reject('my error')); } } - }) + }); }); var serviceError: Error; @@ -240,7 +240,7 @@ describe('bridge', function () { services.myService.myMethod().then( undefined, (error: any) => serviceError = error); }); - waitsFor(()=> !!serviceError, 'errorMessage should have been set', 100); + waitsFor(() => !!serviceError, 'errorMessage should have been set', 100); runs(function () { expect(serviceError instanceof Error).toBe(true); expect(serviceError.message).toBe('my error'); @@ -249,27 +249,27 @@ describe('bridge', function () { - it('if a service expose a signal, the proxied service should expose a signal that is synchronized with the original service', function () { + it('if a service expose a signal, the proxied service should expose a signal that ' + + 'is synchronized with the original service', function () { - var workerSignal = new signal.Signal() worker = new FakeWorker(function (postMessage) { createBridge(this, { signal: new signal.Signal() - }) + }); }); var exposedSignal: signal.Signal, - spy = jasmine.createSpy('onNext') + spy = jasmine.createSpy('onNext'); createBridge(worker, {}).then(services => { - exposedSignal = services.signal + exposedSignal = services.signal; }); - waitsFor(()=> !!exposedSignal, 'workerSignal should have been set', 100); + waitsFor(() => !!exposedSignal, 'workerSignal should have been set', 100); runs(function () { exposedSignal.add(spy); - exposedSignal.dispatch('hello') - exposedSignal.dispatch('world') + exposedSignal.dispatch('hello'); + exposedSignal.dispatch('world'); }); waits(100); runs(function () { @@ -278,4 +278,4 @@ describe('bridge', function () { }); }); -}); \ No newline at end of file +}); diff --git a/src/test/workingSetMock.ts b/src/test/workingSetMock.ts index 0496634..34c9d56 100644 --- a/src/test/workingSetMock.ts +++ b/src/test/workingSetMock.ts @@ -19,7 +19,7 @@ import ws = require('../commons/workingSet'); import signal = require('../commons/signal'); import es6Promise = require('es6-promise'); -import Promise = es6Promise.Promise;; +import Promise = es6Promise.Promise; class WorkingSetMock implements ws.IWorkingSet { files: string [] = []; @@ -45,7 +45,7 @@ class WorkingSetMock implements ws.IWorkingSet { removeFiles(paths: string[]) { - this.files = this.files.filter(path => paths.indexOf(path) === -1) + this.files = this.files.filter(path => paths.indexOf(path) === -1); this.workingSetChanged.dispatch({ kind: ws.WorkingSetChangeKind.REMOVE, paths: paths @@ -53,4 +53,4 @@ class WorkingSetMock implements ws.IWorkingSet { } } -export = WorkingSetMock; \ No newline at end of file +export = WorkingSetMock; diff --git a/src/test/workingSetTest.ts b/src/test/workingSetTest.ts index d0a6fb9..0b5a248 100644 --- a/src/test/workingSetTest.ts +++ b/src/test/workingSetTest.ts @@ -18,21 +18,20 @@ import WorkingSet = require('../main/workingSet'); import ws = require('../commons/workingSet'); -import signal = require('../commons/signal'); describe('WorkingSet', function (): void { var workingSetFiles: string[], documentManagerMock = { getWorkingSet() { - return workingSetFiles.map(file => { return { fullPath: file }}); + return workingSetFiles.map(file => ({ fullPath: file })); }, addFile(path: string) { - workingSetFiles.push(path) + workingSetFiles.push(path); $(this).triggerHandler('workingSetAdd', { fullPath: path }); }, addFiles(paths: string[]) { - workingSetFiles = workingSetFiles.concat(paths) - $(this).triggerHandler('workingSetAddList', paths.map(path => { return { fullPath: path }})); + workingSetFiles = workingSetFiles.concat(paths); + $(this).triggerHandler('workingSetAddList', paths.map(path => ({ fullPath: path }))); }, removeFile(path: string) { var index = workingSetFiles.indexOf(path); @@ -43,7 +42,7 @@ describe('WorkingSet', function (): void { }, removeFiles(paths: string[]) { workingSetFiles = workingSetFiles.filter(path => paths.indexOf(path) === -1); - $(this).triggerHandler('workingSetRemoveList', paths.map(path => { return { fullPath: path }})) + $(this).triggerHandler('workingSetRemoveList', paths.map(path => ({ fullPath: path }))); } }, @@ -53,9 +52,9 @@ describe('WorkingSet', function (): void { return currentEditor; }, setActiveEditor(editor: brackets.Editor) { - var previous = currentEditor + var previous = currentEditor; currentEditor = editor; - $(this).triggerHandler("activeEditorChange", [currentEditor, previous]); + $(this).triggerHandler('activeEditorChange', [currentEditor, previous]); } }, workingSet: WorkingSet; @@ -70,11 +69,11 @@ describe('WorkingSet', function (): void { currentEditor = { document : { file: {fullPath : '/path/file1.ts'}, - getText() { return 'hello world'} + getText() { return 'hello world'; } } }; workingSet = new WorkingSet(documentManagerMock, editorManagerMock ); - }) + }); afterEach(function () { workingSet.dispose(); @@ -82,12 +81,12 @@ describe('WorkingSet', function (): void { function expectWorkingSetFilesMatch() { var files: string[]; - workingSet.getFiles().then(result => files = result) - waitsFor(() => !!files, 'files should have been set') + workingSet.getFiles().then(result => files = result); + waitsFor(() => !!files, 'files should have been set'); runs(function () { expect(files).toEqual(workingSetFiles); - }) + }); } describe('files', function () { @@ -97,7 +96,7 @@ describe('WorkingSet', function (): void { }); describe('workingSetChanged', function () { - var spy = jasmine.createSpy('workingSetChangedHandler') + var spy = jasmine.createSpy('workingSetChangedHandler'); beforeEach(function () { workingSet.workingSetChanged.add(spy); @@ -164,7 +163,7 @@ describe('WorkingSet', function (): void { it('should notify when a document has been edited', function () { - var doc = currentEditor.document + var doc = currentEditor.document; $(doc).triggerHandler('change', [doc, [{ from : { @@ -175,7 +174,7 @@ describe('WorkingSet', function (): void { ch: 0, line: 0, }, - text : ['\'use strict\'','console.log(\'Hello World\')'], + text : ['\'use strict\'', 'console.log(\'Hello World\')'], removed : [''] }, { from : { @@ -203,7 +202,7 @@ describe('WorkingSet', function (): void { }, text: '\'use strict\'\nconsole.log(\'Hello World\')', removed: '' - },{ + }, { from : { ch: 8, line: 1 diff --git a/src/ts-worker/completionService.ts b/src/ts-worker/completionService.ts index 919732e..8a4d73e 100644 --- a/src/ts-worker/completionService.ts +++ b/src/ts-worker/completionService.ts @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -'use strict' +'use strict'; import es6Promise = require('es6-promise'); import Promise = es6Promise.Promise; @@ -52,7 +52,7 @@ class CompletionService implements completion.ICompletionService { typeScriptEntries = completionInfo && completionInfo.entries; - if(!typeScriptEntries) { + if (!typeScriptEntries) { return { entries: [], match: '' }; } @@ -61,7 +61,7 @@ class CompletionService implements completion.ICompletionService { match: string; if (currentToken && this.isValidTokenKind(currentToken.token().tokenKind)) { - match= currentToken.token().fullText(); + match = currentToken.token().fullText(); if (currentToken.element().leadingTrivia()) { match = match.substr(currentToken.element().leadingTriviaWidth()); } @@ -76,8 +76,8 @@ class CompletionService implements completion.ICompletionService { } typeScriptEntries.sort((entry1, entry2) => { - var match1 = entry1? entry1.name.indexOf(match): -1, - match2 = entry2? entry2.name.indexOf(match): -1; + var match1 = entry1 ? entry1.name.indexOf(match) : -1, + match2 = entry2 ? entry2.name.indexOf(match) : -1; if (match1 === 0 && match2 !== 0) { return -1; } else if (match2 === 0 && match1 !== 0) { @@ -86,15 +86,12 @@ class CompletionService implements completion.ICompletionService { var name1 = entry1 && entry1.name.toLowerCase(), name2 = entry2 && entry2.name.toLowerCase(); - if(name1 < name2) { + if (name1 < name2) { return -1; - } - else if(name1 > name2) { + } else if (name1 > name2) { return 1; - } - - else { - return 0 + } else { + return 0; } } }); @@ -109,7 +106,7 @@ class CompletionService implements completion.ICompletionService { }; - switch(typeScriptEntry.kind) { + switch (typeScriptEntry.kind) { case ScriptElementKind.unknown: case ScriptElementKind.primitiveType: case ScriptElementKind.scriptElement: @@ -166,7 +163,7 @@ class CompletionService implements completion.ICompletionService { return { entries: completionEntries, match : match - } + }; }).catch(() => ({ entries: [], match : '' @@ -178,9 +175,9 @@ class CompletionService implements completion.ICompletionService { */ private isValidTokenKind(tokenKind: number) { return tokenKind === TypeScript.SyntaxKind.IdentifierName || - (tokenKind >= TypeScript.SyntaxKind.BreakKeyword && tokenKind < TypeScript.SyntaxKind.OpenBraceToken) + (tokenKind >= TypeScript.SyntaxKind.BreakKeyword && tokenKind < TypeScript.SyntaxKind.OpenBraceToken); } } -export = CompletionService; \ No newline at end of file +export = CompletionService; diff --git a/src/ts-worker/definitionService.ts b/src/ts-worker/definitionService.ts index 22e07f1..f5ca688 100644 --- a/src/ts-worker/definitionService.ts +++ b/src/ts-worker/definitionService.ts @@ -12,12 +12,12 @@ // See the License for the specific language governing permissions and // limitations under the License. -'use strict' +'use strict'; import TypeScriptProjectManager = require('./projectManager'); import es6Promise = require('es6-promise'); -import definition = require('../commons/definition') +import definition = require('../commons/definition'); import Promise = es6Promise.Promise; @@ -59,11 +59,11 @@ class DefinitionService implements definition.IDefinitionService { lineEnd : endPos.line, charEnd : endPos.ch, fileName: definition.fileName - } + }; }); - }).catch(() => []) + }).catch(() => []); } } -export = DefinitionService; \ No newline at end of file +export = DefinitionService; diff --git a/src/ts-worker/errorService.ts b/src/ts-worker/errorService.ts index c2e3baf..1643f42 100644 --- a/src/ts-worker/errorService.ts +++ b/src/ts-worker/errorService.ts @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -'use strict' +'use strict'; import TypeScriptProjectManager = require('./projectManager'); @@ -25,11 +25,11 @@ import IErrorService = require('../commons/errorService'); */ var Type = { /** Unambiguous error, such as a syntax error */ - ERROR: "problem_type_error", + ERROR: 'problem_type_error', /** Maintainability issue, probable error / bad smell, etc. */ - WARNING: "problem_type_warning", + WARNING: 'problem_type_warning', /** Inspector unable to continue, code too complex for static analysis, etc. Not counted in error/warning tally. */ - META: "problem_type_meta" + META: 'problem_type_meta' }; /** @@ -69,8 +69,8 @@ class ErrorService implements IErrorService { return { errors: [], aborted: false - } - }) + }; + }); } /** @@ -83,9 +83,9 @@ class ErrorService implements IErrorService { } return diagnostics.map(diagnostic => { var info = diagnostic.info(), - type: string + type: string; - switch(info.category) { + switch (info.category) { case TypeScript.DiagnosticCategory.Error: type = Type.ERROR; break; @@ -116,4 +116,4 @@ class ErrorService implements IErrorService { } } -export = ErrorService; \ No newline at end of file +export = ErrorService; diff --git a/src/ts-worker/index.ts b/src/ts-worker/index.ts index d969183..8207553 100644 --- a/src/ts-worker/index.ts +++ b/src/ts-worker/index.ts @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -'use strict' +'use strict'; // inject global in the worker global.TypeScript = require('typescriptServices'); @@ -27,7 +27,6 @@ import CompletionService = require('./completionService'); import LexicalStructureService = require('./lexicalStructureService'); import WorkerBridge = require('../commons/workerBridge'); import logger = require('../commons/logger'); -import path = require('path'); //instantiate the different service var projectManager = new TypeScriptProjectManager(), @@ -49,11 +48,16 @@ bridge.init({ proxy.getLogLevel().then((logLevel: string) => { self.console = proxy.console; logger.setLogLevel(logLevel); - projectManager.init(location, proxy.preferencesManager, proxy.fileSystem, proxy.workingSet, TypeScriptProject.newProject).then(( )=>{ + projectManager.init( + location, + proxy.preferencesManager, + proxy.fileSystem, proxy.workingSet, + TypeScriptProject.newProject + ).then(() => { if (logger.information()) { - logger.log('TSWorker : initilialization complete') + logger.log('TSWorker : initilialization complete'); } - }) + }); }); - }) -}); \ No newline at end of file + }); +}); diff --git a/src/ts-worker/languageServiceHost.ts b/src/ts-worker/languageServiceHost.ts index 173cc43..869d73f 100644 --- a/src/ts-worker/languageServiceHost.ts +++ b/src/ts-worker/languageServiceHost.ts @@ -40,7 +40,7 @@ class LanguageServiceHost extends logger.LogingClass implements TypeScript.Servi * @param fileName the absolute path of the file * @param content the file content */ - addScript(fileName: string, content:string) { + addScript(fileName: string, content: string) { var script = new ScriptInfo(fileName, content); this.fileNameToScript.set(fileName, script); } @@ -75,7 +75,7 @@ class LanguageServiceHost extends logger.LogingClass implements TypeScript.Servi script.updateContent(content); return; } - throw new Error("No script with name '" + fileName + "'"); + throw new Error('No script with name \'' + fileName + '\''); } /** @@ -93,7 +93,7 @@ class LanguageServiceHost extends logger.LogingClass implements TypeScript.Servi return; } - throw new Error("No script with name '" + fileName + "'"); + throw new Error('No script with name \'' + fileName + '\''); } /** @@ -105,11 +105,11 @@ class LanguageServiceHost extends logger.LogingClass implements TypeScript.Servi setScriptIsOpen(fileName: string, isOpen: boolean) { var script = this.fileNameToScript.get(fileName); if (script) { - script.isOpen = isOpen + script.isOpen = isOpen; return; } - throw new Error("No script with name '" + fileName + "'"); + throw new Error('No script with name \'' + fileName + '\''); } /** @@ -143,7 +143,7 @@ class LanguageServiceHost extends logger.LogingClass implements TypeScript.Servi getIndexFromPos(fileName: string, position: CodeMirror.Position): number { var script = this.fileNameToScript.get(fileName); if (script) { - return script.getPositionFromLine(position.line, position.ch) + return script.getPositionFromLine(position.line, position.ch); } return -1; } @@ -161,7 +161,7 @@ class LanguageServiceHost extends logger.LogingClass implements TypeScript.Servi return { ch: tsPosition.character, line: tsPosition.line - } + }; } return null; } @@ -212,11 +212,11 @@ class LanguageServiceHost extends logger.LogingClass implements TypeScript.Servi } getDiagnosticsObject(): TypeScript.Services.ILanguageServicesDiagnostics { - return new LanguageServicesDiagnostics(""); + return new LanguageServicesDiagnostics(''); } getLocalizedDiagnosticMessages(): string { - return ""; + return ''; } fileExists(s: string) { @@ -256,7 +256,8 @@ class ScriptInfo { * @param isOpen the open status of the script * @param byteOrderMark */ - constructor(fileName: string, content: string, isOpen = false, byteOrderMark: TypeScript.ByteOrderMark = TypeScript.ByteOrderMark.None) { + constructor(fileName: string, content: string, isOpen = false, + byteOrderMark: TypeScript.ByteOrderMark = TypeScript.ByteOrderMark.None) { this.fileName = fileName; this.content = content; this.isOpen = isOpen; @@ -320,7 +321,7 @@ class ScriptInfo { */ getLineAndColForPositon(position: number) { var lineAndChar = { line: -1, character: -1}; - this.lineMap.fillLineAndCharacterFromPosition(position, lineAndChar) + this.lineMap.fillLineAndCharacterFromPosition(position, lineAndChar); return lineAndChar; } @@ -395,4 +396,4 @@ class LanguageServicesDiagnostics implements TypeScript.Services.ILanguageServic } -export = LanguageServiceHost; \ No newline at end of file +export = LanguageServiceHost; diff --git a/src/ts-worker/lexicalStructureService.ts b/src/ts-worker/lexicalStructureService.ts index e844a25..04995eb 100644 --- a/src/ts-worker/lexicalStructureService.ts +++ b/src/ts-worker/lexicalStructureService.ts @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -'use strict' +'use strict'; import TypeScriptProjectManager = require('./projectManager'); @@ -52,4 +52,4 @@ class LexicalStructureService implements ls.ILexicalStructureService { } } -export = LexicalStructureService; \ No newline at end of file +export = LexicalStructureService; diff --git a/src/ts-worker/project.ts b/src/ts-worker/project.ts index e829845..f0d0b95 100644 --- a/src/ts-worker/project.ts +++ b/src/ts-worker/project.ts @@ -12,16 +12,15 @@ // See the License for the specific language governing permissions and // limitations under the License. -'use strict' +'use strict'; import path = require('path'); import minimatch = require('minimatch'); import es6Promise = require('es6-promise'); -import Promise = es6Promise.Promise;; -import PromiseQueue = require('../commons/promiseQueue') +import Promise = es6Promise.Promise; +import PromiseQueue = require('../commons/promiseQueue'); import Services = TypeScript.Services; -import signal = require('../commons/signal'); import collections = require('../commons/collections'); import fs = require('../commons/fileSystem'); import ws = require('../commons/workingSet'); @@ -160,8 +159,8 @@ class TypeScriptProject { return Promise.all(promises) .then(() => this.collectFiles()) - .then(() => this.updateWorkingSet()) - }) + .then(() => this.updateWorkingSet()); + }); } /** @@ -222,7 +221,7 @@ class TypeScriptProject { TypeScriptProject.ProjectFileKind.REFERENCE ; } else { - return TypeScriptProject.ProjectFileKind.NONE + return TypeScriptProject.ProjectFileKind.NONE; } } @@ -240,7 +239,7 @@ class TypeScriptProject { return Promise.cast({ factory: new Services.TypeScriptServicesFactory(), libLocation: this.defaultLibLocation - }) + }); } else { var typescriptServicesFile = path.join(typescriptPath, 'typescriptServices.js'); @@ -252,18 +251,18 @@ class TypeScriptProject { return { factory: new typeScript.Services.TypeScriptServicesFactory(), libLocation: path.join(typescriptPath, 'lib.d.ts') - } + }; }) //TODO instead of silently returning default we should handle this error in project //manager and return an error in the linter .catch(() => { if (logger.error()) { - logger.log('could not retrieve typescript compiler at path: ' + typescriptPath) + logger.log('could not retrieve typescript compiler at path: ' + typescriptPath); } return { factory: new Services.TypeScriptServicesFactory(), libLocation: this.defaultLibLocation - } + }; }); } } @@ -271,7 +270,7 @@ class TypeScriptProject { /** * create Typescript compilation settings from config file */ - private createCompilationSettings() : TypeScript.CompilationSettings { + private createCompilationSettings(): TypeScript.CompilationSettings { var compilationSettings = new TypeScript.CompilationSettings(), moduleType = this.config.module.toLowerCase(); @@ -288,11 +287,11 @@ class TypeScriptProject { moduleType === 'none' ? TypeScript.ModuleGenTarget.Unspecified : moduleType === 'amd' ? - TypeScript.ModuleGenTarget.Asynchronous: + TypeScript.ModuleGenTarget.Asynchronous : TypeScript.ModuleGenTarget.Synchronous ; - return compilationSettings + return compilationSettings; } /** @@ -356,7 +355,7 @@ class TypeScriptProject { promises.push(this.addFile(referencedFile)); this.addReference(fileName, referencedFile); }); - return Promise.all(promises) + return Promise.all(promises); }, (): any => { this.projectFilesSet.remove(fileName); }); @@ -405,7 +404,7 @@ class TypeScriptProject { */ private getReferencedOrImportedFiles(fileName: string): string[] { if (!this.projectFilesSet.has(fileName)) { - return [] + return []; } var script = this.languageServiceHost.getScriptSnapshot(fileName), preProcessedFileInfo = this.coreService.getPreProcessedFileInfo(fileName, script), @@ -428,7 +427,7 @@ class TypeScriptProject { if (!this.references.has(referencedPath)) { this.references.set(referencedPath, new collections.StringSet()); } - this.references.get(referencedPath).add(fileName) + this.references.get(referencedPath).add(fileName); } /** @@ -496,8 +495,8 @@ class TypeScriptProject { break; } }); - }) - } + }); + }; /** * handle changes in the workingSet @@ -522,7 +521,7 @@ class TypeScriptProject { break; } }); - } + }; /** * handle document edition @@ -548,7 +547,7 @@ class TypeScriptProject { if (mustUpdate || this.languageServiceHost.getScriptContent(record.path) !== record.documentText) { if (logger.warning()) { if (mustUpdate) { - logger.log('TypeScriptProject: inconsistent change descriptor: ' + JSON.stringify(lastChange)) + logger.log('TypeScriptProject: inconsistent change descriptor: ' + JSON.stringify(lastChange)); } else { logger.log('TypeScriptProject: text different before and after change'); } @@ -559,7 +558,7 @@ class TypeScriptProject { this.updateReferences(record.path, oldPaths); } }); - } + }; } diff --git a/src/ts-worker/projectManager.ts b/src/ts-worker/projectManager.ts index 35ba74a..04772bb 100644 --- a/src/ts-worker/projectManager.ts +++ b/src/ts-worker/projectManager.ts @@ -12,14 +12,13 @@ // See the License for the specific language governing permissions and // limitations under the License. -'use strict' +'use strict'; import es6Promise = require('es6-promise'); import Promise = es6Promise.Promise; import path = require('path'); -import PromiseQueue = require('../commons/promiseQueue') -import signal = require('../commons/signal'); +import PromiseQueue = require('../commons/promiseQueue'); import ws = require('../commons/workingSet'); import fs = require('../commons/fileSystem'); import TypeScriptPreferenceManager = require('../commons/preferencesManager'); @@ -29,7 +28,6 @@ import tsUtils = require('../commons/typeScriptUtils'); import utils = require('../commons/utils'); import logger = require('../commons/logger'); import TypeScriptProject = require('./project'); -import Services = TypeScript.Services; //-------------------------------------------------------------------------- // @@ -150,14 +148,14 @@ class TypeScriptProjectManager { getProjectForFile(fileName: string): Promise { return this.queue.then((): any => { var projects = this.projectMap.values, - project : TypeScriptProject = null; + project: TypeScriptProject = null; //first we check for a project that have tha file as source projects.some(tsProject => { if (tsProject.getProjectFileKind(fileName) === TypeScriptProject.ProjectFileKind.SOURCE) { project = tsProject; return true; } - }) + }); //then we check if a project has a file referencing the given file @@ -218,7 +216,7 @@ class TypeScriptProjectManager { /** * dispose every projects created by the ProjectManager */ - private disposeProjects():void { + private disposeProjects(): void { var projectMap = this.projectMap; projectMap.keys.forEach(path => { projectMap.get(path).dispose(); @@ -250,9 +248,9 @@ class TypeScriptProjectManager { this.projectMap.set(projectId, project); }, () => { if (logger.fatal()) { - logger.log('could not create project:' + projectId) + logger.log('could not create project:' + projectId); } - }) + }); } @@ -278,16 +276,16 @@ class TypeScriptProjectManager { } else { promises.push(project.update(config)); } - }) + }); Object.keys(configs).forEach(projectId => { if (!this.projectMap.has(projectId)) { - promises.push(this.createProjectFromConfig(projectId, configs[projectId])) + promises.push(this.createProjectFromConfig(projectId, configs[projectId])); } - }) + }); }); }); - } + }; } module TypeScriptProjectManager { diff --git a/tslint.json b/tslint.json index ab95352..1960fcc 100644 --- a/tslint.json +++ b/tslint.json @@ -3,40 +3,41 @@ "class-name": true, "curly": true, "eofline": true, - "forin": false, - "jsdoc-format": true, "indent": [true, 4], "label-position": true, "label-undefined": true, + "max-line-length": [true, 140], "no-arg": true, "no-bitwise": true, "no-construct": true, "no-debugger": true, "no-duplicate-key": true, "no-duplicate-variable": true, - "no-empty": false, "no-eval": true, "no-string-literal": true, - "no-trailing-whitespace": false, + "no-trailing-comma": true, + "no-unused-variable": true, "no-unreachable": true, - "one-line": [ - true, + "one-line": [true, "check-open-brace", "check-catch", "check-else", "check-whitespace" ], - "quotemark": [true, "simple"], + "quotemark": [true, "single"], "radix": true, "semicolon": true, "triple-equals": [true, "allow-null-check"], - "typedef-whitespace": [ - true, - "callSignature", - "catchClause", - "indexSignature" - ], - "variable-name": false, + "typedef-whitespace": [true, + { + "callSignature": "nospace", + "catchClause": "nospace", + "indexSignature": "nospace", + "parameter": "nospace", + "propertySignature": "nospace", + "variableDeclarator": "nospace" + } + ], "whitespace": [true, "check-branch", "check-decl",