mirror of
https://github.com/ckaczor/vscode-gitlens.git
synced 2026-01-14 01:25:43 -05:00
Renamed to GitLens
Reworked Uri scheme to drastically reduce encoded data (big perf improvement)
This commit is contained in:
@@ -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).
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"name": "git-codelens",
|
||||
"name": "gitlens",
|
||||
"version": "0.0.1",
|
||||
"author": "Eric Amodio",
|
||||
"publisher": "eamodio",
|
||||
@@ -7,13 +7,13 @@
|
||||
"vscode": "^1.3.0"
|
||||
},
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"displayName": "Git CodeLens",
|
||||
"displayName": "GitLens",
|
||||
"description": "Provides Git blame information in CodeLens",
|
||||
"categories": [
|
||||
"Other"
|
||||
],
|
||||
"keywords": [
|
||||
"git", "gitblame", "blame"
|
||||
"git", "gitblame", "blame", "codelens"
|
||||
],
|
||||
"galleryBanner": {
|
||||
"color": "#0000FF",
|
||||
@@ -23,7 +23,7 @@
|
||||
"main": "./out/src/extension",
|
||||
"contributes": {
|
||||
"commands": [{
|
||||
"command": "git.codelen.showBlameHistory",
|
||||
"command": "git.action.showBlameHistory",
|
||||
"title": "Show Blame History",
|
||||
"category": "Git"
|
||||
}]
|
||||
|
||||
@@ -1,21 +1,26 @@
|
||||
'use strict';
|
||||
import {CancellationToken, CodeLens, CodeLensProvider, commands, Location, Position, Range, SymbolInformation, SymbolKind, TextDocument, Uri} from 'vscode';
|
||||
import {Commands, VsCodeCommands} from './constants';
|
||||
import {IGitBlameLine, gitBlame} from './git';
|
||||
import {toGitBlameUri} from './gitBlameUri';
|
||||
import {CancellationToken, CodeLens, CodeLensProvider, commands, ExtensionContext, Location, Position, Range, SymbolInformation, SymbolKind, TextDocument, Uri} from 'vscode';
|
||||
import {Commands, VsCodeCommands, WorkspaceState} from './constants';
|
||||
import GitBlameProvider, {IGitBlame, IGitBlameCommit} from './gitBlameProvider';
|
||||
import * as moment from 'moment';
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
getBlameLines(): Promise<IGitBlameLine[]> {
|
||||
return this.blame.then(allLines => allLines.slice(this.blameRange.start.line, this.blameRange.end.line + 1));
|
||||
get locations() {
|
||||
return this._locations;
|
||||
}
|
||||
|
||||
static toUri(lens: GitBlameCodeLens, index: number, line: IGitBlameLine, lines: IGitBlameLine[], commits: string[]): Uri {
|
||||
return toGitBlameUri(Object.assign({ repoPath: lens.repoPath, index: index, range: lens.blameRange, lines: lines, commits: commits }, line));
|
||||
getBlame(): Promise<IGitBlame> {
|
||||
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 {
|
||||
// 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 {
|
||||
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[]> {
|
||||
// TODO: Should I wait here?
|
||||
const blame = gitBlame(document.fileName);
|
||||
this.blameProvider.blameFile(document.fileName);
|
||||
|
||||
return (commands.executeCommand(VsCodeCommands.ExecuteDocumentSymbolProvider, document.uri) as Promise<SymbolInformation[]>).then(symbols => {
|
||||
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
|
||||
if (!lenses.find(l => l.range.start.line === 0 && l.range.end.line === 0)) {
|
||||
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))));
|
||||
}
|
||||
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) {
|
||||
case SymbolKind.Package:
|
||||
case SymbolKind.Module:
|
||||
@@ -68,7 +76,7 @@ export default class GitCodeLensProvider implements CodeLensProvider {
|
||||
}
|
||||
|
||||
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))));
|
||||
}
|
||||
|
||||
@@ -79,45 +87,34 @@ export default class GitCodeLensProvider implements CodeLensProvider {
|
||||
|
||||
_resolveGitBlameCodeLens(lens: GitBlameCodeLens, token: CancellationToken): Thenable<CodeLens> {
|
||||
return new Promise<CodeLens>((resolve, reject) => {
|
||||
lens.getBlameLines().then(lines => {
|
||||
if (!lines.length) {
|
||||
lens.getBlame().then(blame => {
|
||||
if (!blame.lines.length) {
|
||||
console.error('No blame lines found', lens);
|
||||
reject(null);
|
||||
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[] = [];
|
||||
if (lines.length > 1) {
|
||||
let sorted = lines.sort((a, b) => b.date.getTime() - a.date.getTime());
|
||||
recentLine = sorted[0];
|
||||
|
||||
// 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]);
|
||||
let recentCommit;
|
||||
Array.from(blame.commits.values())
|
||||
.sort((a, b) => b.date.getTime() - a.date.getTime())
|
||||
.forEach((c, i) => {
|
||||
if (i === 0) {
|
||||
recentCommit = c;
|
||||
}
|
||||
});
|
||||
|
||||
const commits = Array.from(map.keys());
|
||||
Array.from(map.values()).forEach((lines, i) => {
|
||||
const uri = GitBlameCodeLens.toUri(lens, i + 1, lines[0], lines, commits);
|
||||
lines.forEach(l => locations.push(new Location(uri, new Position(l.originalLine, 0))));
|
||||
const uri = GitBlameCodeLens.toUri(lens, this.repoPath, c, i + 1, commitCount);
|
||||
blame.lines
|
||||
.filter(l => l.sha === c.sha)
|
||||
.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 = {
|
||||
title: `${recentLine.author}, ${moment(recentLine.date).fromNow()}`,
|
||||
title: `${recentCommit.author}, ${moment(recentCommit.date).fromNow()}`,
|
||||
command: Commands.ShowBlameHistory,
|
||||
arguments: [Uri.file(lens.fileName), lens.range.start, locations]
|
||||
arguments: [Uri.file(lens.fileName), lens.range.start, lens.locations]
|
||||
};
|
||||
resolve(lens);
|
||||
});
|
||||
|
||||
@@ -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 const Commands = {
|
||||
ShowBlameHistory: 'git.action.showBlameHistory' as Commands
|
||||
@@ -8,8 +15,9 @@ export const 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 = {
|
||||
ExecuteDocumentSymbolProvider: 'vscode.executeDocumentSymbolProvider' as VsCodeCommands,
|
||||
ExecuteCodeLensProvider: 'vscode.executeCodeLensProvider' as VsCodeCommands,
|
||||
ShowReferences: 'editor.action.showReferences' as VsCodeCommands
|
||||
}
|
||||
@@ -1,19 +1,21 @@
|
||||
'use strict';
|
||||
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 {fromGitBlameUri, IGitBlameUriData} from './gitBlameUri';
|
||||
import GitBlameProvider, {IGitBlameUriData} from './gitBlameProvider';
|
||||
import * as moment from 'moment';
|
||||
|
||||
export default class GitBlameContentProvider implements TextDocumentContentProvider {
|
||||
static scheme = DocumentSchemes.GitBlame;
|
||||
|
||||
public repoPath: string;
|
||||
private _blameDecoration: TextEditorDecorationType;
|
||||
private _onDidChange = new EventEmitter<Uri>();
|
||||
// private _subscriptions: Disposable;
|
||||
// private _dataMap: Map<string, IGitBlameUriData>;
|
||||
//private _subscriptions: Disposable;
|
||||
|
||||
constructor(context: ExtensionContext, public blameProvider: GitBlameProvider) {
|
||||
this.repoPath = context.workspaceState.get(WorkspaceState.RepoPath) as string;
|
||||
|
||||
constructor(context: ExtensionContext) {
|
||||
this._blameDecoration = window.createTextEditorDecorationType({
|
||||
dark: {
|
||||
backgroundColor: 'rgba(255, 255, 255, 0.15)',
|
||||
@@ -30,25 +32,14 @@ export default class GitBlameContentProvider implements TextDocumentContentProvi
|
||||
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')),
|
||||
// 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() {
|
||||
this._onDidChange.dispose();
|
||||
// this._subscriptions && this._subscriptions.dispose();
|
||||
//this._subscriptions && this._subscriptions.dispose();
|
||||
}
|
||||
|
||||
get onDidChange() {
|
||||
@@ -60,12 +51,11 @@ export default class GitBlameContentProvider implements TextDocumentContentProvi
|
||||
}
|
||||
|
||||
provideTextDocumentContent(uri: Uri): string | Thenable<string> {
|
||||
const data = fromGitBlameUri(uri);
|
||||
// this._dataMap.set(uri.toString(), data);
|
||||
const data = GitBlameProvider.fromBlameUri(uri);
|
||||
|
||||
//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);
|
||||
|
||||
// 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 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}`)
|
||||
// return workspace.openTextDocument(uri).then(doc => {
|
||||
// this.update(uri);
|
||||
@@ -102,12 +92,16 @@ export default class GitBlameContentProvider implements TextDocumentContentProvi
|
||||
let editor = this._findEditor(uri);
|
||||
if (editor) {
|
||||
clearInterval(handle);
|
||||
editor.setDecorations(this._blameDecoration, data.lines.map(l => {
|
||||
return {
|
||||
range: editor.document.validateRange(new Range(l.originalLine, 0, l.originalLine, 1000000)),
|
||||
hoverMessage: `${moment(l.date).format('MMMM Do, YYYY hh:MMa')}\n${l.author}\n${l.sha}`
|
||||
};
|
||||
}));
|
||||
this.blameProvider.getBlameForShaRange(data.fileName, data.sha, data.range).then(blame => {
|
||||
if (blame.lines.length) {
|
||||
editor.setDecorations(this._blameDecoration, blame.lines.map(l => {
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
// });
|
||||
// }
|
||||
// }
|
||||
@@ -1,30 +1,47 @@
|
||||
'use strict';
|
||||
import {commands, DocumentSelector, ExtensionContext, languages, workspace} from 'vscode';
|
||||
import GitCodeLensProvider from './codeLensProvider';
|
||||
import {CodeLens, commands, DocumentSelector, ExtensionContext, languages, Uri, window, workspace} from 'vscode';
|
||||
import GitCodeLensProvider, {GitBlameCodeLens} from './codeLensProvider';
|
||||
import GitContentProvider from './contentProvider';
|
||||
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
|
||||
export function activate(context: ExtensionContext) {
|
||||
// Workspace not using a folder. No access to git repo.
|
||||
if (!workspace.rootPath) {
|
||||
console.warn('Git CodeLens inactive: no rootPath');
|
||||
console.warn('GitLens inactive: no rootPath');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`Git CodeLens active: ${workspace.rootPath}`);
|
||||
|
||||
console.log(`GitLens active: ${workspace.rootPath}`);
|
||||
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) => {
|
||||
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' };
|
||||
context.subscriptions.push(languages.registerCodeLensProvider(selector, new GitCodeLensProvider(repoPath)));
|
||||
context.subscriptions.push(languages.registerCodeLensProvider(selector, new GitCodeLensProvider(context, blameProvider)));
|
||||
}).catch(reason => console.warn(reason));
|
||||
}
|
||||
|
||||
|
||||
50
src/git.ts
50
src/git.ts
@@ -1,50 +1,23 @@
|
||||
'use strict';
|
||||
import {basename, dirname, extname} from 'path';
|
||||
import {basename, dirname, extname, relative} from 'path';
|
||||
import * as fs from 'fs';
|
||||
import * as tmp from 'tmp';
|
||||
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) {
|
||||
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) {
|
||||
console.log('git', 'blame', '-fnw', '--root', '--', fileName);
|
||||
return gitCommand(dirname(fileName), 'blame', '-fnw', '--root', '--', fileName).then(data => {
|
||||
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;
|
||||
});
|
||||
return gitCommand(dirname(fileName), 'blame', '-fnw', '--root', '--', fileName);
|
||||
}
|
||||
|
||||
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) => {
|
||||
gitCommand(repoPath, 'show', `${sha.replace('^', '')}:${source.replace(/\\/g, '/')}`).then(data => {
|
||||
let ext = extname(source);
|
||||
tmp.file({ prefix: `${basename(source, ext)}-${sha}_`, postfix: ext }, (err, destination, fd, cleanupCallback) => {
|
||||
gitGetVersionText(fileName, repoPath, sha).then(data => {
|
||||
let ext = extname(fileName);
|
||||
tmp.file({ prefix: `${basename(fileName, ext)}-${sha}_`, postfix: ext }, (err, destination, fd, cleanupCallback) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
return;
|
||||
@@ -65,9 +38,14 @@ export function gitGetVersionFile(repoPath: string, sha: string, source: string)
|
||||
});
|
||||
}
|
||||
|
||||
export function gitGetVersionText(repoPath: string, sha: string, source: string) {
|
||||
console.log('git', 'show', `${sha}:${source.replace(/\\/g, '/')}`);
|
||||
return gitCommand(repoPath, 'show', `${sha}:${source.replace(/\\/g, '/')}`);
|
||||
export function gitGetVersionText(fileName: string, repoPath: string, sha: string) {
|
||||
const gitArg = normalizeArgument(fileName, repoPath, sha);
|
||||
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) {
|
||||
|
||||
130
src/gitBlameProvider.ts
Normal file
130
src/gitBlameProvider.ts
Normal 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
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
{
|
||||
"globalDependencies": {
|
||||
"tmp": "registry:dt/tmp#0.0.0+20160514170650"
|
||||
},
|
||||
"dependencies": {
|
||||
"lodash": "registry:npm/lodash#4.0.0+20160723033700"
|
||||
}
|
||||
}
|
||||
|
||||
1
typings/index.d.ts
vendored
1
typings/index.d.ts
vendored
@@ -1 +1,2 @@
|
||||
/// <reference path="globals/tmp/index.d.ts" />
|
||||
/// <reference path="modules/lodash/index.d.ts" />
|
||||
|
||||
18545
typings/modules/lodash/index.d.ts
vendored
Normal file
18545
typings/modules/lodash/index.d.ts
vendored
Normal file
File diff suppressed because it is too large
Load Diff
11
typings/modules/lodash/typings.json
Normal file
11
typings/modules/lodash/typings.json
Normal 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"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user