diff --git a/package-lock.json b/package-lock.json index 2914f839789e9..babcee61cf8dc 100644 --- a/package-lock.json +++ b/package-lock.json @@ -27523,8 +27523,10 @@ "dependencies": { "@theia/core": "1.77.0", "@theia/editor": "1.77.0", + "@theia/filesystem": "1.77.0", "@theia/monaco": "1.77.0", "@theia/monaco-editor-core": "1.108.201", + "@theia/workspace": "1.77.0", "p-queue": "^8.1.1", "tslib": "^2.8.1" }, diff --git a/packages/output/package.json b/packages/output/package.json index 22cbeca89d3cd..e17b17698d9ae 100644 --- a/packages/output/package.json +++ b/packages/output/package.json @@ -6,8 +6,10 @@ "dependencies": { "@theia/core": "1.77.0", "@theia/editor": "1.77.0", + "@theia/filesystem": "1.77.0", "@theia/monaco": "1.77.0", "@theia/monaco-editor-core": "1.108.201", + "@theia/workspace": "1.77.0", "p-queue": "^8.1.1", "tslib": "^2.8.1" }, diff --git a/packages/output/src/browser/output-frontend-module.ts b/packages/output/src/browser/output-frontend-module.ts index 84bac6427dd9a..b80df2d79601a 100644 --- a/packages/output/src/browser/output-frontend-module.ts +++ b/packages/output/src/browser/output-frontend-module.ts @@ -18,7 +18,7 @@ import { ContainerModule } from '@theia/core/shared/inversify'; import { OutputWidget } from './output-widget.js'; import { TabBarToolbarContribution } from '@theia/core/lib/browser/shell/tab-bar-toolbar'; import { ResourceResolver } from '@theia/core/lib/common'; -import { WidgetFactory, bindViewContribution, OpenHandler } from '@theia/core/lib/browser'; +import { WidgetFactory, bindViewContribution, OpenHandler, FrontendApplicationContribution } from '@theia/core/lib/browser'; import { OutputChannelManager } from './output-channel.js'; import { bindOutputPreferences } from '../common/output-preferences.js'; import { OutputToolbarContribution } from './output-toolbar-contribution.js'; @@ -28,6 +28,8 @@ import { OutputContextMenuService } from './output-context-menu.js'; import { OutputEditorFactory } from './output-editor-factory.js'; import { MonacoEditorModelFactory } from '@theia/monaco/lib/browser/monaco-text-model-service'; import { OutputEditorModelFactory } from './output-editor-model-factory.js'; +import { OutputLinkComputer } from './output-link-computer.js'; +import { OutputLinkProvider } from './output-link-provider.js'; export default new ContainerModule(bind => { bind(OutputChannelManager).toSelf().inSingletonScope(); @@ -50,4 +52,8 @@ export default new ContainerModule(bind => { bind(OutputToolbarContribution).toSelf().inSingletonScope(); bind(TabBarToolbarContribution).toService(OutputToolbarContribution); + + bind(OutputLinkComputer).toSelf().inSingletonScope(); + bind(OutputLinkProvider).toSelf().inSingletonScope(); + bind(FrontendApplicationContribution).toService(OutputLinkProvider); }); diff --git a/packages/output/src/browser/output-link-computer.spec.ts b/packages/output/src/browser/output-link-computer.spec.ts new file mode 100644 index 0000000000000..a9c17417fff7a --- /dev/null +++ b/packages/output/src/browser/output-link-computer.spec.ts @@ -0,0 +1,107 @@ +// ***************************************************************************** +// Copyright (C) 2026 EclipseSource and others. +// +// This program and the accompanying materials are made available under the +// terms of the Eclipse Public License v. 2.0 which is available at +// http://www.eclipse.org/legal/epl-2.0. +// +// This Source Code may also be made available under the following Secondary +// Licenses when the conditions for such availability set forth in the Eclipse +// Public License v. 2.0 are satisfied: GNU General Public License, version 2 +// with the GNU Classpath Exception which is available at +// https://www.gnu.org/software/classpath/license.html. +// +// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0 +// ***************************************************************************** + +import { expect } from 'chai'; +import URI from '@theia/core/lib/common/uri'; +import { OutputLinkComputer } from './output-link-computer.js'; + +describe('OutputLinkComputer', () => { + + const computer = new OutputLinkComputer(); + computer.setWorkspaceFolders([{ uri: new URI('file:///workspace/project'), fsPath: '/workspace/project' }]); + + const urls = (line: string, linkComputer = computer): string[] => + linkComputer.computeLinks([line]).map(link => new URI(link.url!.toString()).toString(true)); + + it('should link a path in the workspace', () => { + expect(urls('plain: /workspace/project/README.md')).to.deep.equal(['file:///workspace/project/README.md']); + }); + + it('should link GCC style positions', () => { + expect(urls('/workspace/project/package.json:3:5: error: something')).to.deep.equal(['file:///workspace/project/package.json#L3,5']); + }); + + it('should link MSBuild style positions as one link', () => { + expect(urls('/workspace/project/package.json(10,3): warning')).to.deep.equal(['file:///workspace/project/package.json#L10,3']); + }); + + it('should link "on line" positions', () => { + expect(urls('/workspace/project/README.md on line 20, column 4')).to.deep.equal(['file:///workspace/project/README.md#L20,4']); + }); + + it('should not link paths outside the workspace', () => { + expect(urls('/etc/hosts:1:1')).to.be.empty; + }); + + it('should not link folders that only start with the workspace path', () => { + expect(urls('/workspace/project-other/README.md')).to.be.empty; + }); + + it('should link paths if the workspace folder is a file system root', () => { + const posixRoot = new OutputLinkComputer(); + posixRoot.setWorkspaceFolders([{ uri: new URI('file:///'), fsPath: '/' }]); + expect(urls('/src/a.ts:3:4', posixRoot)).to.deep.equal(['file:///src/a.ts#L3,4']); + + const driveRoot = new OutputLinkComputer(); + driveRoot.setWorkspaceFolders([{ uri: new URI('file:///c:/'), fsPath: 'c:\\' }]); + expect(urls('c:\\src\\a.ts:3', driveRoot)).to.deep.equal(['file:///c:/src/a.ts#L3']); + expect(urls('c:/src/b.ts(3,4)', driveRoot)).to.deep.equal(['file:///c:/src/b.ts#L3,4']); + }); + + it('should not link URLs if the workspace folder is a file system root', () => { + const posixRoot = new OutputLinkComputer(); + posixRoot.setWorkspaceFolders([{ uri: new URI('file:///'), fsPath: '/' }]); + expect(urls('GET https://example.com/api 200', posixRoot)).to.be.empty; + }); + + it('should not link text with slashes if the workspace folder is a file system root', () => { + const posixRoot = new OutputLinkComputer(); + posixRoot.setWorkspaceFolders([{ uri: new URI('file:///'), fsPath: '/' }]); + expect(urls('Content-Type: application/json', posixRoot)).to.be.empty; + expect(urls('progress 50/100 and/or', posixRoot)).to.be.empty; + }); + + it('should not link the workspace path within another path', () => { + expect(urls('/other/workspace/project/README.md')).to.be.empty; + }); + + it('should link paths after delimiters', () => { + expect(urls('file=/workspace/project/a.ts (/workspace/project/b.ts:3)')).to.deep.equal([ + 'file:///workspace/project/a.ts', + 'file:///workspace/project/b.ts#L3' + ]); + }); + + it('should compute the range of the link', () => { + const [link] = computer.computeLinks(['first line', 'see /workspace/project/a.ts']); + expect(link.range).to.deep.equal({ startLineNumber: 2, startColumn: 5, endLineNumber: 2, endColumn: 28 }); + }); + + it('should not link trailing periods', () => { + const [link] = computer.computeLinks(['Compiled /workspace/project/a.ts.']); + expect(new URI(link.url!.toString()).toString(true)).to.equal('file:///workspace/project/a.ts'); + expect(link.range).to.deep.equal({ startLineNumber: 1, startColumn: 10, endLineNumber: 1, endColumn: 33 }); + expect(urls('See /workspace/project/b.ts:3...')).to.deep.equal(['file:///workspace/project/b.ts#L3']); + expect(urls('Up to /workspace/project/..')).to.be.empty; + }); + + it('should link Windows paths with either separator', () => { + const windows = new OutputLinkComputer(); + windows.setWorkspaceFolders([{ uri: new URI('file:///c:/ws'), fsPath: 'c:\\ws' }]); + expect(urls('C:\\ws\\src\\a.ts(3,4)', windows)).to.deep.equal(['file:///c:/ws/src/a.ts#L3,4']); + expect(urls('c:/ws/src/b.ts:7', windows)).to.deep.equal(['file:///c:/ws/src/b.ts#L7']); + }); +}); diff --git a/packages/output/src/browser/output-link-computer.ts b/packages/output/src/browser/output-link-computer.ts new file mode 100644 index 0000000000000..b47f3e1417643 --- /dev/null +++ b/packages/output/src/browser/output-link-computer.ts @@ -0,0 +1,116 @@ +// ***************************************************************************** +// Copyright (C) 2026 EclipseSource and others. +// +// This program and the accompanying materials are made available under the +// terms of the Eclipse Public License v. 2.0 which is available at +// http://www.eclipse.org/legal/epl-2.0. +// +// This Source Code may also be made available under the following Secondary +// Licenses when the conditions for such availability set forth in the Eclipse +// Public License v. 2.0 are satisfied: GNU General Public License, version 2 +// with the GNU Classpath Exception which is available at +// https://www.gnu.org/software/classpath/license.html. +// +// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0 +// ***************************************************************************** + +import type * as monaco from '@theia/monaco-editor-core'; +import { injectable } from '@theia/core/shared/inversify'; +import URI from '@theia/core/lib/common/uri'; +import { escapeRegExpCharacters } from '@theia/core/lib/common/strings'; + +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +// some code copied and modified from https://github.com/microsoft/vscode/blob/1.95.0/src/vs/workbench/contrib/output/common/outputLinkComputer.ts + +export interface OutputLinkWorkspaceFolder { + uri: URI; + /** The OS-specific path of the folder, as it appears in tool output. */ + fsPath: string; +} + +/** + * Detects paths of files in the workspace folders in output channel content. + * Like VS Code, only absolute paths that start with a workspace folder are linked. + */ +@injectable() +export class OutputLinkComputer { + + protected patterns: { folder: URI, regExps: RegExp[] }[] = []; + + setWorkspaceFolders(folders: OutputLinkWorkspaceFolder[]): void { + this.patterns = folders.map(folder => ({ folder: folder.uri, regExps: this.createPatterns(folder.fsPath) })); + } + + protected createPatterns(folderPath: string): RegExp[] { + const folderPaths = [folderPath]; + if (folderPath.includes('\\')) { + // Windows tools print forward slashes as well + folderPaths.push(folderPath.replace(/\\/g, '/')); + } + const pathCharacter = '[^\\s\\(\\):<>\'"]'; + const pathCharacterOrSpace = `(?:${pathCharacter}| ${pathCharacter})`; + // a path that ends with a file extension, it may contain single spaces + const pathWithExtension = `${pathCharacterOrSpace}+\\.${pathCharacter}+`; + const strictPath = `${pathCharacter}+`; + return folderPaths.flatMap(path => { + // the path of a file system root already ends with a separator + const separator = /[\\/]$/.test(path) ? '' : '[\\\\/]'; + // don't start a match within a word or path, e.g. `application/json` if the folder is `/` + const folder = `(?${pathWithExtension}) on line (?\\d+)(?:, column (?\\d+))?`, + // /ws/src/server.js:line 8, column 13 + `${folder}(?${pathWithExtension}):line (?\\d+)(?:, column (?\\d+))?`, + // /ws/src/Features.ts(45,18): error + `${folder}(?${pathWithExtension})\\s?\\((?\\d+)(?:,(?\\d+))?\\)`, + // /ws/src/Game.ts:336:9 + `${folder}(?${strictPath})(?::(?\\d+))?(?::(?\\d+))?` + ].map(pattern => new RegExp(pattern, 'gi')); + }); + } + + computeLinks(lines: string[]): monaco.languages.ILink[] { + const links: monaco.languages.ILink[] = []; + lines.forEach((line, index) => { + const lineNumber = index + 1; + const lineLinks: monaco.languages.ILink[] = []; + for (const { folder, regExps } of this.patterns) { + for (const regExp of regExps) { + regExp.lastIndex = 0; + let match: RegExpExecArray | null; + while (match = regExp.exec(line)) { + // remove trailing periods that likely end a sentence + const path = match.groups!.path!.replace(/\.+$/, ''); + if (!path || /^[\\/]/.test(path)) { + // e.g. the `//host/path` of a URL if the workspace folder is a file system root + continue; + } + const startColumn = match.index + 1; + const endColumn = startColumn + match[0].replace(/\.+$/, '').length; + const overlaps = lineLinks.some(link => link.range.startColumn < endColumn && startColumn < link.range.endColumn); + if (!overlaps) { + lineLinks.push({ + range: { startLineNumber: lineNumber, startColumn, endLineNumber: lineNumber, endColumn }, + url: this.toUri(folder, { ...match.groups, path }).toString() + }); + } + } + } + } + links.push(...lineLinks); + }); + return links; + } + + protected toUri(folder: URI, groups: Record): URI { + const uri = folder.resolve(groups.path!); + if (!groups.line) { + return uri; + } + return uri.withFragment(groups.column ? `L${groups.line},${groups.column}` : `L${groups.line}`); + } +} diff --git a/packages/output/src/browser/output-link-provider.ts b/packages/output/src/browser/output-link-provider.ts new file mode 100644 index 0000000000000..7a56d7a335a75 --- /dev/null +++ b/packages/output/src/browser/output-link-provider.ts @@ -0,0 +1,76 @@ +// ***************************************************************************** +// Copyright (C) 2026 EclipseSource and others. +// +// This program and the accompanying materials are made available under the +// terms of the Eclipse Public License v. 2.0 which is available at +// http://www.eclipse.org/legal/epl-2.0. +// +// This Source Code may also be made available under the following Secondary +// Licenses when the conditions for such availability set forth in the Eclipse +// Public License v. 2.0 are satisfied: GNU General Public License, version 2 +// with the GNU Classpath Exception which is available at +// https://www.gnu.org/software/classpath/license.html. +// +// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0 +// ***************************************************************************** + +import * as monaco from '@theia/monaco-editor-core'; +import { ILogger } from '@theia/core'; +import { inject, injectable, named } from '@theia/core/shared/inversify'; +import { FrontendApplicationContribution } from '@theia/core/lib/browser/frontend-application-contribution'; +import { FileService } from '@theia/filesystem/lib/browser/file-service'; +import { FileStat } from '@theia/filesystem/lib/common/files'; +import { WorkspaceService } from '@theia/workspace/lib/browser/workspace-service'; +import { OutputUri } from '../common/output-uri.js'; +import { OutputLinkComputer } from './output-link-computer.js'; + +/** + * Makes paths of workspace files in output channels clickable. + */ +@injectable() +export class OutputLinkProvider implements FrontendApplicationContribution, monaco.languages.LinkProvider { + + @inject(OutputLinkComputer) + protected readonly linkComputer: OutputLinkComputer; + + @inject(WorkspaceService) + protected readonly workspaceService: WorkspaceService; + + @inject(FileService) + protected readonly fileService: FileService; + + @inject(ILogger) @named('output:OutputLinkProvider') + protected readonly logger: ILogger; + + protected registration: monaco.IDisposable | undefined; + protected updateCount = 0; + + onStart(): void { + this.workspaceService.roots.then(roots => this.updateWorkspaceFolders(roots)); + this.workspaceService.onWorkspaceChanged(roots => this.updateWorkspaceFolders(roots)); + } + + provideLinks(model: monaco.editor.ITextModel): monaco.languages.ILinksList { + return { links: this.linkComputer.computeLinks(model.getLinesContent()) }; + } + + protected async updateWorkspaceFolders(roots: FileStat[]): Promise { + const update = ++this.updateCount; + try { + const folders = await Promise.all(roots.map(async root => ({ + uri: root.resource, + fsPath: await this.fileService.fsPath(root.resource) + }))); + if (update !== this.updateCount) { + // a newer update is in progress + return; + } + this.linkComputer.setWorkspaceFolders(folders); + // registering again makes Monaco recompute the links of open output channels + this.registration?.dispose(); + this.registration = folders.length ? monaco.languages.registerLinkProvider({ scheme: OutputUri.SCHEME }, this) : undefined; + } catch (error) { + this.logger.error('Failed to update the workspace folders of output links', error); + } + } +} diff --git a/packages/output/tsconfig.json b/packages/output/tsconfig.json index d724ea1f75211..5920c2dd0ba35 100644 --- a/packages/output/tsconfig.json +++ b/packages/output/tsconfig.json @@ -15,8 +15,14 @@ { "path": "../editor" }, + { + "path": "../filesystem" + }, { "path": "../monaco" + }, + { + "path": "../workspace" } ] }