Merge pull request #99 from lyyyuna/vscode-ext

vscode extension init
This commit is contained in:
qiniu-bot 2020-09-02 19:41:17 +08:00 committed by GitHub
commit 976c0a8aad
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
19 changed files with 1634 additions and 3 deletions

3
.gitignore vendored
View File

@ -1,6 +1,3 @@
# Vscode files
.vscode
# ignore log file # ignore log file
**/goc.log **/goc.log

4
tools/vscode-ext/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
out
node_modules
.vscode-test/
*.vsix

View File

@ -0,0 +1,7 @@
{
// See http://go.microsoft.com/fwlink/?LinkId=827846
// for the documentation about the extensions.json format
"recommendations": [
"ms-vscode.vscode-typescript-tslint-plugin"
]
}

36
tools/vscode-ext/.vscode/launch.json vendored Normal file
View File

@ -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": "Run Extension",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
"--extensionDevelopmentPath=${workspaceFolder}"
],
"outFiles": [
"${workspaceFolder}/out/**/*.js"
],
"preLaunchTask": "${defaultBuildTask}"
},
{
"name": "Extension Tests",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
"--extensionDevelopmentPath=${workspaceFolder}",
"--extensionTestsPath=${workspaceFolder}/out/test/suite/index"
],
"outFiles": [
"${workspaceFolder}/out/test/**/*.js"
],
"preLaunchTask": "${defaultBuildTask}"
}
]
}

11
tools/vscode-ext/.vscode/settings.json vendored Normal file
View File

@ -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
tools/vscode-ext/.vscode/tasks.json vendored Normal file
View File

@ -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
}
}
]
}

View File

@ -0,0 +1,10 @@
.vscode/**
.vscode-test/**
out/test/**
src/**
.gitignore
vsc-extension-quickstart.md
**/tsconfig.json
**/tslint.json
**/*.map
**/*.ts

View File

@ -0,0 +1,9 @@
# Change Log
All notable changes to the "goc" extension will be documented in this file.
Check [Keep a Changelog](http://keepachangelog.com/) for recommendations on how to structure this file.
## 0.0.3 2020-09-02
- Initial release

View File

@ -0,0 +1,44 @@
# Goc Coverage
This extension provides rich support for the [goc](https://github.com/qiniu/goc) tool.
## Overview
* [Getting started](#getting-started)
* [Ask for help](#ask-for-help)
## Getting started
Welcome! The [goc](https://github.com/qiniu/goc) is a coverage tool for Golang projects. The most interesting part of [goc](https://github.com/qiniu/goc) is that it can generate coverage report while the service is running! You can test the service manually or automatically, whatever, you don't have to stop the tested service to get the coverage report anymore.
This extension provides a frontend to show the covered lines in real time.
### Basic requirements
Before you started, make sure that you have:
1. Go
2. [goc](https://github.com/qiniu/goc)
3. source code of the tested service
### Set up your environment
Follow the [goc example](https://github.com/qiniu/goc#examples) guide to build and start the tested service. After you finished this step, there should be a **goc server** running at default port `7777`.
Use `vscode` to open the source code. Make sure the vscode's `workspace` is in the Golang project's root directory. If your project uses `go module`, just open vscode in the repo's directory. If your project uses `GOPATH`, you should setup right `GOPATH` before you open vscode.
Open any Go source files, you should see a `Goc Coverage OFF` button in the bottom status bar, click on the button to enable rendering covered lines in real time.
### Configuration
#### goc server url
If you deploy the goc server on another host with a customized port, you can set:
```
"goc.serverUrl": "http://192.168.1.3:51234"
```
## Ask for help
If you're having issues with this extension, please reach out to us by [filing an issue](https://github.com/qiniu/goc/issues/new/choose) directly.

1055
tools/vscode-ext/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,62 @@
{
"name": "goc",
"displayName": "Goc Coverage",
"description": "Goc Coverage can display coverage vairation in real time. Goc is a comprehensive coverage testing system for The Go Programming Language, especially for some complex scenarios, like system testing code coverage collection and accurate testing.",
"version": "0.0.3",
"publisher": "lyyyuna",
"repository": {
"url": "https://github.com/qiniu/goc"
},
"engines": {
"vscode": "^1.43.0"
},
"categories": [
"Other"
],
"activationEvents": [
"onLanguage:go"
],
"main": "./out/extension.js",
"contributes": {
"commands": [
{
"command": "extension.switch",
"title": "Enable/Disable coverage report"
}
],
"configuration": {
"title": "Goc",
"properties": {
"goc.serverUrl": {
"type": "string",
"default": "http://127.0.0.1:7777",
"items": {
"type": "string"
},
"description": "Specify the goc server url."
}
}
}
},
"scripts": {
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"watch": "tsc -watch -p ./",
"pretest": "npm run compile",
"test": "node ./out/test/runTest.js"
},
"devDependencies": {
"@types/glob": "^7.1.1",
"@types/mocha": "^5.2.7",
"@types/node": "^12.11.7",
"@types/vscode": "^1.43.0",
"glob": "^7.1.5",
"mocha": "^6.2.2",
"typescript": "^3.6.4",
"tslint": "^5.20.0",
"vscode-test": "^1.2.2"
},
"dependencies": {
"axios": "^0.19.2"
}
}

View File

@ -0,0 +1,38 @@
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
import { GocServer } from './gocserver';
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {
let gocStatusBarItem: vscode.StatusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left, 0);
gocStatusBarItem.text = 'Goc Coverage OFF';
gocStatusBarItem.command = 'extension.switch';
gocStatusBarItem.show();
let gocserver = new GocServer();
let disposable2 = vscode.commands.registerCommand('extension.switch', async () => {
if (gocStatusBarItem.text == 'Goc Coverage OFF') {
let err = gocserver.checkGoEnv()
// check if pc meets extension's requirement
if (err) {
vscode.window.showErrorMessage('Cannot get Golang version, please check your go environment.')
return
}
gocStatusBarItem.text = 'Goc Coverage ON';
// get current project package structure
let packages = gocserver.getGoList();
await gocserver.startQueryLoop(packages);
} else {
gocStatusBarItem.text = 'Goc Coverage OFF';
gocserver.stopQueryLoop();
}
})
context.subscriptions.push(disposable2);
}
export function deactivate() {}

View File

@ -0,0 +1,185 @@
import axios from 'axios';
axios.defaults.timeout = 3000;
import * as vscode from 'vscode';
import { spawnSync } from 'child_process';
import * as path from 'path';
import { promisify } from 'util';
const sleep = promisify(setTimeout);
export class GocServer {
private _serverUrl: string = '';
private timer = true;
private highlightDecorationType = vscode.window.createTextEditorDecorationType({
backgroundColor: 'green',
border: '2px solid white',
color: 'white'
});;
private lastProfile = '';
private lastFileNeedsRender = '';
construct() { }
async startQueryLoop(packages: any[]) {
this.timer = true;
while ( true === this.timer ) {
await sleep(2000);
if ( true !== this.timer ) {
this.clearHightlight();
return;
}
this.getConfigurations();
let profile = await this.getLatestProfile();
this.renderFile(packages, profile);
}
}
stopQueryLoop() {
this.timer = false;
this.lastProfile = '';
this.lastFileNeedsRender = '';
this.clearHightlight()
}
clearHightlight() {
vscode.window.visibleTextEditors.forEach(visibleEditor => {
visibleEditor.setDecorations(this.highlightDecorationType, []);
});
}
getConfigurations() {
this._serverUrl = vscode.workspace.getConfiguration().get('goc.serverUrl') || '';
}
async getLatestProfile(): Promise<string> {
let profileApi = `${this._serverUrl}/v1/cover/profile?force=true`;
try {
let res = await axios.get(profileApi, );
let body: string = res.data.toString();
return body;
} catch(err) {
console.error(err)
}
return "";
}
checkGoEnv() : Boolean {
let output = spawnSync('go', ['version']);
if (output.status != 0 || output.status == null) {
console.error(output.stderr.toString())
return true;
}
return false;
}
getGoList(): Array<any> {
let cwd = "";
let workspaces = vscode.workspace.workspaceFolders || [];
if (workspaces.length == 0) {
console.error("no workspace found");
return [];
} else {
cwd = workspaces[0].uri.path;
}
let opts = {
'cwd': cwd
};
let output = spawnSync('go', ['list', '-json', './...'], opts);
if (output.status != 0 || output.status == null) {
console.error(output.stderr.toString());
return [];
}
let packages = JSON.parse('[' + output.stdout.toString().replace(/}\n{/g, '},\n{') + ']');
return packages;
}
renderFile(packages: Array<any>, profile: string) {
let activeTextEditor = vscode.window.activeTextEditor;
let fileNeedsRender = activeTextEditor?.document.fileName || '---';
// check if needs to rerender
if (profile == this.lastProfile && fileNeedsRender == this.lastFileNeedsRender) {
return;
}
this.lastProfile = profile;
this.lastFileNeedsRender = fileNeedsRender;
for (let i=0; i<packages.length; i++) {
let p = packages[i];
let baseDir: string = p['Dir'];
for (let gofile of p['GoFiles']) {
let filepath = path.join(baseDir, gofile);
if (filepath == fileNeedsRender) {
let importPath: string = path.join(p['ImportPath'], gofile);
let ranges = this.parseProfile(profile, importPath)
this.triggerUpdateDecoration(ranges)
return;
}
}
}
}
parseProfile(profile: string, importPathNeedsRender: string): vscode.Range[] {
let lines = profile.split('\n');
if (lines.length <= 1) {
console.error("empty coverage profile from server");
return [];
}
let ranges: vscode.Range[] = [];
for (let i=0; i<lines.length; i++) {
let line = lines[i];
let importPath: string = line.split(':')[0];
let blockInfo: string = line.split(':')[1];
if (importPath != importPathNeedsRender) {
continue;
}
let rxp = /(\d+)\.(\d+),(\d+)\.(\d+)\s(\d+)\s(\d+)/g
let matches = rxp.exec(blockInfo)!;
let startLine = matches[1];
let startCol = matches[2];
let endLine = matches[3];
let endCol = matches[4];
let stmts = matches[5];
let count = matches[6];
// no need to render code block not covered
if (count == '0') {
continue;
}
let range = new vscode.Range(
new vscode.Position(Number(startLine)-1, Number(startCol)-1),
new vscode.Position(Number(endLine)-1, Number(endCol)-1)
);
ranges.push(range);
}
return ranges
}
triggerUpdateDecoration(ranges: vscode.Range[]) {
if (!vscode.window.activeTextEditor) {
return;
}
console.debug('[' + new Date().toUTCString() + '] ' + 'update latest profile success')
if (ranges.length == 0) {
this.clearHightlight();
} else {
vscode.window.activeTextEditor.setDecorations(
this.highlightDecorationType,
ranges
)
}
}
}

View File

@ -0,0 +1,23 @@
import * as path from 'path';
import { runTests } from 'vscode-test';
async function main() {
try {
// The folder containing the Extension Manifest package.json
// Passed to `--extensionDevelopmentPath`
const extensionDevelopmentPath = path.resolve(__dirname, '../../');
// The path to test runner
// Passed to --extensionTestsPath
const extensionTestsPath = path.resolve(__dirname, './suite/index');
// Download VS Code, unzip it and run the integration test
await runTests({ extensionDevelopmentPath, extensionTestsPath });
} catch (err) {
console.error('Failed to run tests');
process.exit(1);
}
}
main();

View File

@ -0,0 +1,15 @@
import * as assert from 'assert';
// You can import and use all API from the 'vscode' module
// as well as import your extension to test it
import * as vscode from 'vscode';
// import * as myExtension from '../extension';
suite('Extension Test Suite', () => {
vscode.window.showInformationMessage('Start all tests.');
test('Sample test', () => {
assert.equal(-1, [1, 2, 3].indexOf(5));
assert.equal(-1, [1, 2, 3].indexOf(0));
});
});

View File

@ -0,0 +1,37 @@
import * as path from 'path';
import * as Mocha from 'mocha';
import * as glob from 'glob';
export function run(): Promise<void> {
// Create the mocha test
const mocha = new Mocha({
ui: 'tdd',
});
mocha.useColors(true);
const testsRoot = path.resolve(__dirname, '..');
return new Promise((c, e) => {
glob('**/**.test.js', { cwd: testsRoot }, (err, files) => {
if (err) {
return e(err);
}
// Add files to the test suite
files.forEach(f => mocha.addFile(path.resolve(testsRoot, f)));
try {
// Run the mocha test
mocha.run(failures => {
if (failures > 0) {
e(new Error(`${failures} tests failed.`));
} else {
c();
}
});
} catch (err) {
e(err);
}
});
});
}

View File

@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"outDir": "out",
"lib": [
"es6"
],
"sourceMap": true,
"rootDir": "src",
"strict": true /* enable all strict type-checking options */
/* Additional Checks */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
},
"exclude": [
"node_modules",
".vscode-test"
]
}

View File

@ -0,0 +1,15 @@
{
"rules": {
"no-string-throw": true,
"no-unused-expression": true,
"no-duplicate-variable": true,
"curly": true,
"class-name": true,
"semicolon": [
true,
"always"
],
"triple-equals": true
},
"defaultSeverity": "warning"
}

View File

@ -0,0 +1,42 @@
# Welcome to your VS Code Extension
## What's in the folder
* This folder contains all of the files necessary for your extension.
* `package.json` - this is the manifest file in which you declare your extension and command.
* The sample plugin registers a command and defines its title and command name. With this information VS Code can show the command in the command palette. It doesnt yet need to load the plugin.
* `src/extension.ts` - this is the main file where you will provide the implementation of your command.
* The file exports one function, `activate`, which is called the very first time your extension is activated (in this case by executing the command). Inside the `activate` function we call `registerCommand`.
* We pass the function containing the implementation of the command as the second parameter to `registerCommand`.
## Get up and running straight away
* Press `F5` to open a new window with your extension loaded.
* Run your command from the command palette by pressing (`Ctrl+Shift+P` or `Cmd+Shift+P` on Mac) and typing `Hello World`.
* Set breakpoints in your code inside `src/extension.ts` to debug your extension.
* Find output from your extension in the debug console.
## Make changes
* You can relaunch the extension from the debug toolbar after changing code in `src/extension.ts`.
* You can also reload (`Ctrl+R` or `Cmd+R` on Mac) the VS Code window with your extension to load your changes.
## Explore the API
* You can open the full set of our API when you open the file `node_modules/@types/vscode/index.d.ts`.
## Run tests
* Open the debug viewlet (`Ctrl+Shift+D` or `Cmd+Shift+D` on Mac) and from the launch configuration dropdown pick `Extension Tests`.
* Press `F5` to run the tests in a new window with your extension loaded.
* See the output of the test result in the debug console.
* Make changes to `src/test/suite/extension.test.ts` or create new test files inside the `test/suite` folder.
* The provided test runner will only consider files matching the name pattern `**.test.ts`.
* You can create folders inside the `test` folder to structure your tests any way you want.
## Go further
* Reduce the extension size and improve the startup time by [bundling your extension](https://code.visualstudio.com/api/working-with-extensions/bundling-extension).
* [Publish your extension](https://code.visualstudio.com/api/working-with-extensions/publishing-extension) on the VSCode extension marketplace.
* Automate builds by setting up [Continuous Integration](https://code.visualstudio.com/api/working-with-extensions/continuous-integration).