vscode#RelativePattern TypeScript Examples

The following examples show how to use vscode#RelativePattern. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: dbtProject.ts    From vscode-dbt-power-user with MIT License 6 votes vote down vote up
private async findModelInTargetfolder(modelPath: Uri, type: string) { 
    if (this.targetPath === undefined) {
      return;
    }
    const baseName = path.basename(modelPath.fsPath);
    const targetModels = await workspace.findFiles(
      new RelativePattern(
        this.projectRoot,
        `${this.targetPath}/${type}/**/${baseName}`
      )
    );
    if (targetModels.length > 0) {
      commands.executeCommand("vscode.open", targetModels[0], {
        preview: false,
      });
    }
  }
Example #2
Source File: dbtProject.ts    From vscode-dbt-power-user with MIT License 6 votes vote down vote up
constructor(
    private dbtProjectContainer: DBTProjectContainer,
    private sourceFileWatchersFactory: SourceFileWatchersFactory,
    private dbtProjectLogFactory: DBTProjectLogFactory,
    private targetWatchersFactory: TargetWatchersFactory,
    private dbtCommandFactory: DBTCommandFactory,
    private terminal: DBTTerminal,
    path: Uri,
    _onManifestChanged: EventEmitter<ManifestCacheChangedEvent>
  ) {
    this.projectRoot = path;

    const dbtProjectConfigWatcher = workspace.createFileSystemWatcher(
      new RelativePattern(path, DBTProject.DBT_PROJECT_FILE)
    );

    setupWatcherHandler(dbtProjectConfigWatcher, () => this.tryRefresh());

    this.sourceFileWatchers = this.sourceFileWatchersFactory.createSourceFileWatchers(
      this.onProjectConfigChanged
    );
    this.onSourceFileChanged = this.sourceFileWatchers.onSourceFileChanged;

    this.dbtProjectLog = this.dbtProjectLogFactory.createDBTProjectLog(
      this.onProjectConfigChanged
    );

    this.disposables.push(
      this.targetWatchersFactory.createTargetWatchers(
        _onManifestChanged,
        this.onProjectConfigChanged
      ),
      dbtProjectConfigWatcher,
      this.onSourceFileChanged(() => this.listModels()),
      this.sourceFileWatchers,
      this.dbtProjectLog
    );
  }
Example #3
Source File: dbtWorkspaceFolder.ts    From vscode-dbt-power-user with MIT License 6 votes vote down vote up
async discoverProjects() {
    const dbtProjectFiles = await workspace.findFiles(
      new RelativePattern(
        this.workspaceFolder,
        `**/${DBTProject.DBT_PROJECT_FILE}`
      ),
      new RelativePattern(this.workspaceFolder, `**/{${DBTProject.DBT_MODULES.join(',')}}`)
    );
    // TODO: could potentially have issues with casing @camfrout
    return dbtProjectFiles
      .filter((uri) => this.notInVenv(uri.path))
      .map((uri) => Uri.file(uri.path.split("/")!.slice(0, -1).join("/")))
      .forEach((uri) => this.registerDBTProject(uri));
  }
Example #4
Source File: dbtWorkspaceFolder.ts    From vscode-dbt-power-user with MIT License 6 votes vote down vote up
private createConfigWatcher(): FileSystemWatcher {
    const watcher = workspace.createFileSystemWatcher(
      new RelativePattern(
        this.workspaceFolder,
        `**/${DBTProject.DBT_PROJECT_FILE}`
      )
    );

    const dirName = (uri: Uri) => Uri.file(path.dirname(uri.fsPath));

    watcher.onDidCreate((uri) => {
      if (this.notInVenv(uri.fsPath)) {
        this.registerDBTProject(dirName(uri));
      }
    });
    watcher.onDidDelete((uri) => this.unregisterDBTProject(dirName(uri)));
    this.disposables.push(watcher);
    return watcher;
  }
Example #5
Source File: dbtProjectLog.ts    From vscode-dbt-power-user with MIT License 6 votes vote down vote up
private onProjectConfigChanged(event: ProjectConfigChangedEvent) {
    const { projectName, projectRoot } = event;
    if (this.outputChannel === undefined) {
      this.outputChannel = window.createOutputChannel(
        `${projectName} dbt logs`
      );
      this.readLogFileFromLastPosition(event);

      this.logFileWatcher = workspace.createFileSystemWatcher(
        new RelativePattern(
          projectRoot.path,
          `${DBTProjectLog.LOG_PATH}/${DBTProjectLog.LOG_FILE}`
        )
      );
      setupWatcherHandler(this.logFileWatcher, () =>
        this.readLogFileFromLastPosition(event)
      );
      this.currentProjectName = projectName;
    }
    if (this.currentProjectName !== projectName) {
      this.outputChannel.dispose();
      this.outputChannel = window.createOutputChannel(
        `${projectName} dbt logs`
      );
      this.logPosition = 0;
      this.readLogFileFromLastPosition(event);
      this.currentProjectName = projectName;
    }
  }
Example #6
Source File: sourceFileWatchers.ts    From vscode-dbt-power-user with MIT License 6 votes vote down vote up
private onProjectConfigChanged(event: ProjectConfigChangedEvent) {
    const { sourcePaths, projectRoot } = event;
    if (
      this.currentSourcePaths === undefined ||
      !arrayEquals(this.currentSourcePaths, sourcePaths)
    ) {
      this.disposeWatchers();
      this.watchers = [];
      sourcePaths.forEach((sourcePath) => {
        const parsedSourcePath = Uri.parse(sourcePath);
        const globPattern = Uri.joinPath(
          parsedSourcePath,
          "**/*.sql"
        ).path.substring(1);
        const sourceFolderWatcher = workspace.createFileSystemWatcher(
          new RelativePattern(projectRoot, globPattern)
        );

        const debouncedSourceFileChangedEvent = debounce(
          () => this._onSourceFileChanged.fire(),
          2000
        );

        sourceFolderWatcher.onDidChange(() =>
          debouncedSourceFileChangedEvent()
        );
        this.watchers.push(sourceFolderWatcher);
      });
      this.currentSourcePaths = sourcePaths;
    }
  }
Example #7
Source File: targetWatchers.ts    From vscode-dbt-power-user with MIT License 6 votes vote down vote up
private createManifestWatcher(
    event: ProjectConfigChangedEvent
  ): FileSystemWatcher {
    const { targetPath, projectRoot } = event;
    const manifestWatcher = workspace.createFileSystemWatcher(
      new RelativePattern(
        projectRoot.path,
        `${targetPath}/${DBTProject.MANIFEST_FILE}`
      )
    );
    return manifestWatcher;
  }
Example #8
Source File: targetWatchers.ts    From vscode-dbt-power-user with MIT License 6 votes vote down vote up
private createTargetFolderWatcher(
    event: ProjectConfigChangedEvent
  ): FileSystemWatcher {
    const { targetPath, projectRoot } = event;
    const targetFolderWatcher = workspace.createFileSystemWatcher(
      new RelativePattern(projectRoot.path, targetPath)
    );
    return targetFolderWatcher;
  }
Example #9
Source File: file-watcher.ts    From karma-test-explorer with MIT License 6 votes vote down vote up
private registerFileHandler(
    filePatterns: readonly string[],
    handler: (filePath: string, changeType: FileChangeType) => void
  ): FileSystemWatcher[] {
    const fileWatchers: FileSystemWatcher[] = [];
    const workspaceRootPath = normalizePath(this.workspaceFolder.uri.fsPath);
    const relativeProjectRootPath = relative(workspaceRootPath, this.projectRootPath);
    const isProjectRootSameAsWorkspace = this.projectRootPath === workspaceRootPath;

    this.logger.debug(() => `Registering file handler for files: ${JSON.stringify(filePatterns, null, 2)}`);

    for (const fileOrPattern of filePatterns) {
      const relativeFileOrPattern = isProjectRootSameAsWorkspace
        ? fileOrPattern
        : normalizePath(join(relativeProjectRootPath, fileOrPattern));

      const absoluteFileOrPattern = new RelativePattern(this.workspaceFolder, relativeFileOrPattern);

      this.logger.debug(
        () =>
          `Creating file watcher for file or pattern '${fileOrPattern}' ` +
          `using base path: ${absoluteFileOrPattern.base}`
      );
      const fileWatcher = workspace.createFileSystemWatcher(absoluteFileOrPattern);
      fileWatchers.push(fileWatcher);

      this.disposables.push(
        fileWatcher.onDidChange(fileUri => handler(normalizePath(fileUri.fsPath), FileChangeType.Changed)),
        fileWatcher.onDidCreate(fileUri => handler(normalizePath(fileUri.fsPath), FileChangeType.Created)),
        fileWatcher.onDidDelete(fileUri => handler(normalizePath(fileUri.fsPath), FileChangeType.Deleted))
      );
    }
    return fileWatchers;
  }
Example #10
Source File: select-bclicense.ts    From al-objid with MIT License 6 votes vote down vote up
async function selectLicenseFromManifest(app: ALApp): Promise<string | undefined> {
    const folderPath: string = app.uri.fsPath;
    const pattern = new RelativePattern(folderPath, "**/*.bclicense");
    const files = await workspace.findFiles(pattern, null);
    if (files.length === 0) {
        UI.license.noLicenseFilesFound(app);
        return;
    }

    const picks = files.map(file => `.${file.fsPath.substring(folderPath.length)}`);
    return window.showQuickPick(picks, { placeHolder: "Select a *.bclicense file..." });
}
Example #11
Source File: FileWatcher.ts    From al-objid with MIT License 6 votes vote down vote up
private async setUpGitWatcher() {
        if (!(await Git.instance.isInitialized(this._uri))) {
            return;
        }

        this._gitAware = true;

        const updateBranchName = () => {
            // We don't want the branch change event immediately. If branch change affects this file,
            // then the relevant watcher event will update the branch name.
            setTimeout(async () => {
                this._gitBranch = await Git.instance.getCurrentBranchName(this._uri);
            }, 5000);
        };

        const gitRoot = await Git.instance.getTopLevelPath(this._uri);
        const gitHeadPattern = new RelativePattern(gitRoot, GIT_HEAD);
        this._gitWatcher = workspace.createFileSystemWatcher(gitHeadPattern);
        this._gitWatcher.onDidChange(updateBranchName);
        updateBranchName();
    }
Example #12
Source File: Controller.ts    From vscode-alxmldocumentation with MIT License 5 votes vote down vote up
/**
     * Initialize AL XML Documentation.
     */
    public async Initialize() {
        try 
        {
            await window.withProgress({
                location: ProgressLocation.Window,
                title: 'AL XML Documentation initialization in progress...',
            }, async (progress, token) => {
                let workspacePaths = workspace.workspaceFolders;
                if ((!workspacePaths) || (workspacePaths === undefined)) {
                    throw new Error('Workspace folders could not be retrieved.');
                }
    
                for (let validPath of workspacePaths) {
                    let allFiles = await workspace.findFiles(new RelativePattern(validPath, '**/*.al'), undefined, undefined, token);
                    let relevantFileTasks = allFiles.map(async (file: Uri) => {
                        let content = await readFile(file.fsPath, 'utf-8');
                        if (content.match(/(procedure|trigger|event)\s+(.*?)\(/gm)) {
                            return { uri: file, content: content };
                        }
    
                        return undefined;
                    });
                    let relevantFiles = await Promise.all(relevantFileTasks);
                    relevantFiles = relevantFiles.filter(f => f);
    
                    let tasks: Array<Promise<void>> = [];
                    let task = async (file: { uri: Uri, content: string }) => {
                        let document = Object.assign({});
                        document.getText = () => file.content;
                        document.fileName = file.uri.fsPath;
                        document.uri = file.uri;
                        
                        ALSyntaxUtil.GetALObject(document as any);
                    };
                    let max = relevantFiles.length;
                    for (let i = 0; i < max; i++) {
                        let file = relevantFiles[i];
                        tasks.push(task(file!));
    
                        if (i % 500 === 0) {
                            await Promise.all(tasks);
                            tasks = [];
                        }
                    }
    
                    if (tasks.length > 0) {
                        await Promise.all(tasks);
                    }
                }
    
                return true;
            });
        }
        catch (ex)
        {
            console.debug(ex);
        }
    }
Example #13
Source File: languageServerClient.ts    From vscode-stripe with MIT License 5 votes vote down vote up
/**
   * Returns a solutions file or project file if it exists in the workspace.
   *
   * If the user is working with multiple workspaces that contain C# projects, we don't know which one to run the server on, so we'll return the first one we find.
   * In the future, we may want to prompt the user to pick one, or expose a command that let's the user change the tracking project and restart.
   *
   * Returns [] if none of the workspaces are .NET projects.
   */
  static async getDotnetProjectFiles(): Promise<string[]> {
    const workspaceFolders = workspace.workspaceFolders;
    if (!workspaceFolders) {
      return [];
    }

    const projectFiles = await Promise.all(
      workspaceFolders.map(async (w) => {
        const workspacePath = w.uri.fsPath;

        // First look for solutions files. We only expect one solutions file to be present in a workspace.
        const pattern = new RelativePattern(workspacePath, '**/*.sln');

        // Files and folders to exclude
        // There may be more we want to exclude but starting with the same set omnisharp uses:
        // https://github.com/OmniSharp/omnisharp-vscode/blob/master/src/omnisharp/launcher.ts#L66
        const exclude = '{**/node_modules/**,**/.git/**,**/bower_components/**}';
        const sln = await workspace.findFiles(pattern, exclude, 1);
        if (sln && sln.length === 1) {
          return sln[0].fsPath;
        } else {
          // If there was no solutions file, look for a csproj file.
          const pattern = new RelativePattern(workspacePath, '**/*.csproj');
          const csproj = await workspace.findFiles(pattern, exclude, 1);
          if (csproj && csproj.length === 1) {
            return csproj[0].fsPath;
          }
        }
      }),
    );

    return projectFiles.filter((file): file is string => Boolean(file));
  }
Example #14
Source File: languageServerClient.ts    From vscode-stripe with MIT License 5 votes vote down vote up
static async getJavaProjectFiles() {
    const openedJavaFiles = [];
    let activeJavaFile: string | undefined;

    if (window.activeTextEditor) {
      activeJavaFile = getJavaFilePathOfTextDocument(window.activeTextEditor.document);
      if (activeJavaFile) {
        openedJavaFiles.push(Uri.file(activeJavaFile).toString());
      }
    }

    if (!workspace.workspaceFolders) {
      return openedJavaFiles;
    }

    await Promise.all(
      workspace.workspaceFolders.map(async (rootFolder) => {
        if (rootFolder.uri.scheme !== 'file') {
          return;
        }

        const rootPath = path.normalize(rootFolder.uri.fsPath);
        if (activeJavaFile && isPrefix(rootPath, activeJavaFile)) {
          return;
        }

        for (const textEditor of window.visibleTextEditors) {
          const javaFileInTextEditor = getJavaFilePathOfTextDocument(textEditor.document);
          if (javaFileInTextEditor && isPrefix(rootPath, javaFileInTextEditor)) {
            openedJavaFiles.push(Uri.file(javaFileInTextEditor).toString());
            return;
          }
        }

        for (const textDocument of workspace.textDocuments) {
          const javaFileInTextDocument = getJavaFilePathOfTextDocument(textDocument);
          if (javaFileInTextDocument && isPrefix(rootPath, javaFileInTextDocument)) {
            openedJavaFiles.push(Uri.file(javaFileInTextDocument).toString());
            return;
          }
        }

        const javaFilesUnderRoot: Uri[] = await workspace.findFiles(
          new RelativePattern(rootFolder, '*.java'),
          undefined,
          1,
        );
        for (const javaFile of javaFilesUnderRoot) {
          if (isPrefix(rootPath, javaFile.fsPath)) {
            openedJavaFiles.push(javaFile.toString());
            return;
          }
        }

        const javaFilesInCommonPlaces: Uri[] = await workspace.findFiles(
          new RelativePattern(rootFolder, '{src, test}/**/*.java'),
          undefined,
          1,
        );
        for (const javaFile of javaFilesInCommonPlaces) {
          if (isPrefix(rootPath, javaFile.fsPath)) {
            openedJavaFiles.push(javaFile.toString());
            return;
          }
        }
      }),
    );

    return openedJavaFiles;
  }
Example #15
Source File: ObjectIds.ts    From al-objid with MIT License 5 votes vote down vote up
export async function getWorkspaceFolderFiles(uri: Uri): Promise<Uri[]> {
    let folderPath: string = uri.fsPath;
    let pattern = new RelativePattern(folderPath, "**/*.al");
    return await executeWithStopwatchAsync(
        () => workspace.findFiles(pattern, null),
        `Retrieving list of files in ${uri}`
    );
}