Просмотр исходного кода

Adds blame "references" (wip)

main
Eric Amodio 8 лет назад
Родитель
Сommit
b08044fc18
12 измененных файлов: 298 добавлений и 43 удалений
  1. Двоичные данные
      blame.png
  2. +6
    -0
      package.json
  3. +47
    -25
      src/codeLensProvider.ts
  4. +15
    -0
      src/constants.ts
  5. +81
    -0
      src/contentProvider.ts
  6. +21
    -0
      src/definitionProvider.ts
  7. +10
    -2
      src/extension.ts
  8. +59
    -16
      src/git.ts
  9. +5
    -0
      typings.json
  10. +45
    -0
      typings/globals/tmp/index.d.ts
  11. +8
    -0
      typings/globals/tmp/typings.json
  12. +1
    -0
      typings/index.d.ts

Двоичные данные
blame.png Просмотреть файл

До После
Ширина: 325  |  Высота: 325  |  Размер: 3.3 KiB

+ 6
- 0
package.json Просмотреть файл

@ -19,6 +19,11 @@
],
"main": "./out/src/extension",
"contributes": {
"commands": [{
"command": "git.codelen.showBlameHistory",
"title": "Show Blame History",
"category": "Git"
}]
},
"scripts": {
"vscode:prepublish": "node ./node_modules/vscode/bin/compile",
@ -26,6 +31,7 @@
"postinstall": "node ./node_modules/vscode/bin/install && tsc"
},
"dependencies": {
"tmp": "^0.0.28"
},
"devDependencies": {
"typescript": "^1.8.10",

+ 47
- 25
src/codeLensProvider.ts Просмотреть файл

@ -1,15 +1,21 @@
'use strict';
import {CancellationToken, CodeLens, CodeLensProvider, commands, Range, SymbolInformation, SymbolKind, TextDocument, Uri} from 'vscode';
import {IBlameLine, gitBlame} from './git';
import {CancellationToken, CodeLens, CodeLensProvider, commands, Location, Range, SymbolInformation, SymbolKind, TextDocument, Uri} from 'vscode';
import {Commands, VsCodeCommands} from './constants';
import {IGitBlameLine, gitBlame} from './git';
import {toGitBlameUri} from './contentProvider';
import * as moment from 'moment';
export class GitCodeLens extends CodeLens {
constructor(public blame: Promise<IBlameLine[]>, public fileName: string, public blameRange: Range, range: Range) {
constructor(private blame: Promise<IGitBlameLine[]>, public repoPath: string, public fileName: string, private blameRange: Range, range: Range) {
super(range);
}
getBlameLines(): Promise<IGitBlameLine[]> {
return this.blame.then(allLines => allLines.slice(this.blameRange.start.line, this.blameRange.end.line + 1));
}
this.blame = blame;
this.fileName = fileName;
this.blameRange = blameRange;
static toUri(lens: GitCodeLens, line: IGitBlameLine, lines: IGitBlameLine[]): Uri {
return toGitBlameUri(Object.assign({ repoPath: lens.repoPath, range: lens.blameRange, lines: lines }, line));
}
}
@ -20,14 +26,14 @@ export default class GitCodeLensProvider implements CodeLensProvider {
// TODO: Should I wait here?
let blame = gitBlame(document.fileName);
return (commands.executeCommand('vscode.executeDocumentSymbolProvider', document.uri) as Promise<SymbolInformation[]>).then(symbols => {
return (commands.executeCommand(VsCodeCommands.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 {
private _provideCodeLens(document: TextDocument, symbol: SymbolInformation, blame: Promise<IGitBlameLine[]>, lenses: CodeLens[]): void {
switch (symbol.kind) {
case SymbolKind.Module:
case SymbolKind.Class:
@ -43,30 +49,46 @@ export default class GitCodeLensProvider implements CodeLensProvider {
}
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);
let lens = new GitCodeLens(blame, this.repoPath, 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];
resolveCodeLens(lens: CodeLens, token: CancellationToken): Thenable<CodeLens> {
if (lens instanceof GitCodeLens) {
return lens.getBlameLines().then(lines => {
let recentLine = lines[0];
let locations: Location[] = [];
if (lines.length > 1) {
let sorted = lines.sort((a, b) => b.date.getTime() - a.date.getTime());
line = sorted[0];
let sorted = lines.sort((a, b) => a.date.getTime() - b.date.getTime());
recentLine = sorted[sorted.length - 1];
console.log(lens.fileName, 'Blame lines:', sorted);
let map: Map<string, IGitBlameLine[]> = new Map();
sorted.forEach(l => {
let item = map.get(l.sha);
if (item) {
item.push(l);
} else {
map.set(l.sha, [l]);
}
});
locations = Array.from(map.values()).map(l => new Location(GitCodeLens.toUri(lens, l[0], l), lens.range.start))
} else {
locations = [new Location(GitCodeLens.toUri(lens, recentLine, lines), lens.range.start)];
}
codeLens.command = {
title: `${line.author}, ${moment(line.date).fromNow()}`,
command: 'git.viewFileHistory',
arguments: [Uri.file(codeLens.fileName)]
lens.command = {
title: `${recentLine.author}, ${moment(recentLine.date).fromNow()}`,
command: Commands.ShowBlameHistory,
arguments: [Uri.file(lens.fileName), lens.range.start, locations]
// 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
return lens;
}).catch(ex => Promise.reject(ex)); // TODO: Figure out a better way to stop the codelens from appearing
}
}
}

+ 15
- 0
src/constants.ts Просмотреть файл

@ -0,0 +1,15 @@
export type Commands = 'git.action.showBlameHistory';
export const Commands = {
ShowBlameHistory: 'git.action.showBlameHistory' as Commands
}
export type DocumentSchemes = 'gitblame';
export const DocumentSchemes = {
GitBlame: 'gitblame' as DocumentSchemes
}
export type VsCodeCommands = 'vscode.executeDocumentSymbolProvider' | 'editor.action.showReferences';
export const VsCodeCommands = {
ExecuteDocumentSymbolProvider: 'vscode.executeDocumentSymbolProvider' as VsCodeCommands,
ShowReferences: 'editor.action.showReferences' as VsCodeCommands
}

+ 81
- 0
src/contentProvider.ts Просмотреть файл

@ -0,0 +1,81 @@
'use strict';
import {Disposable, EventEmitter, ExtensionContext, Location, OverviewRulerLane, Range, TextEditorDecorationType, TextDocumentContentProvider, Uri, window, workspace} from 'vscode';
import {DocumentSchemes} from './constants';
import {gitGetVersionFile, gitGetVersionText, IGitBlameLine} from './git';
import {basename, dirname, extname} from 'path';
import * as moment from 'moment';
export default class GitBlameContentProvider implements TextDocumentContentProvider {
static scheme = DocumentSchemes.GitBlame;
private _blameDecoration: TextEditorDecorationType;
private _onDidChange = new EventEmitter<Uri>();
constructor(context: ExtensionContext) {
let image = context.asAbsolutePath('blame.png');
this._blameDecoration = window.createTextEditorDecorationType({
backgroundColor: 'rgba(21, 251, 126, 0.7)',
gutterIconPath: image,
gutterIconSize: 'auto'
});
}
dispose() {
this._onDidChange.dispose();
}
get onDidChange() {
return this._onDidChange.event;
}
public update(uri: Uri) {
this._onDidChange.fire(uri);
}
provideTextDocumentContent(uri: Uri): string | Thenable<string> {
const data = fromGitBlameUri(uri);
console.log('provideTextDocumentContent', uri, data);
return gitGetVersionText(data.repoPath, data.sha, data.file).then(text => {
this.update(uri);
setTimeout(() => {
let uriString = uri.toString();
let editor = window.visibleTextEditors.find((e: any) => (e._documentData && e._documentData._uri && e._documentData._uri.toString()) === uriString);
if (editor) {
editor.setDecorations(this._blameDecoration, data.lines.map(l => new Range(l.line, 0, l.line, 1)));
}
}, 1500);
// let foo = text.split('\n');
// return foo.slice(data.range.start.line, data.range.end.line).join('\n')
return text;
});
// return gitGetVersionFile(data.repoPath, data.sha, data.file).then(dst => {
// let uri = Uri.parse(`file:${dst}`)
// return workspace.openTextDocument(uri).then(doc => {
// this.update(uri);
// return doc.getText();
// });
// });
}
}
export interface IGitBlameUriData extends IGitBlameLine {
repoPath: string,
range: Range,
lines: IGitBlameLine[]
}
export function toGitBlameUri(data: IGitBlameUriData) {
let ext = extname(data.file);
let path = `${dirname(data.file)}/${data.sha}: ${basename(data.file, ext)}${ext}`;
return Uri.parse(`${DocumentSchemes.GitBlame}:${path}?${JSON.stringify(data)}`);
}
export function fromGitBlameUri(uri: Uri): IGitBlameUriData {
let data = JSON.parse(uri.query);
data.range = new Range(data.range[0].line, data.range[0].character, data.range[1].line, data.range[1].character);
return data;
}

+ 21
- 0
src/definitionProvider.ts Просмотреть файл

@ -0,0 +1,21 @@
// 'use strict';
// import {CancellationToken, CodeLens, commands, DefinitionProvider, Position, Location, TextDocument, Uri} from 'vscode';
// import {GitCodeLens} from './codeLensProvider';
// export default class GitDefinitionProvider implements DefinitionProvider {
// public provideDefinition(document: TextDocument, position: Position, token: CancellationToken): Promise<Location> {
// return (commands.executeCommand('vscode.executeCodeLensProvider', document.uri) as Promise<CodeLens[]>).then(lenses => {
// let matches: CodeLens[] = [];
// lenses.forEach(lens => {
// if (lens instanceof GitCodeLens && lens.blameRange.contains(position)) {
// matches.push(lens);
// }
// });
// if (matches.length) {
// return new Location(Uri.parse(), position);
// }
// return null;
// });
// }
// }

+ 10
- 2
src/extension.ts Просмотреть файл

@ -1,7 +1,9 @@
'use strict';
import {DocumentSelector, ExtensionContext, languages, workspace} from 'vscode';
import {commands, DocumentSelector, ExtensionContext, languages, workspace} from 'vscode';
import GitCodeLensProvider from './codeLensProvider';
import {gitRepoPath} from './git'
import GitContentProvider from './contentProvider';
import {gitRepoPath} from './git';
import {Commands, VsCodeCommands} from './constants';
// this method is called when your extension is activated
export function activate(context: ExtensionContext) {
@ -11,6 +13,12 @@ export function activate(context: ExtensionContext) {
}
gitRepoPath(workspace.rootPath).then(repoPath => {
context.subscriptions.push(workspace.registerTextDocumentContentProvider(GitContentProvider.scheme, new GitContentProvider(context)));
context.subscriptions.push(commands.registerCommand(Commands.ShowBlameHistory, (...args) => {
return commands.executeCommand(VsCodeCommands.ShowReferences, ...args);
}));
let selector: DocumentSelector = { scheme: 'file' };
context.subscriptions.push(languages.registerCodeLensProvider(selector, new GitCodeLensProvider(repoPath)));
}).catch(reason => console.warn(reason));

+ 59
- 16
src/git.ts Просмотреть файл

@ -1,13 +1,17 @@
'use strict';
import {spawn} from 'child_process';
import {dirname} from 'path';
import {basename, dirname, extname} from 'path';
import * as fs from 'fs';
import * as tmp from 'tmp';
export declare interface IBlameLine {
line: number;
export declare interface IGitBlameLine {
sha: string;
file: string;
originalLine: number;
author: string;
date: Date;
sha: string;
//code: string;
line: number;
code: string;
}
export function gitRepoPath(cwd) {
@ -22,33 +26,72 @@ export function gitRepoPath(cwd) {
});
}
const blameMatcher = /^(.*)\t\((.*)\t(.*)\t(.*?)\)(.*)$/gm;
//const blameMatcher = /^(.*)\t\((.*)\t(.*)\t(.*?)\)(.*)$/gm;
const blameMatcher = /^([0-9a-fA-F]{8})\s([\S]*)\s([0-9\S]+)\s\((.*?)\s([0-9]{4}-[0-9]{2}-[0-9]{2}\s[0-9]{2}:[0-9]{2}:[0-9]{2}\s[-|+][0-9]{4})\s([0-9]+)\)(.*)$/gm;
export function gitBlame(fileName: string) {
export function gitBlame(fileName: string): Promise<IGitBlameLine[]> {
const mapper = (input, output) => {
let blame = input.toString();
console.log(fileName, 'Blame:', blame);
let m: Array<string>;
while ((m = blameMatcher.exec(input.toString())) != null) {
while ((m = blameMatcher.exec(blame)) != null) {
output.push({
line: parseInt(m[4], 10),
author: m[2],
date: new Date(m[3]),
sha: m[1]
//code: m[5]
sha: m[1],
file: m[2].trim(),
originalLine: parseInt(m[3], 10),
author: m[4].trim(),
date: new Date(m[5]),
line: parseInt(m[6], 10),
code: m[7]
});
}
};
return gitCommand(dirname(fileName), mapper, 'blame', '-c', '-M', '-w', '--', fileName) as Promise<IBlameLine[]>;
return gitCommand(dirname(fileName), mapper, 'blame', '-fnw', '--', fileName);
}
export function gitGetVersionFile(repoPath: string, sha: string, source: string): Promise<any> {
const mapper = (input, output) => output.push(input);
return new Promise<string>((resolve, reject) => {
(gitCommand(repoPath, mapper, 'show', `${sha}:${source.replace(/\\/g, '/')}`) as Promise<Array<Buffer>>).then(o => {
let ext = extname(source);
tmp.file({ prefix: `${basename(source, ext)}-${sha}_`, postfix: ext }, (err, destination, fd, cleanupCallback) => {
if (err) {
reject(err);
return;
}
console.log("File: ", destination);
console.log("Filedescriptor: ", fd);
fs.appendFile(destination, o.join(), err => {
if (err) {
reject(err);
return;
}
resolve(destination);
});
});
});
});
}
export function gitGetVersionText(repoPath: string, sha: string, source: string): Promise<string> {
const mapper = (input, output) => output.push(input.toString());
return new Promise<string>((resolve, reject) => (gitCommand(repoPath, mapper, 'show', `${sha}:${source.replace(/\\/g, '/')}`) as Promise<Array<string>>).then(o => resolve(o.join())));
}
function gitCommand(cwd: string, map: (input: Buffer, output: Array<any>) => void, ...args): Promise<any> {
function gitCommand(cwd: string, mapper: (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);
mapper(data, output);
});
let errors: Array<string> = [];

+ 5
- 0
typings.json Просмотреть файл

@ -0,0 +1,5 @@
{
"globalDependencies": {
"tmp": "registry:dt/tmp#0.0.0+20160514170650"
}
}

+ 45
- 0
typings/globals/tmp/index.d.ts Просмотреть файл

@ -0,0 +1,45 @@
// Generated by typings
// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/5d6115f046550714a28caa3555f47a1aec114fe5/tmp/tmp.d.ts
declare module "tmp" {
namespace tmp {
interface Options extends SimpleOptions {
mode?: number;
}
interface SimpleOptions {
prefix?: string;
postfix?: string;
template?: string;
dir?: string;
tries?: number;
keep?: boolean;
unsafeCleanup?: boolean;
}
interface SynchrounousResult {
name: string;
fd: number;
removeCallback: () => void;
}
function file(callback: (err: any, path: string, fd: number, cleanupCallback: () => void) => void): void;
function file(config: Options, callback?: (err: any, path: string, fd: number, cleanupCallback: () => void) => void): void;
function fileSync(config?: Options): SynchrounousResult;
function dir(callback: (err: any, path: string, cleanupCallback: () => void) => void): void;
function dir(config: Options, callback?: (err: any, path: string, cleanupCallback: () => void) => void): void;
function dirSync(config?: Options): SynchrounousResult;
function tmpName(callback: (err: any, path: string) => void): void;
function tmpName(config: SimpleOptions, callback?: (err: any, path: string) => void): void;
function tmpNameSync(config?: SimpleOptions): string;
function setGracefulCleanup(): void;
}
export = tmp;
}

+ 8
- 0
typings/globals/tmp/typings.json Просмотреть файл

@ -0,0 +1,8 @@
{
"resolution": "main",
"tree": {
"src": "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/5d6115f046550714a28caa3555f47a1aec114fe5/tmp/tmp.d.ts",
"raw": "registry:dt/tmp#0.0.0+20160514170650",
"typings": "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/5d6115f046550714a28caa3555f47a1aec114fe5/tmp/tmp.d.ts"
}
}

+ 1
- 0
typings/index.d.ts Просмотреть файл

@ -0,0 +1 @@
/// <reference path="globals/tmp/index.d.ts" />

Загрузка…
Отмена
Сохранить