-
-
Notifications
You must be signed in to change notification settings - Fork 5
feat: add openFileInNpmx command for node_modules files
#34
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
Merged
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
f70a04c
test: setup `jest-mock-vscode`
dgp1130 ceeac58
test: add filesystem mocking utility
dgp1130 c85c8a5
refactor: resolve files within their local package
dgp1130 70e20e7
feat: add `openFileInNpmx` command
dgp1130 a0e56a4
[autofix.ci] apply automated fixes
autofix-ci[bot] 24d8d9d
fix: improve `node_modules` check
9romise 2712a78
refactor: move command into `commands`
9romise a2fbb8d
refactor: prefer return an object instead of tuple
9romise a3911cb
fix(explorer): hide context command on folders
9romise 0155bb6
test: fix
9romise a8db241
apply suggestions from coderabbit
9romise 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
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
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,44 @@ | ||
| import { logger } from '#state' | ||
| import { npmxFileUrl } from '#utils/links' | ||
| import { resolvePackageRelativePath } from '#utils/resolve' | ||
| import { useActiveTextEditor } from 'reactive-vscode' | ||
| import { env, Uri, window } from 'vscode' | ||
|
|
||
| export async function openFileInNpmx(fileUri?: Uri) { | ||
| const textEditor = useActiveTextEditor() | ||
|
|
||
| // If triggered from context menu, fileUri is provided. | ||
| // If triggered from command palette, use active text editor. | ||
| const uri = fileUri ?? textEditor.value?.document.uri | ||
| if (!uri) { | ||
| window.showErrorMessage('npmx: No active file selected.') | ||
| return | ||
| } | ||
|
|
||
| // Assert the given file is in `node_modules/`, though the command should | ||
| // already be limited to such files. | ||
| if (!uri.path.includes('/node_modules/')) { | ||
| window.showErrorMessage('npmx: Selected file is not within a node_modules folder.') | ||
| return | ||
| } | ||
|
|
||
| // Find the associated package manifest and the relative path to the given file. | ||
| const result = await resolvePackageRelativePath(uri) | ||
| if (!result) { | ||
| logger.warn(`Could not resolve npmx url: ${uri.toString()}`) | ||
| window.showWarningMessage(`npmx: Could not find package.json for ${uri.toString()}`) | ||
| return | ||
| } | ||
| const { manifest, relativePath } = result | ||
|
|
||
| // Use line number only if the user is actively looking at the relevant file | ||
| const openingActiveFile = !fileUri || fileUri.toString() === textEditor.value?.document.uri.toString() | ||
|
|
||
| // VSCode uses 0-indexed lines, npmx uses 1-indexed lines | ||
| const vsCodeLine = openingActiveFile ? textEditor.value?.selection.active.line : undefined | ||
| const npmxLine = vsCodeLine !== undefined ? vsCodeLine + 1 : undefined | ||
|
|
||
| // Construct the npmx.dev URL and open it. | ||
| const url = npmxFileUrl(manifest.name, manifest.version, relativePath, npmxLine) | ||
| await env.openExternal(Uri.parse(url)) | ||
| } | ||
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,87 @@ | ||
| import { Uri, workspace } from 'vscode' | ||
|
|
||
| /** | ||
| * Resolves the relative path of a file within its package. | ||
| * | ||
| * @param uri The URI of the file to resolve. | ||
| * @returns A promise that resolves to the package manifest and relative path, | ||
| * or `undefined` if not found. | ||
| */ | ||
| export async function resolvePackageRelativePath(uri: Uri): Promise<{ manifest: PackageManifest, relativePath: string } | undefined> { | ||
| const result = await findPackageJson(uri) | ||
| if (!result) | ||
| return undefined | ||
|
|
||
| const { uri: pkgUri, manifest } = result | ||
| const relativePath = uri.path.slice(pkgUri.path.lastIndexOf('/') + 1) | ||
|
|
||
| return { manifest, relativePath } | ||
| } | ||
|
|
||
| /** A parsed `package.json` manifest file. */ | ||
| interface PackageManifest { | ||
| /** Package name. */ | ||
| name: string | ||
|
|
||
| /** Package version specifier. */ | ||
| version: string | ||
| } | ||
|
|
||
| /** | ||
| * Finds the nearest package.json file by searching upwards from the given URI. | ||
| * | ||
| * @param file The URI to start the search from. | ||
| * @returns The URI and parsed content of the package.json, or `undefined` if | ||
| * not found. | ||
| */ | ||
| async function findPackageJson(file: Uri): Promise<{ uri: Uri, manifest: PackageManifest } | undefined> { | ||
| // Start from the directory, so we don't look for | ||
| // `node_modules/foo/bar.js/package.json` | ||
| const startDir = Uri.joinPath(file, '..') | ||
|
|
||
| for (const dir of walkAncestors(startDir)) { | ||
| const pkgUri = Uri.joinPath(dir, 'package.json') | ||
|
|
||
| let pkg: Partial<PackageManifest> | undefined | ||
| try { | ||
| const content = await workspace.fs.readFile(pkgUri) | ||
| pkg = JSON.parse(new TextDecoder().decode(content)) as Partial<PackageManifest> | ||
| } catch { | ||
| continue | ||
| } | ||
|
|
||
| if (isValidManifest(pkg)) { | ||
| return { | ||
| uri: pkgUri, | ||
| manifest: pkg, | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return undefined | ||
| } | ||
|
|
||
| function* walkAncestors(start: Uri): Generator<Uri, void, void> { | ||
| let currentUri = start | ||
| while (true) { | ||
| yield currentUri | ||
|
|
||
| if (currentUri.path.endsWith('/node_modules')) | ||
| return | ||
|
|
||
| const parentUri = Uri.joinPath(currentUri, '..') | ||
| if (parentUri.toString() === currentUri.toString()) | ||
| return | ||
|
|
||
| currentUri = parentUri | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Check for valid package manifest, as it might be a manifest which just | ||
| * configures a setting without really being a package (such as | ||
| * `{sideEffects: false}`). | ||
| */ | ||
| function isValidManifest(json: Partial<PackageManifest>): json is PackageManifest { | ||
| return Boolean(json && json.name && json.version) | ||
| } |
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,27 @@ | ||
| import { expect, vi } from 'vitest' | ||
| import { workspace } from 'vscode' | ||
|
|
||
| /** | ||
| * Mocks the VS Code filesystem by intercepting {@link workspace.fs}. | ||
| * | ||
| * @param files A record mapping file paths to their string content. | ||
| */ | ||
| export function mockFileSystem(files: Record<string, string>) { | ||
| // Make all functions throw by default. | ||
| for (const [name, fn] of Object.entries(workspace.fs)) { | ||
| if (typeof fn === 'function') { | ||
| vi.mocked(fn).mockImplementation(() => { | ||
| expect.fail(`\`workspace.fs.${name}\` is not supported as a fake.`) | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| vi.mocked(workspace.fs.readFile).mockImplementation(async (uri) => { | ||
| const path = uri.path | ||
| const content = files[path] | ||
| if (content === undefined) { | ||
| throw new Error(`File not found: ${uri.toString()}`) | ||
| } | ||
| return new TextEncoder().encode(content) | ||
| }) | ||
| } |
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,17 @@ | ||
| import { createVSCodeMock } from 'jest-mock-vscode' | ||
| import { vi } from 'vitest' | ||
|
|
||
| const vscode = createVSCodeMock(vi) | ||
|
|
||
| export const Uri = vscode.Uri | ||
| export const workspace = vscode.workspace | ||
| export const Range = vscode.Range | ||
| export const Position = vscode.Position | ||
| export const Location = vscode.Location | ||
| export const Selection = vscode.Selection | ||
| export const ThemeColor = vscode.ThemeColor | ||
| export const ThemeIcon = vscode.ThemeIcon | ||
| export const TreeItem = vscode.TreeItem | ||
| export const TreeItemCollapsibleState = vscode.TreeItemCollapsibleState | ||
| export const Disposable = vscode.Disposable | ||
| export default vscode |
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,42 @@ | ||
| import { beforeEach, describe, expect, it, vi } from 'vitest' | ||
| import { Uri, workspace } from 'vscode' | ||
| import { mockFileSystem } from './__mocks__/filesystem' | ||
|
|
||
| describe('mockFileSystem', () => { | ||
| beforeEach(() => { | ||
| vi.resetAllMocks() | ||
| }) | ||
|
|
||
| describe('`readFile`', () => { | ||
| it('should mock matched paths', async () => { | ||
| mockFileSystem({ | ||
| '/test/file.txt': 'hello world', | ||
| }) | ||
|
|
||
| const uri = Uri.file('/test/file.txt') | ||
| const content = await workspace.fs.readFile(uri) | ||
|
|
||
| expect(new TextDecoder().decode(content)).toBe('hello world') | ||
| }) | ||
|
|
||
| it('should throw error for unmatched paths', async () => { | ||
| mockFileSystem({}) | ||
|
|
||
| const uri = Uri.file('/does-not-exist.txt') | ||
| await expect(workspace.fs.readFile(uri)).rejects.toThrow('File not found') | ||
| }) | ||
|
|
||
| it('should handle multiple files', async () => { | ||
| mockFileSystem({ | ||
| '/a.js': 'content a', | ||
| '/b.js': 'content b', | ||
| }) | ||
|
|
||
| const contentA = await workspace.fs.readFile(Uri.file('/a.js')) | ||
| const contentB = await workspace.fs.readFile(Uri.file('/b.js')) | ||
|
|
||
| expect(new TextDecoder().decode(contentA)).toBe('content a') | ||
| expect(new TextDecoder().decode(contentB)).toBe('content b') | ||
| }) | ||
| }) | ||
| }) |
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.
Uh oh!
There was an error while loading. Please reload this page.