Skip to content

Commit

Permalink
centralize vscode.Uri usage
Browse files Browse the repository at this point in the history
  • Loading branch information
pelikhan committed Jun 12, 2024
1 parent ab40afd commit eb42737
Show file tree
Hide file tree
Showing 9 changed files with 37 additions and 57 deletions.
2 changes: 1 addition & 1 deletion packages/vscode/src/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@ import * as vscode from "vscode"
export async function openUrlInTab(url: string) {
await vscode.commands.executeCommand(
"simpleBrowser.show",
vscode.Uri.parse(url)
vscode.Uri.parse(url, true)
)
}
12 changes: 9 additions & 3 deletions packages/vscode/src/edit.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
import * as vscode from "vscode"
import { Fragment, eolPosition } from "genaiscript-core"
import { ExtensionState } from "./state"

export function toPos(p: CharPosition | number) {
if (typeof p === "number") return new vscode.Position(p, 0)
return new vscode.Position(...p)
}
export function toRange(p: CharRange | LineRange) {
if (!p) return undefined
if (Array.isArray(p) && typeof p[0] === "number" && typeof p[1] === "number")
if (
Array.isArray(p) &&
typeof p[0] === "number" &&
typeof p[1] === "number"
)
return new vscode.Range(
new vscode.Position(p[0], 0),
new vscode.Position(p[1], eolPosition)
Expand All @@ -21,6 +26,7 @@ export function fragmentRange(frag: Fragment) {
}

export async function applyEdits(
state: ExtensionState,
edits: Edits[],
options?: {
needsConfirmation?: boolean
Expand All @@ -31,7 +37,7 @@ export async function applyEdits(
const { needsConfirmation } = options || {}
const edit = new vscode.WorkspaceEdit()
for (const e of edits) {
const uri = vscode.Uri.file(e.filename)
const uri = state.host.toUri(e.filename)
const meta: vscode.WorkspaceEditEntryMetadata = {
label: e.label,
needsConfirmation: false,
Expand Down Expand Up @@ -68,7 +74,7 @@ export async function applyEdits(
}
}
if (needsConfirmation)
edit.insert(vscode.Uri.file(edits[0].filename), toPos([0, 0]), "", {
edit.insert(state.host.toUri(edits[0].filename), toPos([0, 0]), "", {
label: "Fake edit",
needsConfirmation: true,
})
Expand Down
8 changes: 4 additions & 4 deletions packages/vscode/src/fragmentcommands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ async function showPromptParametersQuickPicks(
}

export function activateFragmentCommands(state: ExtensionState) {
const { context } = state
const { context, host } = state
const { subscriptions } = context

const pickTemplate = async (options?: {
Expand Down Expand Up @@ -110,7 +110,7 @@ export function activateFragmentCommands(state: ExtensionState) {

let fragment: Fragment
if (typeof frag === "string" && !/\.gpspec\.md(:.*)?$/i.test(frag)) {
const fragUri = vscode.Uri.file(frag)
const fragUri = host.toUri(frag)
if (await checkFileExists(fragUri)) {
const prj = await state.parseDocument(fragUri)
fragment = prj?.rootFiles?.[0].fragments?.[0]
Expand All @@ -119,7 +119,7 @@ export function activateFragmentCommands(state: ExtensionState) {
fragment = prj?.rootFiles?.[0].fragments?.[0]
}
} else if (typeof frag === "string" && GENAI_JS_REGEX.test(frag)) {
const fragUri = vscode.Uri.file(frag)
const fragUri = host.toUri(frag)
const prj = await state.parseDocument(fragUri)
fragment = prj?.rootFiles?.[0].fragments?.[0]
} else {
Expand Down Expand Up @@ -223,7 +223,7 @@ export function activateFragmentCommands(state: ExtensionState) {
fragment = state.project.resolveFragment(fragment)
if (!fragment) return
const { file, startPos } = fragment
const uri = vscode.Uri.file(file.filename)
const uri = host.toUri(file.filename)
const editor = await vscode.window.showTextDocument(uri)
const pos = new vscode.Position(...startPos)
editor.selections = [new vscode.Selection(pos, pos)]
Expand Down
2 changes: 1 addition & 1 deletion packages/vscode/src/lmaccess.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ export async function pickLanguageModel(
else {
await updateConnectionConfiguration(res.provider, res.apiType)
const doc = await vscode.workspace.openTextDocument(
vscode.Uri.joinPath(state.host.projectUri, ".env")
state.host.toUri("./.env")
)
await vscode.window.showTextDocument(doc)
return undefined
Expand Down
6 changes: 3 additions & 3 deletions packages/vscode/src/promptcommands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ import { builtinPromptUri } from "./markdowndocumentprovider"
import { templatesToQuickPickItems } from "./fragmentcommands"

export function activatePromptCommands(state: ExtensionState) {
const { context } = state
const { context, host } = state
const { subscriptions } = context

async function showPrompt(fn: string) {
await state.fixPromptDefinitions()
vscode.window.showTextDocument(vscode.Uri.file(fn))
vscode.window.showTextDocument(host.toUri(fn))
await state.parseWorkspace()
}

Expand Down Expand Up @@ -73,7 +73,7 @@ export function activatePromptCommands(state: ExtensionState) {
"genaiscript.prompt.navigate",
async (prompt: PromptScript) => {
const uri = prompt.filename
? vscode.Uri.file(prompt.filename)
? host.toUri(prompt.filename)
: builtinPromptUri(prompt.id)
await vscode.window.showTextDocument(uri)
}
Expand Down
43 changes: 3 additions & 40 deletions packages/vscode/src/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ export class ExtensionState extends EventTarget {
}

private async saveScripts() {
const dir = vscode.Uri.file(dotGenaiscriptPath("."))
const dir = this.host.toUri(dotGenaiscriptPath("."))
await vscode.workspace.fs.createDirectory(dir)

// add .gitignore
Expand Down Expand Up @@ -214,7 +214,7 @@ temp/
req.editsApplied = null
this.dispatchChange()

const applied = await applyEdits(edits, {
const applied = await applyEdits(this, edits, {
needsConfirmation: true,
})

Expand Down Expand Up @@ -251,43 +251,6 @@ temp/
if (edits?.length) this.applyEdits()
} catch (e) {
if (isCancelError(e)) return
/*
else if (isRequestError(e, 403)) {
const trace = "Open Trace"
const res = await vscode.window.showErrorMessage(
"OpenAI token refused (403).",
trace
)
if (res === trace)
vscode.commands.executeCommand(
"genaiscript.request.open.trace"
)
} else if (isRequestError(e, 400, "context_length_exceeded")) {
const help = "Documentation"
const title = `Context length exceeded.`
const msg = `${title}.
${errorMessage(e)}`
const res = await vscode.window.showWarningMessage(msg, help)
if (res === help)
vscode.env.openExternal(
vscode.Uri.parse(CONTEXT_LENGTH_DOCUMENTATION_URL)
)
} else if (isRequestError(e, 400)) {
const help = "Documentation"
const msg = `OpenAI model error (400).
${errorMessage(e)}`
const res = await vscode.window.showWarningMessage(msg, help)
if (res === help)
vscode.env.openExternal(
vscode.Uri.parse(TOKEN_DOCUMENTATION_URL)
)
} else if (isRequestError(e)) {
const msg = isRequestError(e, 404)
? `LLM model not found (404).`
: errorMessage(e)
await vscode.window.showWarningMessage(msg)
} else
*/
throw e
}
}
Expand Down Expand Up @@ -594,7 +557,7 @@ ${!GENAI_JS_REGEX.test(fn) ? `- [${fn}](./${fn})` : ""}
const murl = /\[([^\]]+)\]\((https:\/\/([^)]+))\)/.exec(message)
if (murl) {
value = murl[1]
target = vscode.Uri.parse(murl[2])
target = vscode.Uri.parse(murl[2], true)
}
const r = new vscode.Diagnostic(
toRange(d.range),
Expand Down
6 changes: 3 additions & 3 deletions packages/vscode/src/statusbar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ export function activateStatusBar(state: ExtensionState) {
)
statusBarItem.command = "genaiscript.request.status"
const updateStatusBar = async () => {
const { parsing } = state
const { computing, progress, options } = state.aiRequest || {}
const { parsing, host, aiRequest } = state
const { computing, progress, options } = aiRequest || {}
const { template, fragment } = options || {}
const { tokensSoFar } = progress || {}
statusBarItem.text = toStringList(
Expand All @@ -28,7 +28,7 @@ export function activateStatusBar(state: ExtensionState) {
const md = new vscode.MarkdownString(
toMarkdownString(
fragment
? Utils.basename(vscode.Uri.file(fragment.file.filename))
? Utils.basename(host.toUri(fragment.file.filename))
: undefined,
template
? `- tool: ${template.title} (${template.id})`
Expand Down
4 changes: 2 additions & 2 deletions packages/vscode/src/testcontroller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { PROMPTFOO_VERSION } from "../../cli/src/version"
import { openUrlInTab } from "./browser"

export async function activateTestController(state: ExtensionState) {
const { context } = state
const { context, host } = state
const { subscriptions } = context

const ctrl = vscode.tests.createTestController(TOOL_ID, "GenAIScript")
Expand Down Expand Up @@ -135,7 +135,7 @@ export async function activateTestController(state: ExtensionState) {
const file = ctrl.createTestItem(
script.id,
script.id,
vscode.Uri.file(script.filename)
host.toUri(script.filename)
)
file.description = script.title ?? script.description
ctrl.items.add(file)
Expand Down
11 changes: 11 additions & 0 deletions packages/vscode/src/vshost.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
LanguageModel,
MODEL_PROVIDER_AZURE,
AbortSignalOptions,
HTTPS_REGEX,
} from "genaiscript-core"
import { Uri } from "vscode"
import { ExtensionState } from "./state"
Expand Down Expand Up @@ -138,6 +139,16 @@ export class VSCodeHost extends EventTarget implements Host {
return r.fsPath
}

toUri(filenameOrUrl: string): vscode.Uri {
const folder = this.projectUri
if (!filenameOrUrl) return folder
if (/^[a-z][a-z0-9+\-.]*:\/\//.test(filenameOrUrl))
return vscode.Uri.parse(filenameOrUrl, true)
if (this.path.isAbsolute(filenameOrUrl))
return vscode.Uri.file(filenameOrUrl)
else return Utils.resolvePath(folder, filenameOrUrl)
}

log(level: LogLevel, msg: string): void {
const output = this.state.output
switch (level) {
Expand Down

0 comments on commit eb42737

Please sign in to comment.