Skip to content
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

Node Explorer: Create a Uri util for parseTsUri #141

Merged
merged 1 commit into from
Jul 31, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,7 @@
"utf-8-validate": "^6.0.3",
"vitest": "^.33.0",
"vscode-jsonrpc": "^8.1.0",
"vscode-uri": "^3.0.7",
"webpack": "^5.88.2",
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^4.15.1",
Expand Down
46 changes: 30 additions & 16 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,12 @@ import { ADMIN_CONSOLE } from './utils/url';
import { Tailscale } from './tailscale';
import { Logger } from './logger';
import { errorForType } from './tailscale/error';
import { NodeExplorerProvider, PeerTree } from './node-explorer-provider';
import { FileExplorer, NodeExplorerProvider, PeerTree } from './node-explorer-provider';

import { TSFileSystemProvider } from './ts-file-system-provider';
import { ConfigManager } from './config-manager';
import { SSH } from './utils/ssh';
import { parseTsUri } from './utils/uri';

let tailscaleInstance: Tailscale;

Expand Down Expand Up @@ -115,24 +116,37 @@ export async function activate(context: vscode.ExtensionContext) {
);

context.subscriptions.push(
vscode.commands.registerCommand('tailscale.node.setRootDir', async (node: PeerTree) => {
const dir = await vscode.window.showInputBox({
prompt: `Enter the root directory to use for ${node.HostName}`,
value: configManager.config?.hosts?.[node.HostName]?.rootDir || '~',
});
vscode.commands.registerCommand(
'tailscale.node.setRootDir',
async (node: PeerTree | FileExplorer) => {
let hostname: string;

if (node instanceof FileExplorer) {
hostname = parseTsUri(node.uri).hostname;
} else if (node instanceof PeerTree) {
hostname = node.HostName;
} else {
throw new Error(`invalid node type: ${typeof node}`);
}

const dir = await vscode.window.showInputBox({
prompt: `Enter the root directory to use for ${hostname}`,
value: configManager.config?.hosts?.[hostname]?.rootDir || '~',
});

if (!dir) {
return;
}
if (!dir) {
return;
}

if (!path.isAbsolute(dir) && dir !== '~') {
vscode.window.showErrorMessage(`${dir} is an invalid absolute path`);
return;
}
if (!path.isAbsolute(dir) && dir !== '~') {
vscode.window.showErrorMessage(`${dir} is an invalid absolute path`);
return;
}

configManager.setForHost(node.HostName, 'rootDir', dir);
nodeExplorerProvider.refreshAll();
})
configManager.setForHost(hostname, 'rootDir', dir);
nodeExplorerProvider.refreshAll();
}
)
);

vscode.window.registerWebviewViewProvider('tailscale-serve-view', servePanelProvider);
Expand Down
3 changes: 2 additions & 1 deletion src/node-explorer-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { TSFileSystemProvider } from './ts-file-system-provider';
import { SSH } from './utils/ssh';
import { ConfigManager } from './config-manager';
import { Logger } from './logger';
import { parseTsUri } from './utils/uri';

export class NodeExplorerProvider
implements
Expand Down Expand Up @@ -173,7 +174,7 @@ export class NodeExplorerProvider
vscode.commands.registerCommand(
'tailscale.node.openRemoteCodeAtLocation',
async (file: FileExplorer) => {
const { hostname, resourcePath } = this.fsProvider.extractHostAndPath(file.uri);
const { hostname, resourcePath } = parseTsUri(file.uri);
if (!hostname || !resourcePath) {
return;
}
Expand Down
49 changes: 12 additions & 37 deletions src/ts-file-system-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { exec } from 'child_process';
import { Logger } from './logger';
import { SSH } from './utils/ssh';
import { ConfigManager } from './config-manager';
import { escapeSpace } from './utils/string';
import { parseTsUri } from './utils/uri';

export class TSFileSystemProvider implements vscode.FileSystemProvider {
private ssh: SSH;
Expand All @@ -22,7 +24,7 @@ export class TSFileSystemProvider implements vscode.FileSystemProvider {

async stat(uri: vscode.Uri): Promise<vscode.FileStat> {
Logger.info(`stat: ${uri.toString()}`, 'tsFs');
const { hostname, resourcePath } = this.extractHostAndPath(uri);
const { hostname, resourcePath } = parseTsUri(uri);

if (!hostname) {
throw new Error('hostname is undefined');
Expand All @@ -47,7 +49,7 @@ export class TSFileSystemProvider implements vscode.FileSystemProvider {
async readDirectory(uri: vscode.Uri): Promise<[string, vscode.FileType][]> {
Logger.info(`readDirectory: ${uri.toString()}`, 'tsFs');

const { hostname, resourcePath } = this.extractHostAndPath(uri);
const { hostname, resourcePath } = parseTsUri(uri);
Logger.info(`hostname: ${hostname}`, 'tsFs');
Logger.info(`remotePath: ${resourcePath}`, 'tsFs');

Expand Down Expand Up @@ -84,7 +86,7 @@ export class TSFileSystemProvider implements vscode.FileSystemProvider {

async readFile(uri: vscode.Uri): Promise<Uint8Array> {
Logger.info(`readFile: ${uri.toString()}`, 'tsFs-readFile');
const { hostname, resourcePath } = this.extractHostAndPath(uri);
const { hostname, resourcePath } = parseTsUri(uri);

if (!hostname) {
throw new Error('hostname is undefined');
Expand All @@ -102,7 +104,7 @@ export class TSFileSystemProvider implements vscode.FileSystemProvider {
): Promise<void> {
Logger.info(`writeFile: ${uri.toString()}`, 'tsFs');

const { hostname, resourcePath } = this.extractHostAndPath(uri);
const { hostname, resourcePath } = parseTsUri(uri);

if (!options.create && !options.overwrite) {
throw vscode.FileSystemError.FileExists(uri);
Expand All @@ -120,7 +122,7 @@ export class TSFileSystemProvider implements vscode.FileSystemProvider {
async delete(uri: vscode.Uri, options: { recursive: boolean }): Promise<void> {
Logger.info(`delete: ${uri.toString()}`, 'tsFs');

const { hostname, resourcePath } = this.extractHostAndPath(uri);
const { hostname, resourcePath } = parseTsUri(uri);

if (!hostname) {
throw new Error('hostname is undefined');
Expand All @@ -135,7 +137,7 @@ export class TSFileSystemProvider implements vscode.FileSystemProvider {
async createDirectory(uri: vscode.Uri): Promise<void> {
Logger.info(`createDirectory: ${uri.toString()}`, 'tsFs');

const { hostname, resourcePath } = this.extractHostAndPath(uri);
const { hostname, resourcePath } = parseTsUri(uri);

if (!hostname) {
throw new Error('hostname is undefined');
Expand All @@ -151,8 +153,8 @@ export class TSFileSystemProvider implements vscode.FileSystemProvider {
): Promise<void> {
Logger.info('rename', 'tsFs');

const { hostname: oldHost, resourcePath: oldPath } = this.extractHostAndPath(oldUri);
const { hostname: newHost, resourcePath: newPath } = this.extractHostAndPath(newUri);
const { hostname: oldHost, resourcePath: oldPath } = parseTsUri(oldUri);
const { hostname: newHost, resourcePath: newPath } = parseTsUri(newUri);

if (!oldHost) {
throw new Error('hostname is undefined');
Expand All @@ -176,8 +178,8 @@ export class TSFileSystemProvider implements vscode.FileSystemProvider {
scp(src: vscode.Uri, dest: vscode.Uri): Promise<void> {
Logger.info('scp', 'tsFs');

const { resourcePath: srcPath } = this.extractHostAndPath(src);
const { hostname: destHostName, resourcePath: destPath } = this.extractHostAndPath(dest);
const { resourcePath: srcPath } = parseTsUri(src);
const { hostname: destHostName, resourcePath: destPath } = parseTsUri(dest);

const command = `scp ${srcPath} ${destHostName}:${destPath}`;

Expand All @@ -191,31 +193,4 @@ export class TSFileSystemProvider implements vscode.FileSystemProvider {
});
});
}

public extractHostAndPath(uri: vscode.Uri): { hostname: string | null; resourcePath: string } {
switch (uri.scheme) {
case 'ts': {
let hostPath = uri.path;
if (hostPath.startsWith('/')) {
// Remove leading slash
hostPath = hostPath.slice(1);
}
const segments = hostPath.split('/');
const [hostname, ...pathSegments] = segments;
let resourcePath = decodeURIComponent(pathSegments.join('/'));
if (resourcePath !== '~') {
resourcePath = `/${escapeSpace(resourcePath)}`;
}
return { hostname, resourcePath };
}
case 'file':
return { hostname: null, resourcePath: escapeSpace(uri.path) };
default:
throw new Error(`Unsupported scheme: ${uri.scheme}`);
}
}
}

function escapeSpace(str: string): string {
return str.replace(/\s/g, '\\ ');
}
26 changes: 26 additions & 0 deletions src/utils/string.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { test, describe, expect } from 'vitest';
import { escapeSpace, trimSuffix } from './string';

describe('escapeSpace', () => {
test('escapes spaces', () => {
const result = escapeSpace('foo bar');
expect(result).toEqual('foo\\ bar');
});

test('does not escape other characters', () => {
const result = escapeSpace('foo-bar');
expect(result).toEqual('foo-bar');
});
});

describe('trimSuffix', () => {
test('trims the suffix', () => {
const result = trimSuffix('foo.bar', '.bar');
expect(result).toEqual('foo');
});

test('does not trim the suffix if it does not match', () => {
const result = trimSuffix('foo.bar', '.baz');
expect(result).toEqual('foo.bar');
});
});
4 changes: 4 additions & 0 deletions src/utils/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,7 @@ export function trimSuffix(str: string | undefined, suffix: string) {

return str.endsWith(suffix) ? str.slice(0, -suffix.length) : str;
}

export function escapeSpace(str: string): string {
return str.replace(/\s/g, '\\ ');
}
35 changes: 35 additions & 0 deletions src/utils/uri.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { test, expect, vi } from 'vitest';
import { parseTsUri } from './uri';
import { URI } from 'vscode-uri';

vi.mock('vscode');

test('parses ts URIs correctly', () => {
const testUri = URI.parse('ts://tailnet-scales/foo/home/amalie');
const expected = {
hostname: 'foo',
tailnet: 'tailnet-scales',
resourcePath: '/home/amalie',
};

const result = parseTsUri(testUri);
expect(result).toEqual(expected);
});

test('throws an error when scheme is not supported', () => {
const testUri = URI.parse('http://example.com');

expect(() => parseTsUri(testUri)).toThrow('Unsupported scheme: http');
});

test('correctly returns ~ as a resourcePath', () => {
const testUri = URI.parse('ts://tailnet-scales/foo/~');
const expected = {
hostname: 'foo',
tailnet: 'tailnet-scales',
resourcePath: '~',
};

const result = parseTsUri(testUri);
expect(result).toEqual(expected);
});
40 changes: 40 additions & 0 deletions src/utils/uri.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import * as vscode from 'vscode';
import { escapeSpace } from './string';

export interface TsUri {
hostname: string;
tailnet: string;
resourcePath: string;
}

/**
*
* ts://tails-scales/foo/home/amalie
* |> tailnet: tails-scales
* |> hostname: foo
* |> resourcePath: /home/amalie
*/

export function parseTsUri(uri: vscode.Uri): TsUri {
switch (uri.scheme) {
case 'ts': {
let hostPath = uri.path;
if (hostPath.startsWith('/')) {
// Remove leading slash
hostPath = hostPath.slice(1);
}

const segments = hostPath.split('/');
const [hostname, ...pathSegments] = segments;

let resourcePath = decodeURIComponent(pathSegments.join('/'));
if (resourcePath !== '~') {
resourcePath = `/${escapeSpace(resourcePath)}`;
}

return { hostname, tailnet: uri.authority, resourcePath };
}
default:
throw new Error(`Unsupported scheme: ${uri.scheme}`);
}
}
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -6109,6 +6109,11 @@ vscode-jsonrpc@^8.1.0:
resolved "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-8.1.0.tgz"
integrity sha512-6TDy/abTQk+zDGYazgbIPc+4JoXdwC8NHU9Pbn4UJP1fehUyZmM4RHp5IthX7A6L5KS30PRui+j+tbbMMMafdw==

vscode-uri@^3.0.7:
version "3.0.7"
resolved "https://registry.yarnpkg.com/vscode-uri/-/vscode-uri-3.0.7.tgz#6d19fef387ee6b46c479e5fb00870e15e58c1eb8"
integrity sha512-eOpPHogvorZRobNqJGhapa0JdwaxpjVvyBp0QIUMRMSf8ZAlqOdEquKuRmw9Qwu0qXtJIWqFtMkmvJjUZmMjVA==

watchpack@^2.4.0:
version "2.4.0"
resolved "https://registry.yarnpkg.com/watchpack/-/watchpack-2.4.0.tgz#fa33032374962c78113f93c7f2fb4c54c9862a5d"
Expand Down