瀏覽代碼

Initial commit -- very basic blame support

main
Eric Amodio 8 年之前
當前提交
53bebc89f2
共有 17 個檔案被更改,包括 456 行新增0 行删除
  1. +2
    -0
      .gitignore
  2. +28
    -0
      .vscode/launch.json
  3. +12
    -0
      .vscode/settings.json
  4. +30
    -0
      .vscode/tasks.json
  5. +9
    -0
      .vscodeignore
  6. +22
    -0
      LICENSE
  7. +65
    -0
      README.md
  8. +34
    -0
      package.json
  9. +72
    -0
      src/codeLensProvider.ts
  10. +21
    -0
      src/extension.ts
  11. +68
    -0
      src/git.ts
  12. +22
    -0
      test/extension.test.ts
  13. +22
    -0
      test/index.ts
  14. +14
    -0
      tsconfig.json
  15. +1
    -0
      typings/node.d.ts
  16. +1
    -0
      typings/vscode-typings.d.ts
  17. +33
    -0
      vsc-extension-quickstart.md

+ 2
- 0
.gitignore 查看文件

@ -0,0 +1,2 @@
out
node_modules

+ 28
- 0
.vscode/launch.json 查看文件

@ -0,0 +1,28 @@
// A launch configuration that compiles the extension and then opens it inside a new window
{
"version": "0.1.0",
"configurations": [
{
"name": "Launch Extension",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": ["--extensionDevelopmentPath=${workspaceRoot}" ],
"stopOnEntry": false,
"sourceMaps": true,
"outDir": "${workspaceRoot}/out/src",
"preLaunchTask": "npm"
},
{
"name": "Launch Tests",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": ["--extensionDevelopmentPath=${workspaceRoot}", "--extensionTestsPath=${workspaceRoot}/out/test" ],
"stopOnEntry": false,
"sourceMaps": true,
"outDir": "${workspaceRoot}/out/test",
"preLaunchTask": "npm"
}
]
}

+ 12
- 0
.vscode/settings.json 查看文件

@ -0,0 +1,12 @@
// 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
"node_modules": false
},
"search.exclude": {
"out": true, // set this to false to include "out" folder in search results
"node_modules": true
},
"typescript.tsdk": "./node_modules/typescript/lib" // we want to use the TS server from our node_modules folder to control its version
}

+ 30
- 0
.vscode/tasks.json 查看文件

@ -0,0 +1,30 @@
// Available variables which can be used inside of strings.
// ${workspaceRoot}: the root folder of the team
// ${file}: the current opened file
// ${fileBasename}: the current opened file's basename
// ${fileDirname}: the current opened file's dirname
// ${fileExtname}: the current opened file's extension
// ${cwd}: the current working directory of the spawned process
// A task runner that calls a custom npm script that compiles the extension.
{
"version": "0.1.0",
// we want to run npm
"command": "npm",
// the command is a shell script
"isShellCommand": true,
// show the output window only if unrecognized errors occur.
"showOutput": "silent",
// we run the custom script "compile" as defined in package.json
"args": ["run", "compile", "--loglevel", "silent"],
// The tsc compiler is started in watching mode
"isWatching": true,
// use the standard tsc in watch mode problem matcher to find compile problems in the output.
"problemMatcher": "$tsc-watch"
}

+ 9
- 0
.vscodeignore 查看文件

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

+ 22
- 0
LICENSE 查看文件

@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2016 Eric Amodio
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.

+ 65
- 0
README.md 查看文件

@ -0,0 +1,65 @@
# git-codelens README
This is the README for your extension "git-codelens". After writing up a brief description, we recommend including the following sections.
## Features
Describe specific features of your extension including screenshots of your extension in action. Image paths are relative to this README file.
For example if there is an image subfolder under your extension project workspace:
\!\[feature X\]\(images/feature-x.png\)
> Tip: Many popular extensions utilize animations. This is an excellent way to show off your extension! We recommend short, focused animations that are easy to follow.
## Requirements
If you have any requirements or dependencies, add a section describing those and how to install and configure them.
## Extension Settings
Include if your extension adds any VS Code settings through the `contributes.configuration` extension point.
For example:
This extension contributes the following settings:
* `myExtension.enable`: enable/disable this extension
* `myExtension.thing`: set to `blah` to do something
## Known Issues
Calling out known issues can help limit users opening duplicate issues against your extension.
## Release Notes
Users appreciate release notes as you update your extension.
### 1.0.0
Initial release of ...
### 1.0.1
Fixed issue #.
### 1.1.0
Added features X, Y, and Z.
-----------------------------------------------------------------------------------------------------------
## Working with Markdown
**Note:** You can author your README using Visual Studio Code. Here are some useful editor keyboard shortcuts:
* Split the editor (`Cmd+\` on OSX or `Ctrl+\` on Windows and Linux)
* Toggle preview (`Shift+CMD+V` on OSX or `Shift+Ctrl+V` on Windows and Linux)
* Press `Ctrl+Space` (Windows, Linux) or `Cmd+Space` (OSX) to see a list of Markdown snippets
### For more information
* [Visual Studio Code's Markdown Support](http://code.visualstudio.com/docs/languages/markdown)
* [Markdown Syntax Reference](https://help.github.com/articles/markdown-basics/)
**Enjoy!**

+ 34
- 0
package.json 查看文件

@ -0,0 +1,34 @@
{
"name": "git-codelens",
"displayName": "Git CodeLens",
"description": "Provides Git blame information in CodeLens",
"version": "0.0.1",
"author": "Eric Amodio",
"publisher": "eamodio",
"engines": {
"vscode": "^1.3.0"
},
"categories": [
"Other"
],
"activationEvents": [
"*"
],
"keywords": [
"git", "gitblame", "blame"
],
"main": "./out/src/extension",
"contributes": {
},
"scripts": {
"vscode:prepublish": "node ./node_modules/vscode/bin/compile",
"compile": "node ./node_modules/vscode/bin/compile -watch -p ./",
"postinstall": "node ./node_modules/vscode/bin/install && tsc"
},
"dependencies": {
},
"devDependencies": {
"typescript": "^1.8.10",
"vscode": "^0.11.15"
}
}

+ 72
- 0
src/codeLensProvider.ts 查看文件

@ -0,0 +1,72 @@
'use strict';
import {CancellationToken, CodeLens, CodeLensProvider, commands, Range, SymbolInformation, SymbolKind, TextDocument, Uri} from 'vscode';
import {IBlameLine, gitBlame} from './git';
import * as moment from 'moment';
export class GitCodeLens extends CodeLens {
constructor(public blame: Promise<IBlameLine[]>, public fileName: string, public blameRange: Range, range: Range) {
super(range);
this.blame = blame;
this.fileName = fileName;
this.blameRange = blameRange;
}
}
export default class GitCodeLensProvider implements CodeLensProvider {
constructor(public repoPath: string) { }
provideCodeLenses(document: TextDocument, token: CancellationToken): CodeLens[] | Thenable<CodeLens[]> {
// TODO: Should I wait here?
let blame = gitBlame(document.fileName);
return (commands.executeCommand('vscode.executeDocumentSymbolProvider', document.uri) as Promise<SymbolInformation[]>).then(symbols => {
let lenses: CodeLens[] = [];
symbols.forEach(sym => this._provideCodeLens(document, sym, blame, lenses));
return lenses;
});
}
private _provideCodeLens(document: TextDocument, symbol: SymbolInformation, blame: Promise<IBlameLine[]>, lenses: CodeLens[]): void {
switch (symbol.kind) {
case SymbolKind.Module:
case SymbolKind.Class:
case SymbolKind.Interface:
case SymbolKind.Method:
case SymbolKind.Function:
case SymbolKind.Constructor:
case SymbolKind.Field:
case SymbolKind.Property:
break;
default:
return;
}
var line = document.lineAt(symbol.location.range.start);
// if (line.text.includes(symbol.name)) {
// }
let lens = new GitCodeLens(blame, document.fileName, symbol.location.range, line.range);
lenses.push(lens);
}
resolveCodeLens(codeLens: CodeLens, token: CancellationToken): Thenable<CodeLens> {
if (codeLens instanceof GitCodeLens) {
return codeLens.blame.then(allLines => {
let lines = allLines.slice(codeLens.blameRange.start.line, codeLens.blameRange.end.line + 1);
let line = lines[0];
if (lines.length > 1) {
let sorted = lines.sort((a, b) => b.date.getTime() - a.date.getTime());
line = sorted[0];
}
codeLens.command = {
title: `${line.author}, ${moment(line.date).fromNow()}`,
command: 'git.viewFileHistory',
arguments: [Uri.file(codeLens.fileName)]
};
return codeLens;
});//.catch(ex => Promise.reject(ex)); // TODO: Figure out a better way to stop the codelens from appearing
}
}
}

+ 21
- 0
src/extension.ts 查看文件

@ -0,0 +1,21 @@
'use strict';
import {DocumentSelector, ExtensionContext, languages, workspace} from 'vscode';
import GitCodeLensProvider from './codeLensProvider';
import {gitRepoPath} from './git'
// this method is called when your extension is activated
export function activate(context: ExtensionContext) {
// Workspace not using a folder. No access to git repo.
if (!workspace.rootPath) {
return;
}
gitRepoPath(workspace.rootPath).then(repoPath => {
let selector: DocumentSelector = { scheme: 'file' };
context.subscriptions.push(languages.registerCodeLensProvider(selector, new GitCodeLensProvider(repoPath)));
}).catch(reason => console.warn(reason));
}
// this method is called when your extension is deactivated
export function deactivate() {
}

+ 68
- 0
src/git.ts 查看文件

@ -0,0 +1,68 @@
'use strict';
import {spawn} from 'child_process';
import {dirname} from 'path';
export declare interface IBlameLine {
line: number;
author: string;
date: Date;
sha: string;
//code: string;
}
export function gitRepoPath(cwd) {
const mapper = (input, output) => {
output.push(input.toString().replace(/\r?\n|\r/g, ''))
};
return new Promise<string>((resolve, reject) => {
gitCommand(cwd, mapper, 'rev-parse', '--show-toplevel')
.then(result => resolve(result[0]))
.catch(reason => reject(reason));
});
}
const blameMatcher = /^(.*)\t\((.*)\t(.*)\t(.*?)\)(.*)$/gm;
export function gitBlame(fileName: string) {
const mapper = (input, output) => {
let m: Array<string>;
while ((m = blameMatcher.exec(input.toString())) != null) {
output.push({
line: parseInt(m[4], 10),
author: m[2],
date: new Date(m[3]),
sha: m[1]
//code: m[5]
});
}
};
return gitCommand(dirname(fileName), mapper, 'blame', '-c', '-M', '-w', '--', fileName) as Promise<IBlameLine[]>;
}
function gitCommand(cwd: string, map: (input: Buffer, output: Array<any>) => void, ...args): Promise<any> {
return new Promise<any>((resolve, reject) => {
let spawn = require('child_process').spawn;
let process = spawn('git', args, { cwd: cwd });
let output: Array<any> = [];
process.stdout.on('data', data => {
map(data, output);
});
let errors: Array<string> = [];
process.stderr.on('data', err => {
errors.push(err.toString());
});
process.on('close', (exitCode, exitSignal) => {
if (exitCode && errors.length) {
reject(errors.toString());
return;
}
resolve(output);
});
});
}

+ 22
- 0
test/extension.test.ts 查看文件

@ -0,0 +1,22 @@
//
// Note: This example test is leveraging the Mocha test framework.
// Please refer to their documentation on https://mochajs.org/ for help.
//
// The module 'assert' provides assertion methods from node
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 '../src/extension';
// Defines a Mocha test suite to group tests of similar kind together
suite("Extension Tests", () => {
// Defines a Mocha unit test
test("Something 1", () => {
assert.equal(-1, [1, 2, 3].indexOf(5));
assert.equal(-1, [1, 2, 3].indexOf(0));
});
});

+ 22
- 0
test/index.ts 查看文件

@ -0,0 +1,22 @@
//
// PLEASE DO NOT MODIFY / DELETE UNLESS YOU KNOW WHAT YOU ARE DOING
//
// This file is providing the test runner to use when running extension tests.
// By default the test runner in use is Mocha based.
//
// You can provide your own test runner if you want to override it by exporting
// a function run(testRoot: string, clb: (error:Error) => void) that the extension
// host can call to run the tests. The test runner is expected to use console.log
// to report the results back to the caller. When the tests are finished, return
// a possible error to the callback or null if none.
var testRunner = require('vscode/lib/testrunner');
// You can directly control Mocha options by uncommenting the following lines
// See https://github.com/mochajs/mocha/wiki/Using-mocha-programmatically#set-options for more info
testRunner.configure({
ui: 'tdd', // the TDD UI is being used in extension.test.ts (suite, test, etc.)
useColors: true // colored output from test results
});
module.exports = testRunner;

+ 14
- 0
tsconfig.json 查看文件

@ -0,0 +1,14 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"outDir": "out",
"noLib": true,
"sourceMap": true,
"rootDir": "."
},
"exclude": [
"node_modules",
".vscode-test"
]
}

+ 1
- 0
typings/node.d.ts 查看文件

@ -0,0 +1 @@
/// <reference path="../node_modules/vscode/typings/node.d.ts" />

+ 1
- 0
typings/vscode-typings.d.ts 查看文件

@ -0,0 +1 @@
/// <reference path="../node_modules/vscode/typings/index.d.ts" />

+ 33
- 0
vsc-extension-quickstart.md 查看文件

@ -0,0 +1,33 @@
# Welcome to your first 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 doesn’t 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/vscode/vscode.d.ts`
## Run tests
* open the debug viewlet (`Ctrl+Shift+D` or `Cmd+Shift+D` on Mac) and from the launch configuration dropdown pick `Launch 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 `test/extension.test.ts` or create new test files inside the `test` folder
* by convention, the 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

Loading…
取消
儲存