From 2200b6eafd2773afbd7172e5fbd601464a5be906 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 3 Jan 2025 10:10:25 +0100 Subject: [PATCH] uri util fixes --- core/util/ideUtils.ts | 18 ++--- core/util/uri.test.ts | 22 ------ core/util/uri.ts | 71 ++++++++----------- .../StepContainerPreToolbar.tsx | 4 +- 4 files changed, 42 insertions(+), 73 deletions(-) diff --git a/core/util/ideUtils.ts b/core/util/ideUtils.ts index 93cb5008d..b969b2286 100644 --- a/core/util/ideUtils.ts +++ b/core/util/ideUtils.ts @@ -1,6 +1,10 @@ import { IDE } from ".."; -import { joinPathsToUri, pathToUriPathSegment } from "./uri"; +import { + joinEncodedUriPathSegmentToUri, + joinPathsToUri, + pathToUriPathSegment, +} from "./uri"; /* This function takes a relative (to workspace) filepath @@ -51,7 +55,7 @@ export async function inferResolvedUriFromRelativePath( for (const suffix of suffixes) { const uris = dirs.map((dir) => ({ dir, - partialUri: joinPathsToUri(dir, suffix), + partialUri: joinEncodedUriPathSegmentToUri(dir, suffix), })); const promises = uris.map(async ({ partialUri, dir }) => { const exists = await ide.fileExists(partialUri); @@ -67,15 +71,13 @@ export async function inferResolvedUriFromRelativePath( // If exactly one directory matches, use it if (existingUris.length === 1) { - return joinPathsToUri(existingUris[0].dir, segments.join("/")); + return joinEncodedUriPathSegmentToUri( + existingUris[0].dir, + segments.join("/"), + ); } } // If no unique match found, use the first directory return joinPathsToUri(dirs[0], path); } - -interface ResolveResult { - resolvedUri: string; - matchedDir: string; -} diff --git a/core/util/uri.test.ts b/core/util/uri.test.ts index 9e2471054..8a915d73f 100644 --- a/core/util/uri.test.ts +++ b/core/util/uri.test.ts @@ -1,9 +1,7 @@ // Generated by continue -import * as URI from "uri-js"; import { pathToUriPathSegment, findUriInDirs, - relativePathOrUriToUri, getUriPathBasename, getUriFileExtension, getFileExtensionFromBasename, @@ -141,26 +139,6 @@ describe("uri utils", () => { }); }); - describe("relativePathOrUriToUri", () => { - const consoleSpy = jest.spyOn(console, "trace").mockImplementation(); - - afterEach(() => { - consoleSpy.mockClear(); - }); - - it("should return original URI if scheme exists", () => { - const uri = "file:///path/to/file.txt"; - expect(relativePathOrUriToUri(uri, "file:///base")).toBe(uri); - }); - - it("should convert relative path to URI", () => { - expect(relativePathOrUriToUri("path/to/file.txt", "file:///base")).toBe( - "file:///base/path/to/file.txt", - ); - expect(consoleSpy).toHaveBeenCalledWith("Received path with no scheme"); - }); - }); - describe("getLastNUriRelativePathParts", () => { it("should get last N parts of URI relative path", () => { const dirUris = ["file:///workspace/project1"]; diff --git a/core/util/uri.ts b/core/util/uri.ts index 708408ce0..a1bcd7745 100644 --- a/core/util/uri.ts +++ b/core/util/uri.ts @@ -5,23 +5,21 @@ import * as URI from "uri-js"; \this\is\afile.ts -> this/is/afile.ts is/already/clean -> is/already/clean **/ - export function pathToUriPathSegment(path: string) { let clean = path.replace(/[\\]/g, "/"); // backslashes -> forward slashes clean = clean.replace(/^\//, ""); // remove start slash clean = clean.replace(/\/$/, ""); // remove end slash return clean .split("/") - .map((segment) => encodeURIComponent(segment)) + .map((part) => encodeURIComponent(part)) .join("/"); } export function getCleanUriPath(uri: string) { - const path = URI.parse(uri).path; - if (!path) { - return ""; - } - return pathToUriPathSegment(path); + const path = URI.parse(uri).path ?? ""; + let clean = path.replace(/^\//, ""); // remove start slash + clean = clean.replace(/\/$/, ""); // remove end slash + return clean; } export function findUriInDirs( @@ -36,6 +34,7 @@ export function findUriInDirs( if (!uriComps.scheme) { throw new Error(`Invalid uri: ${uri}`); } + const uriPathParts = getCleanUriPath(uri).split("/"); for (const dir of dirUriCandidates) { const dirComps = URI.parse(dir); @@ -51,14 +50,7 @@ export function findUriInDirs( // file:///folder/file is not within file:///fold // At this point we break the path up and check if each dir path part matches - const dirPathParts = (dirComps.path ?? "") - .replace(/^\//, "") - .split("/") - .map((part) => encodeURIComponent(part)); - const uriPathParts = (uriComps.path ?? "") - .replace(/^\//, "") - .split("/") - .map((part) => encodeURIComponent(part)); + const dirPathParts = getCleanUriPath(dir).split("/"); if (uriPathParts.length < dirPathParts.length) { continue; @@ -70,7 +62,10 @@ export function findUriInDirs( } } if (allDirPartsMatch) { - const relativePath = uriPathParts.slice(dirPathParts.length).join("/"); + const relativePath = uriPathParts + .slice(dirPathParts.length) + .map(decodeURIComponent) + .join("/"); return { uri, relativePathOrBasename: relativePath, @@ -86,28 +81,13 @@ export function findUriInDirs( }; } -/* - To smooth out the transition from path to URI will use this function to warn when path is used - This will NOT work consistently with full OS paths like c:\blah\blah or ~/Users/etc -*/ -export function relativePathOrUriToUri( - relativePathOrUri: string, - defaultDirUri: string, -): string { - const out = URI.parse(relativePathOrUri); - if (out.scheme) { - return relativePathOrUri; - } - console.trace("Received path with no scheme"); - return joinPathsToUri(defaultDirUri, out.path ?? ""); -} - /* Returns just the file or folder name of a URI */ export function getUriPathBasename(uri: string): string { - const cleanPath = getCleanUriPath(uri); - return cleanPath.split("/")?.pop() || ""; + const path = getCleanUriPath(uri); + const basename = path.split("/").pop() || ""; + return decodeURIComponent(basename); } export function getFileExtensionFromBasename(basename: string) { @@ -142,6 +122,15 @@ export function joinPathsToUri(uri: string, ...pathSegments: string[]) { return URI.serialize(components); } +export function joinEncodedUriPathSegmentToUri( + uri: string, + pathSegment: string, +) { + const components = URI.parse(uri); + components.path = `${components.path}/${pathSegment}`; + return URI.serialize(components); +} + export function getShortestUniqueRelativeUriPaths( uris: string[], dirUriCandidates: string[], @@ -153,8 +142,7 @@ export function getShortestUniqueRelativeUriPaths( const segmentCombinationsMap = new Map(); const segmentsInfo = uris.map((uri) => { const { relativePathOrBasename } = findUriInDirs(uri, dirUriCandidates); - const cleanPath = pathToUriPathSegment(relativePathOrBasename); - const segments = cleanPath.split("/"); + const segments = relativePathOrBasename.split("/"); const suffixes: string[] = []; // Generate all possible suffix combinations, starting from the shortest (basename) @@ -168,18 +156,19 @@ export function getShortestUniqueRelativeUriPaths( ); } - return { uri, segments, suffixes, cleanPath }; + return { uri, segments, suffixes, relativePathOrBasename }; }); // Find shortest unique path for each URI - return segmentsInfo.map(({ uri, suffixes, cleanPath }) => { + return segmentsInfo.map(({ uri, suffixes, relativePathOrBasename }) => { // Since suffixes are now ordered from shortest to longest, // the first unique one we find will be the shortest - const uniqueCleanPath = + const uniquePath = suffixes.find((suffix) => segmentCombinationsMap.get(suffix) === 1) ?? - cleanPath; // fallback to full path if no unique suffix found - return { uri, uniquePath: decodeURIComponent(uniqueCleanPath) }; + relativePathOrBasename; // fallback to full path if no unique suffix found + return { uri, uniquePath }; }); } + // Only used when working with system paths and relative paths // Since doesn't account for URI segements before workspace export function getLastNPathParts(filepath: string, n: number): string { diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index c6a0d58f0..398ce5747 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx @@ -93,12 +93,12 @@ export default function StepContainerPreToolbar( if (!defaultModel) { return; } - + const fileUri = await inferResolvedUriFromRelativePath( props.relativeFilepath, ideMessenger.ide, ); - + ideMessenger.post("applyToFile", { streamId: streamIdRef.current, filepath: fileUri,