Skip to content
This repository has been archived by the owner on May 9, 2021. It is now read-only.

Commit

Permalink
initial
Browse files Browse the repository at this point in the history
  • Loading branch information
hdevalke committed Jul 14, 2018
0 parents commit 54e442a
Show file tree
Hide file tree
Showing 16 changed files with 428 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Set default behavior to automatically normalize line endings.
* text=auto

4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
out
node_modules
.vscode-test/
*.vsix
36 changes: 36 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// A launch configuration that compiles the extension and then opens it inside a new window
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
{
"version": "0.2.0",
"configurations": [
{
"name": "Extension",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
"--extensionDevelopmentPath=${workspaceFolder}"
],
"outFiles": [
"${workspaceFolder}/out/**/*.js"
],
"preLaunchTask": "npm: watch"
},
{
"name": "Extension Tests",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
"--extensionDevelopmentPath=${workspaceFolder}",
"--extensionTestsPath=${workspaceFolder}/out/test"
],
"outFiles": [
"${workspaceFolder}/out/test/**/*.js"
],
"preLaunchTask": "npm: watch"
}
]
}
11 changes: 11 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// Place your settings in this file to overwrite default and user settings.
{
"files.exclude": {
"out": false // set this to true to hide the "out" folder with the compiled JS files
},
"search.exclude": {
"out": true // set this to false to include "out" folder in search results
},
// Turn off tsc task auto detection since we have the necessary tasks as npm scripts
"typescript.tsc.autoDetect": "off"
}
20 changes: 20 additions & 0 deletions .vscode/tasks.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
{
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "watch",
"problemMatcher": "$tsc-watch",
"isBackground": true,
"presentation": {
"reveal": "never"
},
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
9 changes: 9 additions & 0 deletions .vscodeignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
.vscode/**
.vscode-test/**
out/test/**
out/**/*.map
src/**
.gitignore
tsconfig.json
vsc-extension-quickstart.md
tslint.json
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Change Log

All notable changes to the "rust-test-lens" extension will be documented in this file.

Check [Keep a Changelog](https://keepachangelog.com/) for recommendations on how to structure this file.

## [Unreleased]

- Initial release
- Adds a codelens to quickly debug a specific test.
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2018 Hannes De Valkeneer

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Rust Test Lens

Adds a code lens to rust source files in order to quickly run tests.

## Requirements

Depends on the LLDB extension [vscode-lldb](https://marketplace.visualstudio.com/items?itemName=vadimcn.vscode-lldb).

## Extension Settings

This extension can be enabled/disabled using the following setting:

* `rust_test_lens.enable`: true/false to enable/disable this extension
59 changes: 59 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
{
"name": "rust-test-lens",
"displayName": "Rust Test Lens",
"description": "Adds a code lens to quickly run or debug a single test for your Rust code.",
"version": "0.0.1",
"publisher": "hdevalke",
"engines": {
"vscode": "^1.25.0"
},
"categories": [
"Other", "Programming Languages"
],
"activationEvents": [
"onCommand:extension.debugTest",
"onLanguage:rust"
],
"main": "./out/extension",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/hdevalke/rust-test-lens.git"
},
"scripts": {
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"watch": "tsc -watch -p ./",
"postinstall": "node ./node_modules/vscode/bin/install",
"test": "npm run compile && node ./node_modules/vscode/bin/test"
},
"devDependencies": {
"typescript": "^2.9.2",
"vscode": "^1.1.18",
"tslint": "^5.10.0",
"@types/node": "^10.5.2",
"@types/mocha": "^5.2.4"
},
"extensionDependencies": [
"vadimcn.vscode-lldb"
],
"contributes": {
"commands": [
{
"command": "extension.debugTest",
"title": "Debug Rust Test"
}
],
"configuration": {
"type": "object",
"title": "Rust Test Lens configuration",
"properties": {
"rust-test-lens.enabled": {
"type": "boolean",
"default": true,
"description": "Enable or disable this extension"
}
}
}
}
}
72 changes: 72 additions & 0 deletions src/RustCodeLensProvider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
'use strict';
import {
CancellationToken, CodeLens, CodeLensProvider, Event, EventEmitter,
Range, TextDocument, DebugConfiguration
} from 'vscode';
import { RustTests } from './RustTests';
import { basename } from 'path';

export class RustCodeLensProvider implements CodeLensProvider {

private static readonly TEST_LEN = "#[test]".length;

constructor(private _onDidChange: EventEmitter<void>,
private rustTests: RustTests) {
}

get onDidChangeCodeLenses(): Event<void> {
return this._onDidChange.event;
}

public async provideCodeLenses(doc: TextDocument,
token: CancellationToken): Promise<CodeLens[]> {
if (token.isCancellationRequested) {
return [];
}
const text = doc.getText();
const reTest = /#\[test\]/g;
const reFnTest = /fn\s+(.+)\s*\(\s*\)/g;
let lenses: CodeLens[] = [];
while (reTest.exec(text) !== null) {
const end = doc.positionAt(reTest.lastIndex);
let startIdx = reTest.lastIndex - RustCodeLensProvider.TEST_LEN;
const start = doc.positionAt(startIdx);
const range = new Range(start, end);
reFnTest.lastIndex = reTest.lastIndex;
const match = reFnTest.exec(text);
const fn = match === null ? null : match[1];
if (fn) {
const debugConfig = this.createDebugConfig(fn, doc.fileName);
if (debugConfig) {
lenses.push(new CodeLens(range, {
title: 'Debug test',
command: "extension.debugTest",
tooltip: 'Debug Test',
arguments: [debugConfig]
}));
}
}
}
return lenses;
}

createDebugConfig(fn: string, uri: string): DebugConfiguration | undefined {
const pkg = this.rustTests.getPackage(fn, uri);
if (pkg) {
return {
type: "lldb",
request: "launch",
name: `Debug ${fn} in ${basename(uri)}`,
cargo: {
"args": [
"test",
"--no-run",
`--package=${pkg.name}`
]
},
"args": [fn],
"cwd": "${workspaceFolder}"
};
}
}
}
26 changes: 26 additions & 0 deletions src/RustTests.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
'use strict';
import { Metadata, Package } from "./cargo";
import { dirname } from "path";

export class RustTests {
private readonly testMap: Map<string, Package> = new Map<string, Package>();
constructor(private metadata: Metadata) {

}
/**
* Get the package based on the function name.
* @param fn function name
*/
getPackage(fn: string, uri: string): Package | undefined {
let pkg = this.testMap.get(fn);
if (!pkg) {
for (pkg of this.metadata.packages) {
let pkg_dir = dirname(pkg.manifest_path);
if (uri.startsWith(pkg_dir)) {
break;
}
}
}
return pkg;
}
}
64 changes: 64 additions & 0 deletions src/cargo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
'use strict';
// Helper function and interfaces to work with cargo metadata.
import { workspace } from "vscode";
import { spawn } from "child_process";

export interface Package {
name: string;
authors: string[];
version: string;
manifest_path: string;
}

export interface Metadata {
packages: Package[];
target_directory: string;
version: number;
workspace_members: string[];
workspace_root: string;
}

type StrSink = (data: string) => void;

export async function metadata(onStdErr?: StrSink): Promise<Metadata> {
let meta = "";
const cargoArgs = [
"metadata",
"--no-deps",
"--format-version=1"];
return runCargo(cargoArgs, data => meta += data, onStdErr)
.then(_ => JSON.parse(meta))
.catch((errInfo) => console.error(`Couldn't get metadata: ${errInfo}`));
}


async function runCargo(args?: ReadonlyArray<string>, onStdOut?: StrSink,
onStdErr?: StrSink): Promise<number> {
return new Promise<number>((resolve, reject) => {
const workspaceFolders = workspace.workspaceFolders;
const options = {
cwd: workspaceFolders ? workspaceFolders[0].uri.fsPath : undefined,
stdio: ['ignore', 'pipe', 'pipe'],
};
const proc = spawn("cargo", args, options);
proc.on('error', err => reject(err));

proc.stderr.on('data', chunk => {
if (onStdErr) {
onStdErr(chunk.toString());
}
});

proc.stdout.on('data', chunk => {
if (onStdOut) {
onStdOut(chunk.toString());
}
});

proc.on('exit', (exitCode, signal) => {
exitCode === 0
? resolve(exitCode)
: reject({ exitCode: exitCode, signal: signal });
});
});
}
Loading

0 comments on commit 54e442a

Please sign in to comment.