Renamed to GitLens

Reworked Uri scheme to drastically reduce encoded data (big perf improvement)
This commit is contained in:
Eric Amodio
2016-08-31 03:34:16 -04:00
parent 06b350bc82
commit c395a583b7
14 changed files with 18808 additions and 173 deletions

View File

@@ -1,4 +1,4 @@
# Git CodeLens # GitLens
Provides Git blame (and history eventually) CodeLens for many supported Visual Studio Code languages (in theory -- the language must support symbol searching). Provides Git blame (and history eventually) CodeLens for many supported Visual Studio Code languages (in theory -- the language must support symbol searching).

View File

@@ -1,5 +1,5 @@
{ {
"name": "git-codelens", "name": "gitlens",
"version": "0.0.1", "version": "0.0.1",
"author": "Eric Amodio", "author": "Eric Amodio",
"publisher": "eamodio", "publisher": "eamodio",
@@ -7,13 +7,13 @@
"vscode": "^1.3.0" "vscode": "^1.3.0"
}, },
"license": "SEE LICENSE IN LICENSE", "license": "SEE LICENSE IN LICENSE",
"displayName": "Git CodeLens", "displayName": "GitLens",
"description": "Provides Git blame information in CodeLens", "description": "Provides Git blame information in CodeLens",
"categories": [ "categories": [
"Other" "Other"
], ],
"keywords": [ "keywords": [
"git", "gitblame", "blame" "git", "gitblame", "blame", "codelens"
], ],
"galleryBanner": { "galleryBanner": {
"color": "#0000FF", "color": "#0000FF",
@@ -23,7 +23,7 @@
"main": "./out/src/extension", "main": "./out/src/extension",
"contributes": { "contributes": {
"commands": [{ "commands": [{
"command": "git.codelen.showBlameHistory", "command": "git.action.showBlameHistory",
"title": "Show Blame History", "title": "Show Blame History",
"category": "Git" "category": "Git"
}] }]

View File

@@ -1,21 +1,26 @@
'use strict'; 'use strict';
import {CancellationToken, CodeLens, CodeLensProvider, commands, Location, Position, Range, SymbolInformation, SymbolKind, TextDocument, Uri} from 'vscode'; import {CancellationToken, CodeLens, CodeLensProvider, commands, ExtensionContext, Location, Position, Range, SymbolInformation, SymbolKind, TextDocument, Uri} from 'vscode';
import {Commands, VsCodeCommands} from './constants'; import {Commands, VsCodeCommands, WorkspaceState} from './constants';
import {IGitBlameLine, gitBlame} from './git'; import GitBlameProvider, {IGitBlame, IGitBlameCommit} from './gitBlameProvider';
import {toGitBlameUri} from './gitBlameUri';
import * as moment from 'moment'; import * as moment from 'moment';
export class GitBlameCodeLens extends CodeLens { export class GitBlameCodeLens extends CodeLens {
constructor(private blame: Promise<IGitBlameLine[]>, public repoPath: string, public fileName: string, private blameRange: Range, range: Range) { private _locations: Location[] = [];
constructor(private blameProvider: GitBlameProvider, public fileName: string, private blameRange: Range, range: Range) {
super(range); super(range);
} }
getBlameLines(): Promise<IGitBlameLine[]> { get locations() {
return this.blame.then(allLines => allLines.slice(this.blameRange.start.line, this.blameRange.end.line + 1)); return this._locations;
} }
static toUri(lens: GitBlameCodeLens, index: number, line: IGitBlameLine, lines: IGitBlameLine[], commits: string[]): Uri { getBlame(): Promise<IGitBlame> {
return toGitBlameUri(Object.assign({ repoPath: lens.repoPath, index: index, range: lens.blameRange, lines: lines, commits: commits }, line)); return this.blameProvider.getBlameForRange(this.fileName, this.blameRange);
}
static toUri(lens: GitBlameCodeLens, repoPath: string, commit: IGitBlameCommit, index: number, commitCount: number): Uri {
return GitBlameProvider.toBlameUri(repoPath, commit, lens.blameRange, index, commitCount);
} }
} }
@@ -25,32 +30,35 @@ export class GitHistoryCodeLens extends CodeLens {
} }
// static toUri(lens: GitHistoryCodeLens, index: number): Uri { // static toUri(lens: GitHistoryCodeLens, index: number): Uri {
// return toGitBlameUri(Object.assign({ repoPath: lens.repoPath, index: index, range: lens.blameRange, lines: lines }, line)); // return GitBlameProvider.toBlameUri(Object.assign({ repoPath: lens.repoPath, index: index, range: lens.blameRange, lines: lines }, line));
// } // }
} }
export default class GitCodeLensProvider implements CodeLensProvider { export default class GitCodeLensProvider implements CodeLensProvider {
constructor(public repoPath: string) { } public repoPath: string;
constructor(context: ExtensionContext, public blameProvider: GitBlameProvider) {
this.repoPath = context.workspaceState.get(WorkspaceState.RepoPath) as string;
}
provideCodeLenses(document: TextDocument, token: CancellationToken): CodeLens[] | Thenable<CodeLens[]> { provideCodeLenses(document: TextDocument, token: CancellationToken): CodeLens[] | Thenable<CodeLens[]> {
// TODO: Should I wait here? this.blameProvider.blameFile(document.fileName);
const blame = gitBlame(document.fileName);
return (commands.executeCommand(VsCodeCommands.ExecuteDocumentSymbolProvider, document.uri) as Promise<SymbolInformation[]>).then(symbols => { return (commands.executeCommand(VsCodeCommands.ExecuteDocumentSymbolProvider, document.uri) as Promise<SymbolInformation[]>).then(symbols => {
let lenses: CodeLens[] = []; let lenses: CodeLens[] = [];
symbols.forEach(sym => this._provideCodeLens(document, sym, blame, lenses)); symbols.forEach(sym => this._provideCodeLens(document, sym, lenses));
// Check if we have a lens for the whole document -- if not add one // Check if we have a lens for the whole document -- if not add one
if (!lenses.find(l => l.range.start.line === 0 && l.range.end.line === 0)) { if (!lenses.find(l => l.range.start.line === 0 && l.range.end.line === 0)) {
const docRange = document.validateRange(new Range(0, 1000000, 1000000, 1000000)); const docRange = document.validateRange(new Range(0, 1000000, 1000000, 1000000));
lenses.push(new GitBlameCodeLens(blame, this.repoPath, document.fileName, docRange, new Range(0, 0, 0, docRange.start.character))); lenses.push(new GitBlameCodeLens(this.blameProvider, document.fileName, docRange, new Range(0, 0, 0, docRange.start.character)));
lenses.push(new GitHistoryCodeLens(this.repoPath, document.fileName, docRange.with(new Position(docRange.start.line, docRange.start.character + 1)))); lenses.push(new GitHistoryCodeLens(this.repoPath, document.fileName, docRange.with(new Position(docRange.start.line, docRange.start.character + 1))));
} }
return lenses; return lenses;
}); });
} }
private _provideCodeLens(document: TextDocument, symbol: SymbolInformation, blame: Promise<IGitBlameLine[]>, lenses: CodeLens[]): void { private _provideCodeLens(document: TextDocument, symbol: SymbolInformation, lenses: CodeLens[]): void {
switch (symbol.kind) { switch (symbol.kind) {
case SymbolKind.Package: case SymbolKind.Package:
case SymbolKind.Module: case SymbolKind.Module:
@@ -68,7 +76,7 @@ export default class GitCodeLensProvider implements CodeLensProvider {
} }
const line = document.lineAt(symbol.location.range.start); const line = document.lineAt(symbol.location.range.start);
lenses.push(new GitBlameCodeLens(blame, this.repoPath, document.fileName, symbol.location.range, line.range.with(new Position(line.range.start.line, line.firstNonWhitespaceCharacterIndex)))); lenses.push(new GitBlameCodeLens(this.blameProvider, document.fileName, symbol.location.range, line.range.with(new Position(line.range.start.line, line.firstNonWhitespaceCharacterIndex))));
lenses.push(new GitHistoryCodeLens(this.repoPath, document.fileName, line.range.with(new Position(line.range.start.line, line.firstNonWhitespaceCharacterIndex + 1)))); lenses.push(new GitHistoryCodeLens(this.repoPath, document.fileName, line.range.with(new Position(line.range.start.line, line.firstNonWhitespaceCharacterIndex + 1))));
} }
@@ -79,45 +87,34 @@ export default class GitCodeLensProvider implements CodeLensProvider {
_resolveGitBlameCodeLens(lens: GitBlameCodeLens, token: CancellationToken): Thenable<CodeLens> { _resolveGitBlameCodeLens(lens: GitBlameCodeLens, token: CancellationToken): Thenable<CodeLens> {
return new Promise<CodeLens>((resolve, reject) => { return new Promise<CodeLens>((resolve, reject) => {
lens.getBlameLines().then(lines => { lens.getBlame().then(blame => {
if (!lines.length) { if (!blame.lines.length) {
console.error('No blame lines found', lens); console.error('No blame lines found', lens);
reject(null); reject(null);
return; return;
} }
let recentLine = lines[0]; // TODO: Rework this to only get the locations in the ShowBlameHistory command, rather than here -- should save a lot of processing
const commitCount = blame.commits.size;
let locations: Location[] = []; let recentCommit;
if (lines.length > 1) { Array.from(blame.commits.values())
let sorted = lines.sort((a, b) => b.date.getTime() - a.date.getTime()); .sort((a, b) => b.date.getTime() - a.date.getTime())
recentLine = sorted[0]; .forEach((c, i) => {
if (i === 0) {
// console.log(lens.fileName, 'Blame lines:', sorted); recentCommit = c;
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]);
} }
});
const commits = Array.from(map.keys()); const uri = GitBlameCodeLens.toUri(lens, this.repoPath, c, i + 1, commitCount);
Array.from(map.values()).forEach((lines, i) => { blame.lines
const uri = GitBlameCodeLens.toUri(lens, i + 1, lines[0], lines, commits); .filter(l => l.sha === c.sha)
lines.forEach(l => locations.push(new Location(uri, new Position(l.originalLine, 0)))); .forEach(l => lens.locations.push(new Location(uri, new Position(l.originalLine, 0))));
}); });
} else {
locations = [new Location(GitBlameCodeLens.toUri(lens, 1, recentLine, lines, [recentLine.sha]), lens.range.start)];
}
lens.command = { lens.command = {
title: `${recentLine.author}, ${moment(recentLine.date).fromNow()}`, title: `${recentCommit.author}, ${moment(recentCommit.date).fromNow()}`,
command: Commands.ShowBlameHistory, command: Commands.ShowBlameHistory,
arguments: [Uri.file(lens.fileName), lens.range.start, locations] arguments: [Uri.file(lens.fileName), lens.range.start, lens.locations]
}; };
resolve(lens); resolve(lens);
}); });

View File

@@ -1,3 +1,10 @@
export type WorkspaceState = 'repoPath';
export const WorkspaceState = {
RepoPath: 'repoPath' as WorkspaceState
}
export const RepoPath: string = 'repoPath';
export type Commands = 'git.action.showBlameHistory'; export type Commands = 'git.action.showBlameHistory';
export const Commands = { export const Commands = {
ShowBlameHistory: 'git.action.showBlameHistory' as Commands ShowBlameHistory: 'git.action.showBlameHistory' as Commands
@@ -8,8 +15,9 @@ export const DocumentSchemes = {
GitBlame: 'gitblame' as DocumentSchemes GitBlame: 'gitblame' as DocumentSchemes
} }
export type VsCodeCommands = 'vscode.executeDocumentSymbolProvider' | 'editor.action.showReferences'; export type VsCodeCommands = 'vscode.executeDocumentSymbolProvider' | 'vscode.executeCodeLensProvider' | 'editor.action.showReferences';
export const VsCodeCommands = { export const VsCodeCommands = {
ExecuteDocumentSymbolProvider: 'vscode.executeDocumentSymbolProvider' as VsCodeCommands, ExecuteDocumentSymbolProvider: 'vscode.executeDocumentSymbolProvider' as VsCodeCommands,
ExecuteCodeLensProvider: 'vscode.executeCodeLensProvider' as VsCodeCommands,
ShowReferences: 'editor.action.showReferences' as VsCodeCommands ShowReferences: 'editor.action.showReferences' as VsCodeCommands
} }

View File

@@ -1,19 +1,21 @@
'use strict'; 'use strict';
import {Disposable, EventEmitter, ExtensionContext, OverviewRulerLane, Range, TextEditor, TextEditorDecorationType, TextDocumentContentProvider, Uri, window, workspace} from 'vscode'; import {Disposable, EventEmitter, ExtensionContext, OverviewRulerLane, Range, TextEditor, TextEditorDecorationType, TextDocumentContentProvider, Uri, window, workspace} from 'vscode';
import {DocumentSchemes} from './constants'; import {DocumentSchemes, WorkspaceState} from './constants';
import {gitGetVersionText} from './git'; import {gitGetVersionText} from './git';
import {fromGitBlameUri, IGitBlameUriData} from './gitBlameUri'; import GitBlameProvider, {IGitBlameUriData} from './gitBlameProvider';
import * as moment from 'moment'; import * as moment from 'moment';
export default class GitBlameContentProvider implements TextDocumentContentProvider { export default class GitBlameContentProvider implements TextDocumentContentProvider {
static scheme = DocumentSchemes.GitBlame; static scheme = DocumentSchemes.GitBlame;
public repoPath: string;
private _blameDecoration: TextEditorDecorationType; private _blameDecoration: TextEditorDecorationType;
private _onDidChange = new EventEmitter<Uri>(); private _onDidChange = new EventEmitter<Uri>();
// private _subscriptions: Disposable; //private _subscriptions: Disposable;
// private _dataMap: Map<string, IGitBlameUriData>;
constructor(context: ExtensionContext, public blameProvider: GitBlameProvider) {
this.repoPath = context.workspaceState.get(WorkspaceState.RepoPath) as string;
constructor(context: ExtensionContext) {
this._blameDecoration = window.createTextEditorDecorationType({ this._blameDecoration = window.createTextEditorDecorationType({
dark: { dark: {
backgroundColor: 'rgba(255, 255, 255, 0.15)', backgroundColor: 'rgba(255, 255, 255, 0.15)',
@@ -30,25 +32,14 @@ export default class GitBlameContentProvider implements TextDocumentContentProvi
isWholeLine: true isWholeLine: true
}); });
// this._dataMap = new Map(); //this._subscriptions = Disposable.from(
// this._subscriptions = Disposable.from(
// window.onDidChangeActiveTextEditor(e => e ? console.log(e.document.uri) : console.log('active missing')), // window.onDidChangeActiveTextEditor(e => e ? console.log(e.document.uri) : console.log('active missing')),
// workspace.onDidOpenTextDocument(d => { //);
// let data = this._dataMap.get(d.uri.toString());
// if (!data) return;
// // TODO: This only works on the first load -- not after since it is cached
// this._tryAddBlameDecorations(d.uri, data);
// }),
// workspace.onDidCloseTextDocument(d => {
// this._dataMap.delete(d.uri.toString());
// })
// );
} }
dispose() { dispose() {
this._onDidChange.dispose(); this._onDidChange.dispose();
// this._subscriptions && this._subscriptions.dispose(); //this._subscriptions && this._subscriptions.dispose();
} }
get onDidChange() { get onDidChange() {
@@ -60,12 +51,11 @@ export default class GitBlameContentProvider implements TextDocumentContentProvi
} }
provideTextDocumentContent(uri: Uri): string | Thenable<string> { provideTextDocumentContent(uri: Uri): string | Thenable<string> {
const data = fromGitBlameUri(uri); const data = GitBlameProvider.fromBlameUri(uri);
// this._dataMap.set(uri.toString(), data);
//const editor = this._findEditor(Uri.file(join(data.repoPath, data.file))); //const editor = this._findEditor(Uri.file(join(data.repoPath, data.file)));
return gitGetVersionText(data.repoPath, data.sha, data.file).then(text => { return gitGetVersionText(data.fileName, this.repoPath, data.sha).then(text => {
this.update(uri); this.update(uri);
// TODO: This only works on the first load -- not after since it is cached // TODO: This only works on the first load -- not after since it is cached
@@ -77,7 +67,7 @@ export default class GitBlameContentProvider implements TextDocumentContentProvi
return text; return text;
}); });
// return gitGetVersionFile(data.repoPath, data.sha, data.file).then(dst => { // return gitGetVersionFile(data.file, this.repoPath, data.sha).then(dst => {
// let uri = Uri.parse(`file:${dst}`) // let uri = Uri.parse(`file:${dst}`)
// return workspace.openTextDocument(uri).then(doc => { // return workspace.openTextDocument(uri).then(doc => {
// this.update(uri); // this.update(uri);
@@ -102,12 +92,16 @@ export default class GitBlameContentProvider implements TextDocumentContentProvi
let editor = this._findEditor(uri); let editor = this._findEditor(uri);
if (editor) { if (editor) {
clearInterval(handle); clearInterval(handle);
editor.setDecorations(this._blameDecoration, data.lines.map(l => { this.blameProvider.getBlameForShaRange(data.fileName, data.sha, data.range).then(blame => {
return { if (blame.lines.length) {
range: editor.document.validateRange(new Range(l.originalLine, 0, l.originalLine, 1000000)), editor.setDecorations(this._blameDecoration, blame.lines.map(l => {
hoverMessage: `${moment(l.date).format('MMMM Do, YYYY hh:MMa')}\n${l.author}\n${l.sha}` return {
}; range: editor.document.validateRange(new Range(l.originalLine, 0, l.originalLine, 1000000)),
})); hoverMessage: `${moment(blame.commit.date).format('MMMM Do, YYYY hh:MMa')}\n${blame.commit.author}\n${l.sha}`
};
}));
}
});
} }
}, 200); }, 200);
} }

View File

@@ -1,21 +0,0 @@
// '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;
// });
// }
// }

View File

@@ -1,30 +1,47 @@
'use strict'; 'use strict';
import {commands, DocumentSelector, ExtensionContext, languages, workspace} from 'vscode'; import {CodeLens, commands, DocumentSelector, ExtensionContext, languages, Uri, window, workspace} from 'vscode';
import GitCodeLensProvider from './codeLensProvider'; import GitCodeLensProvider, {GitBlameCodeLens} from './codeLensProvider';
import GitContentProvider from './contentProvider'; import GitContentProvider from './contentProvider';
import {gitRepoPath} from './git'; import {gitRepoPath} from './git';
import {Commands, VsCodeCommands} from './constants'; import GitBlameProvider from './gitBlameProvider';
import {Commands, VsCodeCommands, WorkspaceState} from './constants';
// this method is called when your extension is activated // this method is called when your extension is activated
export function activate(context: ExtensionContext) { export function activate(context: ExtensionContext) {
// Workspace not using a folder. No access to git repo. // Workspace not using a folder. No access to git repo.
if (!workspace.rootPath) { if (!workspace.rootPath) {
console.warn('Git CodeLens inactive: no rootPath'); console.warn('GitLens inactive: no rootPath');
return; return;
} }
console.log(`Git CodeLens active: ${workspace.rootPath}`); console.log(`GitLens active: ${workspace.rootPath}`);
gitRepoPath(workspace.rootPath).then(repoPath => { gitRepoPath(workspace.rootPath).then(repoPath => {
context.subscriptions.push(workspace.registerTextDocumentContentProvider(GitContentProvider.scheme, new GitContentProvider(context))); context.workspaceState.update(WorkspaceState.RepoPath, repoPath);
const blameProvider = new GitBlameProvider();
context.subscriptions.push(blameProvider);
context.subscriptions.push(workspace.registerTextDocumentContentProvider(GitContentProvider.scheme, new GitContentProvider(context, blameProvider)));
context.subscriptions.push(commands.registerCommand(Commands.ShowBlameHistory, (...args) => { context.subscriptions.push(commands.registerCommand(Commands.ShowBlameHistory, (...args) => {
return commands.executeCommand(VsCodeCommands.ShowReferences, ...args); if (args && args.length) {
return commands.executeCommand(VsCodeCommands.ShowReferences, ...args);
}
// const uri = window.activeTextEditor && window.activeTextEditor.document && window.activeTextEditor.document.uri;
// if (uri) {
// return (commands.executeCommand(VsCodeCommands.ExecuteCodeLensProvider, uri) as Promise<CodeLens[]>).then(lenses => {
// const lens = <GitBlameCodeLens>lenses.find(l => l instanceof GitBlameCodeLens);
// if (lens) {
// return commands.executeCommand(Commands.ShowBlameHistory, Uri.file(lens.fileName), lens.range.start, lens.locations);
// }
// });
// }
})); }));
const selector: DocumentSelector = { scheme: 'file' }; const selector: DocumentSelector = { scheme: 'file' };
context.subscriptions.push(languages.registerCodeLensProvider(selector, new GitCodeLensProvider(repoPath))); context.subscriptions.push(languages.registerCodeLensProvider(selector, new GitCodeLensProvider(context, blameProvider)));
}).catch(reason => console.warn(reason)); }).catch(reason => console.warn(reason));
} }

View File

@@ -1,50 +1,23 @@
'use strict'; 'use strict';
import {basename, dirname, extname} from 'path'; import {basename, dirname, extname, relative} from 'path';
import * as fs from 'fs'; import * as fs from 'fs';
import * as tmp from 'tmp'; import * as tmp from 'tmp';
import {spawnPromise} from 'spawn-rx'; import {spawnPromise} from 'spawn-rx';
export declare interface IGitBlameLine {
sha: string;
file: string;
originalLine: number;
author: string;
date: Date;
line: number;
//code: string;
}
export function gitRepoPath(cwd) { export function gitRepoPath(cwd) {
return gitCommand(cwd, 'rev-parse', '--show-toplevel').then(data => data.replace(/\r?\n|\r/g, '')); return gitCommand(cwd, 'rev-parse', '--show-toplevel').then(data => data.replace(/\r?\n|\r/g, ''));
} }
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) {
console.log('git', 'blame', '-fnw', '--root', '--', fileName); console.log('git', 'blame', '-fnw', '--root', '--', fileName);
return gitCommand(dirname(fileName), 'blame', '-fnw', '--root', '--', fileName).then(data => { return gitCommand(dirname(fileName), 'blame', '-fnw', '--root', '--', fileName);
let lines: Array<IGitBlameLine> = [];
let m: Array<string>;
while ((m = blameMatcher.exec(data)) != null) {
lines.push({
sha: m[1],
file: m[2].trim(),
originalLine: parseInt(m[3], 10) - 1,
author: m[4].trim(),
date: new Date(m[5]),
line: parseInt(m[6], 10) - 1
//code: m[7]
});
}
return lines;
});
} }
export function gitGetVersionFile(repoPath: string, sha: string, source: string): Promise<string> { export function gitGetVersionFile(fileName: string, repoPath: string, sha: string) {
return new Promise<string>((resolve, reject) => { return new Promise<string>((resolve, reject) => {
gitCommand(repoPath, 'show', `${sha.replace('^', '')}:${source.replace(/\\/g, '/')}`).then(data => { gitGetVersionText(fileName, repoPath, sha).then(data => {
let ext = extname(source); let ext = extname(fileName);
tmp.file({ prefix: `${basename(source, ext)}-${sha}_`, postfix: ext }, (err, destination, fd, cleanupCallback) => { tmp.file({ prefix: `${basename(fileName, ext)}-${sha}_`, postfix: ext }, (err, destination, fd, cleanupCallback) => {
if (err) { if (err) {
reject(err); reject(err);
return; return;
@@ -65,9 +38,14 @@ export function gitGetVersionFile(repoPath: string, sha: string, source: string)
}); });
} }
export function gitGetVersionText(repoPath: string, sha: string, source: string) { export function gitGetVersionText(fileName: string, repoPath: string, sha: string) {
console.log('git', 'show', `${sha}:${source.replace(/\\/g, '/')}`); const gitArg = normalizeArgument(fileName, repoPath, sha);
return gitCommand(repoPath, 'show', `${sha}:${source.replace(/\\/g, '/')}`); console.log('git', 'show', gitArg);
return gitCommand(dirname(fileName), 'show', gitArg);
}
function normalizeArgument(fileName: string, repoPath: string, sha: string) {
return `${sha.replace('^', '')}:${relative(repoPath, fileName.replace(/\\/g, '/'))}`;
} }
function gitCommand(cwd: string, ...args) { function gitCommand(cwd: string, ...args) {

130
src/gitBlameProvider.ts Normal file
View File

@@ -0,0 +1,130 @@
import {Disposable, Range, Uri, workspace} from 'vscode';
import {DocumentSchemes} from './constants';
import {gitBlame} from './git';
import {basename, dirname, extname, join} from 'path';
import * as moment from 'moment';
import * as _ from 'lodash';
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 default class GitBlameProvider extends Disposable {
private _files: Map<string, Promise<IGitBlame>>;
private _subscriptions: Disposable;
constructor() {
super(() => this.dispose());
this._files = new Map();
this._subscriptions = Disposable.from(workspace.onDidCloseTextDocument(d => this._removeFile(d.fileName)),
workspace.onDidChangeTextDocument(e => this._removeFile(e.document.fileName)));
}
dispose() {
this._files.clear();
this._subscriptions && this._subscriptions.dispose();
super.dispose();
}
blameFile(fileName: string) {
let blame = this._files.get(fileName);
if (blame !== undefined) return blame;
blame = gitBlame(fileName)
.then(data => {
const commits: Map<string, IGitBlameCommit> = new Map();
const lines: Array<IGitBlameLine> = [];
let m: Array<string>;
while ((m = blameMatcher.exec(data)) != null) {
let sha = m[1];
if (!commits.has(sha)) {
commits.set(sha, {
sha,
fileName: m[2].trim(),
author: m[4].trim(),
date: new Date(m[5])
});
}
lines.push({
sha,
originalLine: parseInt(m[3], 10) - 1,
line: parseInt(m[6], 10) - 1
//code: m[7]
});
}
return { commits, lines };
});
// .catch(ex => {
// console.error(ex);
// });
this._files.set(fileName, blame);
return blame;
}
getBlameForRange(fileName: string, range: Range): Promise<IGitBlame> {
return this.blameFile(fileName).then(blame => {
if (!blame.lines.length) return blame;
const lines = blame.lines.slice(range.start.line, range.end.line + 1);
const commits = new Map();
_.uniqBy(lines, 'sha').forEach(l => commits.set(l.sha, blame.commits.get(l.sha)));
return { commits, lines };
});
}
getBlameForShaRange(fileName: string, sha: string, range: Range): Promise<{commit: IGitBlameCommit, lines: IGitBlameLine[]}> {
return this.blameFile(fileName).then(blame => {
return {
commit: blame.commits.get(sha),
lines: blame.lines.slice(range.start.line, range.end.line + 1).filter(l => l.sha === sha)
};
});
}
private _removeFile(fileName: string) {
this._files.delete(fileName);
}
static toBlameUri(repoPath: string, commit: IGitBlameCommit, range: Range, index: number, commitCount: number) {
const pad = n => ("0000000" + n).slice(-("" + commitCount).length);
const ext = extname(commit.fileName);
const path = `${dirname(commit.fileName)}/${commit.sha}: ${basename(commit.fileName, ext)}${ext}`;
const data: IGitBlameUriData = { fileName: join(repoPath, commit.fileName), sha: commit.sha, range: range, index: index };
// NOTE: Need to specify an index here, since I can't control the sort order -- just alphabetic or by file location
return Uri.parse(`${DocumentSchemes.GitBlame}:${pad(index)}. ${commit.author}, ${moment(commit.date).format('MMM D, YYYY hh:MMa')} - ${path}?${JSON.stringify(data)}`);
}
static fromBlameUri(uri: Uri): IGitBlameUriData {
const 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;
}
}
export interface IGitBlame {
commits: Map<string, IGitBlameCommit>;
lines: IGitBlameLine[];
}
export interface IGitBlameCommit {
sha: string;
fileName: string;
author: string;
date: Date;
}
export interface IGitBlameLine {
sha: string;
originalLine: number;
line: number;
code?: string;
}
export interface IGitBlameUriData {
fileName: string,
sha: string,
range: Range,
index: number
}

View File

@@ -1,28 +0,0 @@
import {Range, Uri} from 'vscode';
import {DocumentSchemes} from './constants';
import {IGitBlameLine} from './git';
import {basename, dirname, extname} from 'path';
import * as moment from 'moment';
export interface IGitBlameUriData extends IGitBlameLine {
repoPath: string,
range: Range,
index: number,
lines: IGitBlameLine[],
commits: string[]
}
export function toGitBlameUri(data: IGitBlameUriData) {
const pad = n => ("0000000" + n).slice(-("" + data.commits.length).length);
let ext = extname(data.file);
let path = `${dirname(data.file)}/${data.sha}: ${basename(data.file, ext)}${ext}`;
// TODO: Need to specify an index here, since I can't control the sort order -- just alphabetic or by file location
return Uri.parse(`${DocumentSchemes.GitBlame}:${pad(data.index)}. ${data.author}, ${moment(data.date).format('MMM D, YYYY hh:MMa')} - ${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;
}

View File

@@ -1,5 +1,8 @@
{ {
"globalDependencies": { "globalDependencies": {
"tmp": "registry:dt/tmp#0.0.0+20160514170650" "tmp": "registry:dt/tmp#0.0.0+20160514170650"
},
"dependencies": {
"lodash": "registry:npm/lodash#4.0.0+20160723033700"
} }
} }

1
typings/index.d.ts vendored
View File

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

18545
typings/modules/lodash/index.d.ts vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,11 @@
{
"resolution": "main",
"tree": {
"src": "https://raw.githubusercontent.com/types/npm-lodash/9b83559bbd3454f0cd9e4020c920e36eee80d5a3/typings.json",
"raw": "registry:npm/lodash#4.0.0+20160723033700",
"main": "index.d.ts",
"version": "4.0.0",
"name": "lodash",
"type": "typings"
}
}