export async function computeWorkspaceType(): Promise<HaskellWorkspaceType> {
    const configType =
        vscode.workspace.getConfiguration('ghcSimple').workspaceType as
            HaskellWorkspaceType | 'detect';

    if (configType !== 'detect') return configType;

    const isStack = await vscode.workspace.findFiles('stack.yaml');
    if (isStack.length > 0)
        return 'stack';
    
    const isCabal = await vscode.workspace.findFiles('**/*.cabal');
    if (isCabal.length > 0)
        return 'cabal';

    const hasStack = await new Promise<boolean>((resolve, reject) => {
            const cp = child_process.exec(
                'stack --help',
                {
                    cwd: vscode.workspace.rootPath,
                    timeout: 5000
                }, (err, stdout, stderr) => {
                    if (err) resolve(false);
                    else resolve(true);
                }
            )
        });

    if (hasStack)
        return 'bare-stack'
    else
        return 'bare';
}
Example #2
0
function selectDotEnsime(callback, filterMethod = (dotEnsime) => true) {
    let dirs = [vscode.workspace.rootPath]

    let dotEnsimeUris = vscode.workspace.findFiles("**/.ensime", "node_modules", 10)

    let toString = (uris: vscode.Uri[]) => uris.map((uri) => uri.fsPath)
    dotEnsimeUris.then((uris) => {
      if(!uris) {
          vscode.window.showErrorMessage("You are not in a workspace. Please open a project before using ENSIME.")
          return
      }

      let dotEnsimes = toString(uris)

      let filteredDotEnsime = dotEnsimes.filter(filterMethod)

      if(filteredDotEnsime.length == 0)
      {
        vscode.window.showErrorMessage("No .ensime file found. Please generate with `sbt gen-ensime` or similar")
      }
      else if (filteredDotEnsime.length == 1)
      {
        callback(filteredDotEnsime[0])
      }
      else
      {
          vscode.window.showQuickPick(filteredDotEnsime).then((item) => callback(item))
      }
    })
}
Example #3
0
async function detectNpmScripts(): Promise<Task[]> {

	let emptyTasks: Task[] = [];
	let allTasks: Task[] = [];
	let visitedPackageJsonFiles: Set<string> = new Set();

	let folders = workspace.workspaceFolders;
	if (!folders) {
		return emptyTasks;
	}
	try {
		for (const folder of folders) {
			if (isAutoDetectionEnabled(folder)) {
				let relativePattern = new RelativePattern(folder, '**/package.json');
				let paths = await workspace.findFiles(relativePattern, '**/node_modules/**');
				for (const path of paths) {
					if (!isExcluded(folder, path) && !visitedPackageJsonFiles.has(path.fsPath)) {
						let tasks = await provideNpmScriptsForFolder(path);
						visitedPackageJsonFiles.add(path.fsPath);
						allTasks.push(...tasks);
					}
				}
			}
		}
		return allTasks;
	} catch (error) {
		return Promise.reject(error);
	}
}
Example #4
0
    private processAllFilesInWorkspace()
    {
        if (workspace.rootPath == undefined) return;
        var fileProcessCount = 0;
        // Find all the php files to process
        workspace.findFiles('**/*.php', '').then(files => {
            console.log(`Files to parse: ${files.length}`);
            fileProcessCount = files.length;
            var filePaths: string[] = [];
            // Get the objects path value for the current file system
            files.forEach(file => { filePaths.push(file.fsPath); });
            // Send the array of paths to the language server
            this.langClient.sendRequest({ method: "buildFromFiles" }, { files: filePaths });
        });

        // Update the UI so the user knows the processing status
        var fileProcessed: NotificationType<any> = { method: "fileProcessed" };
        this.langClient.onNotification(fileProcessed, data => {
            // Get the percent complete
            var percent:string = ((data.total / fileProcessCount) * 100).toFixed(2);
            this.statusBarItem.text = `$(zap) Processing source files (${data.total} of ${fileProcessCount} / ${percent}%)`;
            // Once all files have been processed, update the statusBarItem
            if(data.total == fileProcessCount){
                this.statusBarItem.text = 'File Processing Complete';
            }
        });
    }
Example #5
0
	let buildMap = async (args: any[]) => {
		let config = vscode.workspace.getConfiguration("wurst");

		let mapPromise: Thenable<string>;
		if (args && args.length > 0) {
			mapPromise = Promise.resolve(args[0]);
		} else {
			let items = workspace.findFiles('*.w3x', null, 10)
				.then(uris => uris.sort(function(a, b) {
					return fs.statSync(b.fsPath).mtime.getTime() -
							fs.statSync(a.fsPath).mtime.getTime();
				}))
				.then(uris => uris.map(uri => uri.path))
			mapPromise = window.showQuickPick(items)
		}
		let mappath = await mapPromise;
		if (!mappath) {
			return Promise.reject("No map selected.");
		}

		let request: ExecuteCommandParams = {
			command: "wurst.buildmap",
			arguments: [{
				'mappath': mappath
			}]
		};
		return client.sendRequest(ExecuteCommandRequest.type, request)
	};
Example #6
0
export async function provideNpmScripts(): Promise<Task[]> {
	let emptyTasks: Task[] = [];
	let allTasks: Task[] = [];

	let folders = workspace.workspaceFolders;
	if (!folders) {
		return emptyTasks;
	}
	try {
		for (let i = 0; i < folders.length; i++) {
			let folder = folders[i];
			if (isAutoDetectionEnabled(folder)) {
				let relativePattern = new RelativePattern(folder, '**/package.json');
				let paths = await workspace.findFiles(relativePattern, '**/node_modules/**');
				for (let j = 0; j < paths.length; j++) {
					if (!isExcluded(folder, paths[j])) {
						let tasks = await provideNpmScriptsForFolder(paths[j]);
						allTasks.push(...tasks);
					}
				}
			}
		}
		return allTasks;
	} catch (error) {
		return Promise.reject(error);
	}
}
Example #7
0
 function getYoForceConfig() {
     return vscode.workspace.findFiles('force.json', '').then(function (files) {
         var buffer: NodeBuffer = undefined;
         var data: any = {};
         if (files.length && files[0].path) {
             buffer = fs.readFileSync(files[0].path);
             try {
                 data = JSON.parse(buffer.toString());
             } catch (error) {
                 vscode.window.forceCode.outputChannel.appendLine(error);
             }
             return new Promise((resolve, reject) => {
                 try {
                     keychain.getPassword({
                         account: data.username,
                         service: constants.FORCECODE_KEYCHAIN,
                     }, function (err, pass) {
                         data.password = pass;
                         resolve(data);
                     });
                 } catch (error) {
                     console.error(error);
                     data.password = (vscode.window.forceCode.config.password || '') + (vscode.window.forceCode.config.token || '');
                     resolve(data);
                 }
             });
         }
         return data;
     });
 }
export function forceApexTestRun(testClass?: string) {
  if (testClass) {
    runTestClass(testClass);
  } else {
    vscode.workspace.findFiles('**/*.testSuite-meta.xml', '').then(files => {
      const fileItems: vscode.QuickPickItem[] = files.map(file => {
        return {
          label: path
            .basename(file.toString())
            .replace('.testSuite-meta.xml', ''),
          description: file.fsPath
        };
      });

      fileItems.push({
        label: 'All tests',
        description: 'Runs all tests in the current workspace'
      });

      vscode.window.showQuickPick(fileItems).then(selection => {
        if (selection) {
          if (selection.label === 'All tests') {
            runAllTests();
          } else {
            runTestSuite(selection.label);
          }
        }
      });
    });
  }
}
Example #9
0
export async function registerTaskProvider(ctx: vscode.ExtensionContext) {
	let rakePromise: Thenable<vscode.Task[]> | undefined = undefined;
	let files = await vscode.workspace.findFiles("**/[rR]akefile{,.rb}");
	for (let i = 0; i < files.length; i++) {
		rakeFiles.add(files[i]);
	}

	let fileWatcher = vscode.workspace.createFileSystemWatcher("**/[rR]akefile{,.rb}");
	fileWatcher.onDidChange(() => rakePromise = undefined);
	fileWatcher.onDidCreate((uri) => {
		rakeFiles.add(uri);
		rakePromise = undefined
	});
	fileWatcher.onDidDelete((uri) => {
		rakeFiles.delete(uri);
		rakePromise = undefined
	});

	let taskProvider = vscode.workspace.registerTaskProvider('rake', {
		provideTasks: () => {
			if (!rakePromise) {
				rakePromise = getRakeTasks();
			}
			return rakePromise;
		},
		resolveTask(_task: vscode.Task): vscode.Task | undefined {
			return undefined;
		}
	});
}
Example #10
0
	let startMap = async (cmd: "wurst.startmap" | "wurst.hotstartmap" , args: any[]) => {
		let config = vscode.workspace.getConfiguration("wurst");
		let wc3path = config.get<string>("wc3path");
		if (!wc3path) {
			return Promise.reject("Warcraft path not set (change 'wurst.wc3path' in your settings).");
		}

		let mapPromise: Thenable<string>;
		if (args && args.length > 0) {
			mapPromise = Promise.resolve(args[0]);
		} else {
			let items = workspace.findFiles('*.w3x', null, 10)
				.then(uris => uris.sort(function(a, b) {
					return fs.statSync(b.fsPath).mtime.getTime() -
							fs.statSync(a.fsPath).mtime.getTime();
				}))
				.then(uris => uris.map(uri => uri.path))
			mapPromise = window.showQuickPick(items)
		}
		let mappath = await mapPromise;
		if (!mappath) {
			return Promise.reject("No map selected.");
		}

		let request: ExecuteCommandParams = {
			command: cmd,
			arguments: [{
				'mappath': mappath,
				'wc3path': wc3path
			}]
		};
		_lastMapConfig = mappath
		return client.sendRequest(ExecuteCommandRequest.type, request)
	};
Example #11
0
export function findFiles(
  include: string,
  exclude: string,
  maxResults?: number,
  token?: vscode.CancellationToken): Thenable<vscode.Uri[]> {
  return vscode.workspace.findFiles(include, exclude, maxResults, token);
}
Example #12
0
export function findFilesForCache(searchPattern: string, rootPath: string) {
    let files = vscode.workspace.findFiles(searchPattern, "");
    files.then((value) => {
        this.addtocachefiles(value, rootPath);
    }, (reason) => {
        console.log(reason);
    });
}
Example #13
0
 (resolve, reject) =>
 {
     vscode.workspace.findFiles('**/'+fileWithoutExtension+ext, '', 1).then(
         (uris) =>
         {
             resolve(uris);
         }
     );
 }));
export function getWorkspaceConfigs(): PromiseLike<Object[]> {
    return workspace.findFiles('[tj]sconfig.json', '**/node_modules/**').then(files => {
        if (files && files.length > 0) {
            return files.map(file => JSON5.parse(readFileSync(file.fsPath).toString()));
        } else {
            return [];
        }
    });
}
Example #15
0
	let disposable = vscode.commands.registerCommand('ensime.startEnsime', () => {
		// The code you place here will be executed every time your command is executed

        let dotEnsimeUris = vscode.workspace.findFiles("**/.ensime", "node_modules", 10)
        let toString = (uris: vscode.Uri[]) => uris.map((uri) => uri.fsPath)
        let dotEnsimeStrings = dotEnsimeUris.then(toString)
        
        vscode.commands.registerCommand("ensime.stopEnsime", () => {
            
        });
        
        
        const config = vscode.workspace.getConfiguration('ensime');
        
        const onSelectedDotEnsime = (dotEnsimePath: string) => {
            console.log(dotEnsimePath)
            let dotEnsime = EnsimeClient.dotEnsimeUtils.parseDotEnsime(dotEnsimePath);
            console.log(dotEnsime);
            
            const serverStarter = function(parsedDotEnsime: EnsimeClient.DotEnsime, pidCallback: (string) => void) {
                console.log("hej server!");
                if (!fs.existsSync(parsedDotEnsime.cacheDir)) {
                    fs.mkdirSync(parsedDotEnsime.cacheDir);
                }
                const ensimeServerVersion = config.get("ensime.serverVersion", "0.9.10-SNAPSHOT");

                //     ensimeServerFlags = atom.config.get('Ensime.ensimeServerFlags')
                const ensimeServerFlags = "";
                
                const assemblyJar = mkAssemblyJarFileName(parsedDotEnsime.scalaEdition, ensimeServerVersion);
                    
                if(fs.existsSync(assemblyJar))
                    EnsimeClient.startServerFromAssemblyJar(assemblyJar, parsedDotEnsime, ensimeServerFlags, pidCallback);
                else {
                    const cpF = mkClasspathFileName(parsedDotEnsime.scalaVersion, ensimeServerVersion);
                    const startFromCPFile =
                        () => EnsimeClient.startServerFromFile(cpF, parsedDotEnsime, ensimeServerFlags, pidCallback);
                    
                    if(! classpathFileOk(cpF)) {
                        const nottin = (s: string, i: string) => {};
                        const pidLogger = () => (string) => {};
                        
                        const serverUpdater =
                            EnsimeClient.ensimeServerUpdate(updateDir(), pidLogger, nottin);
                        // EnsimeClient.ensimeServerUpdate(parsedDotEnsime, ensimeServerVersion, cpF, startFromCPFile);
                    } else
                        startFromCPFile();
                }
            };
            const startClient = EnsimeClient.ensimeClientStartup(serverStarter);
            // startClient(dotEnsime, )
        };
            
        vscode.window.showQuickPick(dotEnsimeStrings).then(onSelectedDotEnsime)
        
	});
Example #16
0
	return new Promise((resolve, reject) => {
		var uri: Uri = Uri.file('/dbconfig.json');
		workspace.findFiles('dbconfig.json', '').then(files => {
			if (files.length == 0) {
				noConfigFile();
				return;
			}
			resolve(files);
		});
	});
Example #17
0
	test('findFiles, cancellation', () => {

		const source = new CancellationTokenSource();
		const token = source.token; // just to get an instance first
		source.cancel();

		return workspace.findFiles('*.js', null, 100, token).then((res) => {
			assert.equal(res, void 0);
		});
	});
export default function getLaunchTargets(): Thenable<LaunchTarget[]> {

	if (!workspace.rootPath) {
		return Promise.resolve([]);
	}

	return workspace.findFiles('{**/*.sln,**/*.csproj,**/project.json}', '{**/node_modules/**,**/.git/**,**/bower_components/**}', 100).then(resources => {
		return select(resources, Uri.file(workspace.rootPath));
	});
}
Example #19
0
export function compileAllContracts(diagnosticCollection: vscode.DiagnosticCollection) {

    // Check if is folder, if not stop we need to output to a bin folder on rootPath
    if (vscode.workspace.rootPath === undefined) {
        vscode.window.showWarningMessage('Please open a folder in Visual Studio Code as a workspace');
        return;
    }

    let contractsCollection = new ContractCollection();
    let project = projService.initialiseProject();
    let solidityPath = '**/*.sol';
    if (project.projectPackage.sol_sources !== undefined || project.projectPackage.sol_sources === '') {
        solidityPath = project.projectPackage.sol_sources + '/' + solidityPath;
    }

    // TODO parse excluded files
    let excludePath = '**/bin/**';
    if (project.projectPackage.build_dir !== undefined || project.projectPackage.build_dir === '') {
        excludePath = '**/' + project.projectPackage.build_dir + '/**';
    }

    // Process open Text Documents first as it is faster (We might need to save them all first? Is this assumed?) 
    vscode.workspace.textDocuments.forEach(document => {

        if (path.extname(document.fileName) === '.sol') {
            let contractPath = document.fileName;
            let contractCode = document.getText();
            contractsCollection.addContractAndResolveImports(contractPath, contractCode, project);
        }
    });

    // Find all the other sol files, to compile them (1000 maximum should be enough for now)
    let files = vscode.workspace.findFiles(solidityPath, excludePath, 1000);

    return files.then(documents => {

        documents.forEach(document => {
            let contractPath = document.fsPath;

            // have we got this already opened? used those instead
            if (!contractsCollection.containsContract(contractPath)) {
                let contractCode = fs.readFileSync(document.fsPath, 'utf8');
                contractsCollection.addContractAndResolveImports(contractPath, contractCode, project);
            }
        });
        let sourceDirPath = util.formatPath(project.projectPackage.getSolSourcesAbsolutePath());
        let packagesPath = util.formatPath(project.packagesDir);
        compile(contractsCollection.getContractsForCompilation(),
                diagnosticCollection,
                project.projectPackage.build_dir,
                sourceDirPath,
                packagesPath);

    });
}
export function findLaunchTargets(options: Options): Thenable<LaunchTarget[]> {
    if (!vscode.workspace.workspaceFolders) {
        return Promise.resolve([]);
    }

    return vscode.workspace.findFiles(
            /*include*/ '{**/*.sln,**/*.csproj,**/project.json,**/*.csx,**/*.cake,**/*.cs}',
            /*exclude*/ '{**/node_modules/**,**/.git/**,**/bower_components/**}',
            /*maxResults*/ options.maxProjectResults)
        .then(resourcesToLaunchTargets);
}
Example #21
0
    public processWorkspaceFiles(rebuild: boolean = false) {
        if (workspace.rootPath == undefined) return;
        var fileProcessCount = 0;

        // Get PHP files from 'files.associations' to be processed
        var files = Config.phpFileTypes;

        // Exclude files ignored by the user
        files.exclude = files.exclude.concat(Config.ignoredPaths);

        // Find all the php files to process
        workspace.findFiles(`{${files.include.join(',')}}`, `{${files.exclude.join(',')}}`).then(files => {
            Debug.info(`Preparing to parse ${files.length} PHP source files...`);

            fileProcessCount = files.length;
            var filePaths: string[] = [];

            // Get the objects path value for the current file system
            files.forEach(file => {
                filePaths.push(file.fsPath);
            });

            Crane.statusBarItem.text = "$(zap) Indexing PHP files";

            // Send the array of paths to the language server
            Crane.langClient.onReady().then(() => {
                Crane.langClient.sendRequest("buildFromFiles", {
                    files: filePaths,
                    craneRoot: this.getCraneDir(),
                    projectPath: this.getProjectDir(),
                    treePath: this.getTreePath(),
                    enableCache: this.isCacheable(),
                    rebuild: rebuild
                });
            });

            // Update the UI so the user knows the processing status
            var fileProcessed: NotificationType<any, any> = new NotificationType("fileProcessed");
            Crane.langClient.onReady().then(() => {
                Crane.langClient.onNotification(fileProcessed, data => {
                    // Get the percent complete
                    var percent: string = ((data.total / fileProcessCount) * 100).toFixed(1);
                    Crane.statusBarItem.text = `$(zap) Indexing PHP files (${data.total} of ${fileProcessCount} / ${percent}%)`;
                    if (data.error) {
                        Debug.error("There was a problem parsing PHP file: " + data.filename);
                        Debug.error(`${data.error}`);
                    } else {
                        Debug.info(`Parsed file ${data.total} of ${fileProcessCount} : ${data.filename}`);
                    }
                });
            });
        });
    }
Example #22
0
            vscode.workspace.workspaceFolders.forEach(workspace => {

                let glob = vscode.workspace.getConfiguration('autoimport').get<string>('filesToScan');

                const relativePattern = new vscode.RelativePattern(workspace, glob);

                vscode.workspace.findFiles(relativePattern, '**/node_modules/**', 99999).then((files) => {
                    files.forEach((f, i) => {
                        FS.readFile(f.fsPath, 'utf8', (err, data) => {

                            if (err) {
                                return console.log(err);
                            }

                            let matches = data.match(/\bimport\s+(?:.+\s+from\s+)?[\'"]([^"\']+)["\']/g);

                            if (matches) {
                                matches.forEach(m => {
                                    if (m.indexOf('./') === -1 && m.indexOf('!') === -1) {
                                        let exports = m.match(/\bimport\s+(?:.+\s+from\s+)/),
                                            location = m.match(/[\'"]([^"\']+)["\']/g);

                                        if (exports && location) {
                                            let exportArray = exports[0]
                                                .replace('import', '')
                                                .replace('{', '')
                                                .replace('}', '')
                                                .replace('from', '')
                                                .split(',')
                                                .map(e => {
                                                    e = e.replace(/\s/g, ''); return e;
                                                })

                                            mapArrayToLocation(exportArray, location[0].replace("'", '')
                                                .replace("'", ""));
                                        }
                                    }
                                });
                            }

                            if (i == (files.length - 1)) {
                                for (let key in mappings) {
                                    if (mappings.hasOwnProperty(key)) {
                                        mappings[key] = _.uniq(mappings[key]);
                                    }
                                }
                                return resolve({ mappings, workspace });
                            }
                        });
                    });
                });

            });
  export async function getTruffleConfigUri(): Promise<Uri[]> {
    const workspaceRoot = getWorkspaceRoot();
    const configFiles = await workspace.findFiles(
      new RelativePattern(workspaceRoot, '{**/truffle-config.js}'),
      new RelativePattern(workspaceRoot, `{${ignoreWorkspace.join(',')}}`),
    );

    if (configFiles.length < 1) {
      throw new Error('Configuration does not found');
    }

    return configFiles;
  }
Example #24
0
File: crane.ts Project: ciruz/crane
    private processAllFilesInWorkspace()
    {
        if (workspace.rootPath == undefined) return;

        var fileProcessCount = 0;

        let craneSettings = workspace.getConfiguration("crane");
        let debugMode = false;
        if (craneSettings) {
            debugMode = craneSettings.get<boolean>("debugMode", false);
        }

        // Find all the php files to process
        workspace.findFiles('**/*.php', '').then(files => {
            console.log(`Files to parse: ${files.length}`);

            Debug.info(`Preparing to parse ${files.length} PHP source files...`);

            fileProcessCount = files.length;
            var filePaths: string[] = [];

            // Get the objects path value for the current file system
            files.forEach(file => {
                filePaths.push(file.fsPath);
            });

            // Send the array of paths to the language server
            this.langClient.sendRequest({ method: "buildFromFiles" }, { files: filePaths });
        });

        // Update the UI so the user knows the processing status
        var fileProcessed: NotificationType<any> = { method: "fileProcessed" };
        this.langClient.onNotification(fileProcessed, data => {
            // Get the percent complete
            var percent: string = ((data.total / fileProcessCount) * 100).toFixed(2);
            this.statusBarItem.text = `$(zap) Processing source files (${data.total} of ${fileProcessCount} / ${percent}%)`;

            if (data.error) {
                Debug.error("There was a problem parsing PHP file: " + data.filename);
                Debug.error(data.error);
            } else {
                Debug.info(`Parsed file ${data.total} of ${fileProcessCount} : ${data.filename}`);
            }

            // Once all files have been processed, update the statusBarItem
            if (data.total == fileProcessCount){
                Debug.info("Processing complete!");
                this.statusBarItem.text = '$(check) Processing of PHP source files complete';
            }
        });
    }
Example #25
0
async function getCakeScriptsAsTasks(): Promise<vscode.Task[]> {
    let workspaceRoot = vscode.workspace.rootPath;
    let emptyTasks: vscode.Task[] = [];

    if (!workspaceRoot) {
        return emptyTasks;
    }

    try {
        let cakeConfig = vscode.workspace.getConfiguration('cake');
        let files = await vscode.workspace.findFiles(cakeConfig.taskRunner.scriptsIncludePattern, cakeConfig.taskRunner.scriptsExcludePattern );
        if (files.length === 0) {
            return emptyTasks;
        }
        const result: vscode.Task[] = [];

        files.forEach(file => {
            const contents = fs.readFileSync(file.fsPath).toString();

            let taskRegularExpression = new RegExp(cakeConfig.taskRunner.taskRegularExpression, "g");

            let matches, taskNames = [];
            while (matches = taskRegularExpression.exec(contents)) {
                taskNames.push(matches[1]);
            }

            taskNames.forEach(taskName => {
                const kind: CakeTaskDefinition = {
                    type: 'cake',
                    script: taskName
                };

                let buildCommand = `./build.sh --target \"${taskName}\"`;
                if (os.platform() === "win32") {
                    buildCommand = `powershell -ExecutionPolicy ByPass -File build.ps1 -target \"${taskName}\"`;
                }

                const buildTask = new vscode.Task(kind, `Run ${taskName}`, 'Cake', new vscode.ShellExecution(`${buildCommand}`), []);
                buildTask.group = vscode.TaskGroup.Build;

                result.push(buildTask);
            });
        });

        return result;
    } catch (e) {
        return [];
    }
};
Example #26
0
	private async getTargetResource(resource: vscode.Uri): Promise<vscode.Uri | undefined> {
		if (resource.scheme !== fileSchemes.file) {
			return undefined;
		}

		if (this.client.apiVersion.gte(API.v292) && fs.lstatSync(resource.fsPath).isDirectory()) {
			const files = await vscode.workspace.findFiles({
				base: resource.fsPath,
				pattern: '**/*.{ts,tsx,js,jsx}',
			}, '**/node_modules/**', 1);
			return files[0];
		}

		return this._handles(resource) ? resource : undefined;
	}
Example #27
0
	private async getJsTsFileBeingMoved(resource: vscode.Uri): Promise<vscode.Uri | undefined> {
		if (resource.scheme !== fileSchemes.file) {
			return undefined;
		}

		if (await isDirectory(resource.fsPath)) {
			const files = await vscode.workspace.findFiles({
				base: resource.fsPath,
				pattern: '**/*.{ts,tsx,js,jsx}',
			}, '**/node_modules/**', 1);
			return files[0];
		}

		return (await this._handles(resource)) ? resource : undefined;
	}
Example #28
0
	public async getConfigsForWorkspace(): Promise<Iterable<TSConfig>> {
		if (!vscode.workspace.workspaceFolders) {
			return [];
		}
		const configs = new Map<string, TSConfig>();
		for (const config of await vscode.workspace.findFiles('**/tsconfig*.json', '**/node_modules/**')) {
			const root = vscode.workspace.getWorkspaceFolder(config);
			if (root) {
				configs.set(config.fsPath, {
					path: config.fsPath,
					workspaceFolder: root
				});
			}
		}
		return configs.values();
	}
Example #29
0
    updateCache(filename: string = ""): any {
        console.log("update cache");
        this.cacheUpdates = true;
        let rootPath = vscode.workspace.rootPath;
        if (rootPath) {
            this.db = this.cache.addCollection("ValueTable");
            this.dbcalls = this.cache.addCollection("Calls");

            let self = this;
            let files = vscode.workspace.findFiles("**/*.feature", "", 1000);
                files.then((value) => {
                    this.addtocachefiles(value, false);
                }, (reason) => {
                    console.log(reason);
                });
        }
    };
export function activate() { 
	// Create File System Watcher
	let watcher = workspace.createFileSystemWatcher('.travis.yml', false, false, true);
	watcher.onDidChange((e) => updateStatus());
	watcher.onDidCreate((e) => updateStatus());
	
	// Register Commands
	commands.registerCommand('extension.updateTravis', () => updateStatus());
	commands.registerCommand('extension.openInTravis', () => openInTravis());
	
	// Check if file already present
	workspace.findFiles('.travis.yml', '', 1).then((result) => {
		if (result && result.length > 0) {
			updateStatus();
		}
	});
}