-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Upstream model generated file and line linkification #1803
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
vijayupadya
wants to merge
8
commits into
main
Choose a base branch
from
vijayu/autoGen-links-3
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+1,541
−42
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
a3c7e9e
Upstream model generated file/line Linkification
cd34558
CP feedback updated
a25735f
simplify prompt
490a486
Optimization and consolidation
25ca856
Merge branch 'main' of https://github.com/microsoft/vscode-copilot-ch…
e7f3c3e
GCP feedback updates
94547bc
Update prompt snapshot.
9059f78
few prompt tweaks
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,239 @@ | ||
| /*--------------------------------------------------------------------------------------------- | ||
| * Copyright (c) Microsoft Corporation. All rights reserved. | ||
| * Licensed under the MIT License. See License.txt in the project root for license information. | ||
| *--------------------------------------------------------------------------------------------*/ | ||
|
|
||
| import { IFileSystemService } from '../../../platform/filesystem/common/fileSystemService'; | ||
| import { FileType } from '../../../platform/filesystem/common/fileTypes'; | ||
| import { getWorkspaceFileDisplayPath, IWorkspaceService } from '../../../platform/workspace/common/workspaceService'; | ||
| import { CancellationToken } from '../../../util/vs/base/common/cancellation'; | ||
| import { Location, Position, Range, Uri } from '../../../vscodeTypes'; | ||
| import { coalesceParts, LinkifiedPart, LinkifiedText, LinkifyLocationAnchor } from './linkifiedText'; | ||
| import { IContributedLinkifier, LinkifierContext } from './linkifyService'; | ||
|
|
||
| // Matches markdown links where the text is a path and optional #L anchor is present | ||
| // Example: [src/file.ts](src/file.ts#L10-12) or [src/file.ts](src/file.ts) | ||
| const modelLinkRe = /\[(?<text>[^\]\n]+)\]\((?<target>[^\s)]+)\)/gu; | ||
|
|
||
| export class ModelFilePathLinkifier implements IContributedLinkifier { | ||
| constructor( | ||
| @IFileSystemService private readonly fileSystem: IFileSystemService, | ||
| @IWorkspaceService private readonly workspaceService: IWorkspaceService, | ||
| ) { } | ||
|
|
||
| async linkify(text: string, context: LinkifierContext, token: CancellationToken): Promise<LinkifiedText | undefined> { | ||
| let lastIndex = 0; | ||
| const parts: Array<LinkifiedPart | Promise<LinkifiedPart>> = []; | ||
|
|
||
| for (const match of text.matchAll(modelLinkRe)) { | ||
| const original = match[0]; | ||
| const prefix = text.slice(lastIndex, match.index); | ||
| if (prefix) { | ||
| parts.push(prefix); | ||
| } | ||
| lastIndex = match.index + original.length; | ||
|
|
||
| const parsed = this.parseModelLinkMatch(match); | ||
| if (!parsed) { | ||
| parts.push(original); | ||
| continue; | ||
| } | ||
|
|
||
| const workspaceFolders = this.workspaceService.getWorkspaceFolders(); | ||
| if (!this.canLinkify(parsed, workspaceFolders)) { | ||
| parts.push(original); | ||
| continue; | ||
| } | ||
|
|
||
| const resolved = await this.resolveTarget(parsed.targetPath, workspaceFolders, parsed.preserveDirectorySlash); | ||
| if (!resolved) { | ||
| parts.push(original); | ||
| continue; | ||
| } | ||
|
|
||
| const basePath = getWorkspaceFileDisplayPath(this.workspaceService, resolved); | ||
| const anchorRange = this.parseAnchor(parsed.anchor); | ||
| if (parsed.anchor && !anchorRange) { | ||
| parts.push(original); | ||
vijayupadya marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| continue; | ||
| } | ||
|
|
||
| if (anchorRange) { | ||
| const { range, startLine, endLine } = anchorRange; | ||
| const displayPath = endLine && startLine !== endLine | ||
| ? `${basePath}#L${startLine}-${endLine}` | ||
| : `${basePath}#L${startLine}`; | ||
| parts.push(new LinkifyLocationAnchor(new Location(resolved, range), displayPath)); | ||
| continue; | ||
| } | ||
|
|
||
| parts.push(new LinkifyLocationAnchor(resolved, basePath)); | ||
| } | ||
|
|
||
| const suffix = text.slice(lastIndex); | ||
| if (suffix) { | ||
| parts.push(suffix); | ||
| } | ||
|
|
||
| if (!parts.length) { | ||
| return undefined; | ||
| } | ||
|
|
||
| return { parts: coalesceParts(await Promise.all(parts)) }; | ||
| } | ||
|
|
||
| private parseModelLinkMatch(match: RegExpMatchArray): { readonly text: string; readonly targetPath: string; readonly anchor: string | undefined; readonly preserveDirectorySlash: boolean } | undefined { | ||
| const rawText = match.groups?.['text']; | ||
| const rawTarget = match.groups?.['target']; | ||
| if (!rawText || !rawTarget) { | ||
| return undefined; | ||
| } | ||
|
|
||
| const hashIndex = rawTarget.indexOf('#'); | ||
| const baseTarget = hashIndex === -1 ? rawTarget : rawTarget.slice(0, hashIndex); | ||
| const anchor = hashIndex === -1 ? undefined : rawTarget.slice(hashIndex + 1); | ||
|
|
||
| let decodedBase = baseTarget; | ||
| try { | ||
| decodedBase = decodeURIComponent(baseTarget); | ||
| } catch { | ||
| // noop | ||
| } | ||
|
|
||
| const preserveDirectorySlash = decodedBase.endsWith('/') && decodedBase.length > 1; | ||
| const normalizedTarget = this.normalizeSlashes(decodedBase); | ||
| const normalizedText = this.normalizeLinkText(rawText); | ||
| return { text: normalizedText, targetPath: normalizedTarget, anchor, preserveDirectorySlash }; | ||
| } | ||
|
|
||
| private normalizeSlashes(value: string): string { | ||
| // Collapse one or more backslashes into a single forward slash so mixed separators normalize consistently. | ||
| return value.replace(/\\+/g, '/'); | ||
| } | ||
|
|
||
| private normalizeLinkText(rawText: string): string { | ||
| let text = this.normalizeSlashes(rawText); | ||
| // Remove a leading or trailing backtick that sometimes wraps the visible link label. | ||
| text = text.replace(/^`|`$/g, ''); | ||
|
|
||
| // Look for a trailing #L anchor segment so it can be stripped before we compare names. | ||
| const anchorMatch = /^(.+?)(#L\d+(?:-\d+)?)$/.exec(text); | ||
| return anchorMatch ? anchorMatch[1] : text; | ||
| } | ||
|
|
||
| private canLinkify(parsed: { readonly text: string; readonly targetPath: string; readonly anchor: string | undefined }, workspaceFolders: readonly Uri[]): boolean { | ||
| const { text, targetPath, anchor } = parsed; | ||
| const textMatchesBase = targetPath === text; | ||
| const textIsFilename = !text.includes('/') && targetPath.endsWith(`/${text}`); | ||
| const descriptiveAbsolute = this.isAbsolutePath(targetPath) && !!anchor; | ||
|
|
||
| return Boolean(workspaceFolders.length) && (textMatchesBase || textIsFilename || descriptiveAbsolute); | ||
| } | ||
|
|
||
| private async resolveTarget(targetPath: string, workspaceFolders: readonly Uri[], preserveDirectorySlash: boolean): Promise<Uri | undefined> { | ||
| if (!workspaceFolders.length) { | ||
| return undefined; | ||
| } | ||
|
|
||
| const folderUris = workspaceFolders.map(folder => this.toVsUri(folder)); | ||
|
|
||
| if (this.isAbsolutePath(targetPath)) { | ||
| const absoluteUri = this.tryCreateFileUri(targetPath); | ||
| if (!absoluteUri) { | ||
| return undefined; | ||
| } | ||
|
|
||
| for (const folderUri of folderUris) { | ||
| if (this.isEqualOrParentFs(absoluteUri, folderUri)) { | ||
| return this.tryStat(absoluteUri, preserveDirectorySlash); | ||
| } | ||
| } | ||
| return undefined; | ||
| } | ||
|
|
||
| const segments = targetPath.split('/').filter(Boolean); | ||
| for (const folderUri of folderUris) { | ||
| const candidate = Uri.joinPath(folderUri, ...segments); | ||
| const stat = await this.tryStat(candidate, preserveDirectorySlash); | ||
| if (stat) { | ||
| return stat; | ||
| } | ||
| } | ||
|
|
||
| return undefined; | ||
| } | ||
|
|
||
| private tryCreateFileUri(path: string): Uri | undefined { | ||
| try { | ||
| return Uri.file(path); | ||
| } catch { | ||
| return undefined; | ||
| } | ||
| } | ||
|
|
||
| private toVsUri(folder: Uri): Uri { | ||
| return Uri.parse(folder.toString()); | ||
| } | ||
|
|
||
| private isEqualOrParentFs(target: Uri, folder: Uri): boolean { | ||
| const targetFs = this.normalizeFsPath(target); | ||
| const folderFs = this.normalizeFsPath(folder); | ||
| return targetFs === folderFs || targetFs.startsWith(folderFs.endsWith('/') ? folderFs : `${folderFs}/`); | ||
| } | ||
|
|
||
| private normalizeFsPath(resource: Uri): string { | ||
| // Convert Windows backslashes to forward slashes and remove duplicate separators for stable comparisons. | ||
| return resource.fsPath.replace(/\\/g, '/').replace(/\/+/g, '/').toLowerCase(); | ||
| } | ||
|
|
||
| private parseAnchor(anchor: string | undefined): { readonly range: Range; readonly startLine: string; readonly endLine: string | undefined } | undefined { | ||
| // Ensure the anchor follows the #L123 or #L123-456 format before parsing it. | ||
| if (!anchor || !/^L\d+(?:-\d+)?$/.test(anchor)) { | ||
| return undefined; | ||
| } | ||
|
|
||
| // Capture the start (and optional end) line numbers from the anchor. | ||
| const match = /^L(\d+)(?:-(\d+))?$/.exec(anchor); | ||
| if (!match) { | ||
| return undefined; | ||
| } | ||
|
|
||
| const startLine = match[1]; | ||
| const endLineRaw = match[2]; | ||
| const normalizedEndLine = endLineRaw === startLine ? undefined : endLineRaw; | ||
| const start = parseInt(startLine, 10) - 1; | ||
| const end = parseInt(normalizedEndLine ?? startLine, 10) - 1; | ||
| if (Number.isNaN(start) || Number.isNaN(end) || start < 0 || end < start) { | ||
| return undefined; | ||
| } | ||
|
|
||
| return { | ||
| range: new Range(new Position(start, 0), new Position(end, 0)), | ||
| startLine, | ||
| endLine: normalizedEndLine, | ||
| }; | ||
| } | ||
|
|
||
| private isAbsolutePath(path: string): boolean { | ||
| // Treat drive-letter prefixes (e.g. C:) or leading slashes as absolute paths. | ||
| return /^[a-z]:/i.test(path) || path.startsWith('/'); | ||
| } | ||
|
|
||
| private async tryStat(uri: Uri, preserveDirectorySlash: boolean): Promise<Uri | undefined> { | ||
| try { | ||
| const stat = await this.fileSystem.stat(uri); | ||
| if (stat.type === FileType.Directory) { | ||
| if (preserveDirectorySlash) { | ||
| return uri.path.endsWith('/') ? uri : uri.with({ path: `${uri.path}/` }); | ||
| } | ||
| if (uri.path.endsWith('/') && uri.path !== '/') { | ||
| return uri.with({ path: uri.path.slice(0, -1) }); | ||
| } | ||
| return uri; | ||
| } | ||
| return uri; | ||
| } catch { | ||
| return undefined; | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Let's break up the existing
FilePathLinkifierinto the real links functionality and the inline code functionality. Maybe just delete the real links stuff fromFilePathLinkifierand keep this class. I'd like to avoid the duplication though and make it so we just have one place that handles the markdown file linksThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
updated