| // Copyright 2026 The Fuchsia Authors. All rights reserved. |
| // Use of this source code is governed by a BSD-style license that can be |
| // found in the LICENSE file. |
| |
| // The module 'vscode' contains the VS Code extensibility API |
| // Import the module and reference it with the alias vscode in your code below |
| import * as vscode from 'vscode'; |
| |
| const OSSCS_BASE = 'https://cs.opensource.google/fuchsia/fuchsia/+/main:'; |
| |
| // The object received when the extension is called from context-menu / right click |
| type ContextMenuCommandArg = { |
| path: string, |
| }; |
| |
| /** |
| * Initialize the openInCodeSearch command. |
| */ |
| export function setUpGitHelper(ctx: vscode.ExtensionContext) { |
| ctx.subscriptions.push(vscode.commands.registerCommand('fuchsia.openInCodeSearch', async (arg) => { |
| await openAtMain(arg); |
| })); |
| } |
| |
| /** |
| * Returns the root Fuchsia directory. |
| */ |
| function getRoot(): vscode.Uri | undefined { |
| if (vscode.workspace.workspaceFolders !== undefined) { |
| // Try to find a top-level directory named "fuchsia" |
| for (let dir of vscode.workspace.workspaceFolders) { |
| if (dir.name === 'fuchsia') { |
| return dir.uri; |
| } |
| } |
| } |
| |
| return undefined; |
| } |
| |
| /** |
| * Returns the path segment within the Fuchsia tree for the given context menu argument. |
| */ |
| function getPathSegment(arg: ContextMenuCommandArg) { |
| let root = getRoot()?.fsPath; |
| |
| let fullPath = |
| arg?.path || // Try to use the passed in path, if available |
| vscode.window.activeTextEditor?.document.fileName || // Fallback to the active editor's path |
| root || // Fallback to the root of the workspace |
| ''; |
| |
| return fullPath.slice(root?.length); |
| } |
| |
| /** |
| * Returns the current line number, if applicable. |
| */ |
| function getLineSegment(): string | null { |
| const activeEditor = vscode.window.activeTextEditor; |
| if (activeEditor) { |
| let line = (activeEditor.selection.active.line + 1); |
| return line.toString(); |
| } |
| return null; |
| } |
| |
| /** |
| * Returns the URL for the given path and line number. |
| */ |
| function makeUrl(path: string, line: string | null): vscode.Uri { |
| let url = OSSCS_BASE + path; |
| if (line !== null) { |
| url += ';l=' + line; |
| } |
| |
| return vscode.Uri.parse(url); |
| } |
| |
| /** |
| * Opens the current file, at the current line, on branch main in osscs. |
| */ |
| async function openAtMain(arg: ContextMenuCommandArg) { |
| let cutPath = getPathSegment(arg); |
| let line = getLineSegment(); |
| await vscode.commands.executeCommand('vscode.open', makeUrl(cutPath, line)); |
| } |