Skip to content

Commit 03d4cc8

Browse files
author
Eric Amodio
committed
Richer blame info & highlight (wip)
1 parent b08044f commit 03d4cc8

File tree

5 files changed

+158
-62
lines changed

5 files changed

+158
-62
lines changed

blame.png

20.9 KB
Loading

src/codeLensProvider.ts

Lines changed: 54 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
'use strict';
2-
import {CancellationToken, CodeLens, CodeLensProvider, commands, Location, Range, SymbolInformation, SymbolKind, TextDocument, Uri} from 'vscode';
2+
import {CancellationToken, CodeLens, CodeLensProvider, commands, Location, Position, Range, SymbolInformation, SymbolKind, TextDocument, Uri} from 'vscode';
33
import {Commands, VsCodeCommands} from './constants';
44
import {IGitBlameLine, gitBlame} from './git';
55
import {toGitBlameUri} from './contentProvider';
66
import * as moment from 'moment';
77

8-
export class GitCodeLens extends CodeLens {
8+
export class GitBlameCodeLens extends CodeLens {
99
constructor(private blame: Promise<IGitBlameLine[]>, public repoPath: string, public fileName: string, private blameRange: Range, range: Range) {
1010
super(range);
1111
}
@@ -14,11 +14,21 @@ export class GitCodeLens extends CodeLens {
1414
return this.blame.then(allLines => allLines.slice(this.blameRange.start.line, this.blameRange.end.line + 1));
1515
}
1616

17-
static toUri(lens: GitCodeLens, line: IGitBlameLine, lines: IGitBlameLine[]): Uri {
18-
return toGitBlameUri(Object.assign({ repoPath: lens.repoPath, range: lens.blameRange, lines: lines }, line));
17+
static toUri(lens: GitBlameCodeLens, index: number, line: IGitBlameLine, lines: IGitBlameLine[]): Uri {
18+
return toGitBlameUri(Object.assign({ repoPath: lens.repoPath, index: index, range: lens.blameRange, lines: lines }, line));
1919
}
2020
}
2121

22+
export class GitHistoryCodeLens extends CodeLens {
23+
constructor(public repoPath: string, public fileName: string, range: Range) {
24+
super(range);
25+
}
26+
27+
// static toUri(lens: GitHistoryCodeLens, index: number): Uri {
28+
// return toGitBlameUri(Object.assign({ repoPath: lens.repoPath, index: index, range: lens.blameRange, lines: lines }, line));
29+
// }
30+
}
31+
2232
export default class GitCodeLensProvider implements CodeLensProvider {
2333
constructor(public repoPath: string) { }
2434

@@ -29,39 +39,52 @@ export default class GitCodeLensProvider implements CodeLensProvider {
2939
return (commands.executeCommand(VsCodeCommands.ExecuteDocumentSymbolProvider, document.uri) as Promise<SymbolInformation[]>).then(symbols => {
3040
let lenses: CodeLens[] = [];
3141
symbols.forEach(sym => this._provideCodeLens(document, sym, blame, lenses));
42+
43+
// Check if we have a lens for the whole document -- if not add one
44+
if (!lenses.find(l => l.range.start.line === 0 && l.range.end.line === 0)) {
45+
const docRange = document.validateRange(new Range(0, 1000000, 1000000, 1000000));
46+
lenses.push(new GitBlameCodeLens(blame, this.repoPath, document.fileName, docRange, new Range(0, 0, 0, docRange.start.character)));
47+
}
3248
return lenses;
3349
});
3450
}
3551

3652
private _provideCodeLens(document: TextDocument, symbol: SymbolInformation, blame: Promise<IGitBlameLine[]>, lenses: CodeLens[]): void {
3753
switch (symbol.kind) {
54+
case SymbolKind.Package:
3855
case SymbolKind.Module:
3956
case SymbolKind.Class:
4057
case SymbolKind.Interface:
41-
case SymbolKind.Method:
42-
case SymbolKind.Function:
4358
case SymbolKind.Constructor:
44-
case SymbolKind.Field:
59+
case SymbolKind.Method:
4560
case SymbolKind.Property:
61+
case SymbolKind.Field:
62+
case SymbolKind.Function:
63+
case SymbolKind.Enum:
4664
break;
4765
default:
4866
return;
4967
}
5068

5169
var line = document.lineAt(symbol.location.range.start);
52-
let lens = new GitCodeLens(blame, this.repoPath, document.fileName, symbol.location.range, line.range);
53-
lenses.push(lens);
70+
lenses.push(new GitBlameCodeLens(blame, this.repoPath, document.fileName, symbol.location.range, line.range.with(new Position(line.range.start.line, line.firstNonWhitespaceCharacterIndex))));
71+
lenses.push(new GitHistoryCodeLens(this.repoPath, document.fileName, line.range.with(new Position(line.range.start.line, line.firstNonWhitespaceCharacterIndex + 1))));
5472
}
5573

5674
resolveCodeLens(lens: CodeLens, token: CancellationToken): Thenable<CodeLens> {
57-
if (lens instanceof GitCodeLens) {
75+
if (lens instanceof GitBlameCodeLens) {
5876
return lens.getBlameLines().then(lines => {
77+
if (!lines.length) {
78+
console.error('No blame lines found', lens);
79+
throw new Error('No blame lines found');
80+
}
81+
5982
let recentLine = lines[0];
6083

6184
let locations: Location[] = [];
6285
if (lines.length > 1) {
63-
let sorted = lines.sort((a, b) => a.date.getTime() - b.date.getTime());
64-
recentLine = sorted[sorted.length - 1];
86+
let sorted = lines.sort((a, b) => b.date.getTime() - a.date.getTime());
87+
recentLine = sorted[0];
6588

6689
console.log(lens.fileName, 'Blame lines:', sorted);
6790

@@ -75,20 +98,35 @@ export default class GitCodeLensProvider implements CodeLensProvider {
7598
}
7699
});
77100

78-
locations = Array.from(map.values()).map(l => new Location(GitCodeLens.toUri(lens, l[0], l), lens.range.start))
101+
Array.from(map.values()).forEach((lines, i) => {
102+
const uri = GitBlameCodeLens.toUri(lens, i + 1, lines[0], lines);
103+
lines.forEach(l => {
104+
locations.push(new Location(uri, new Position(l.originalLine, 0)));
105+
});
106+
});
107+
108+
//locations = Array.from(map.values()).map((l, i) => new Location(GitBlameCodeLens.toUri(lens, i, l[0], l), new Position(l[0].originalLine, 0)));//lens.range.start))
79109
} else {
80-
locations = [new Location(GitCodeLens.toUri(lens, recentLine, lines), lens.range.start)];
110+
locations = [new Location(GitBlameCodeLens.toUri(lens, 1, recentLine, lines), lens.range.start)];
81111
}
82112

83113
lens.command = {
84114
title: `${recentLine.author}, ${moment(recentLine.date).fromNow()}`,
85115
command: Commands.ShowBlameHistory,
86116
arguments: [Uri.file(lens.fileName), lens.range.start, locations]
87-
// command: 'git.viewFileHistory',
88-
// arguments: [Uri.file(codeLens.fileName)]
89117
};
90118
return lens;
91119
}).catch(ex => Promise.reject(ex)); // TODO: Figure out a better way to stop the codelens from appearing
92120
}
121+
122+
// TODO: Play with this more -- get this to open the correct diff to the right place
123+
if (lens instanceof GitHistoryCodeLens) {
124+
lens.command = {
125+
title: `View Diff`,
126+
command: 'git.viewFileHistory', // viewLineHistory
127+
arguments: [Uri.file(lens.fileName)]
128+
};
129+
return Promise.resolve(lens);
130+
}
93131
}
94132
}

src/contentProvider.ts

Lines changed: 64 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,46 @@
11
'use strict';
2-
import {Disposable, EventEmitter, ExtensionContext, Location, OverviewRulerLane, Range, TextEditorDecorationType, TextDocumentContentProvider, Uri, window, workspace} from 'vscode';
2+
import {Disposable, EventEmitter, ExtensionContext, OverviewRulerLane, Range, TextEditor, TextEditorDecorationType, TextDocumentContentProvider, Uri, window, workspace} from 'vscode';
33
import {DocumentSchemes} from './constants';
44
import {gitGetVersionFile, gitGetVersionText, IGitBlameLine} from './git';
5-
import {basename, dirname, extname} from 'path';
5+
import {basename, dirname, extname, join} from 'path';
66
import * as moment from 'moment';
77

88
export default class GitBlameContentProvider implements TextDocumentContentProvider {
99
static scheme = DocumentSchemes.GitBlame;
1010

1111
private _blameDecoration: TextEditorDecorationType;
1212
private _onDidChange = new EventEmitter<Uri>();
13+
private _subscriptions: Disposable;
14+
// private _dataMap: Map<string, IGitBlameUriData>;
1315

1416
constructor(context: ExtensionContext) {
15-
let image = context.asAbsolutePath('blame.png');
17+
// TODO: Light & Dark
1618
this._blameDecoration = window.createTextEditorDecorationType({
17-
backgroundColor: 'rgba(21, 251, 126, 0.7)',
18-
gutterIconPath: image,
19-
gutterIconSize: 'auto'
19+
backgroundColor: 'rgba(254, 220, 95, 0.15)',
20+
gutterIconPath: context.asAbsolutePath('blame.png'),
21+
overviewRulerColor: 'rgba(254, 220, 95, 0.60)',
22+
overviewRulerLane: OverviewRulerLane.Right,
23+
isWholeLine: true
2024
});
25+
26+
// this._dataMap = new Map();
27+
// this._subscriptions = Disposable.from(
28+
// workspace.onDidOpenTextDocument(d => {
29+
// let data = this._dataMap.get(d.uri.toString());
30+
// if (!data) return;
31+
32+
// // TODO: This only works on the first load -- not after since it is cached
33+
// this._tryAddBlameDecorations(d.uri, data);
34+
// }),
35+
// workspace.onDidCloseTextDocument(d => {
36+
// this._dataMap.delete(d.uri.toString());
37+
// })
38+
// );
2139
}
2240

2341
dispose() {
2442
this._onDidChange.dispose();
43+
this._subscriptions && this._subscriptions.dispose();
2544
}
2645

2746
get onDidChange() {
@@ -34,21 +53,20 @@ export default class GitBlameContentProvider implements TextDocumentContentProvi
3453

3554
provideTextDocumentContent(uri: Uri): string | Thenable<string> {
3655
const data = fromGitBlameUri(uri);
56+
// this._dataMap.set(uri.toString(), data);
57+
58+
//const editor = this._findEditor(Uri.file(join(data.repoPath, data.file)));
3759

38-
console.log('provideTextDocumentContent', uri, data);
60+
//console.log('provideTextDocumentContent', uri, data);
3961
return gitGetVersionText(data.repoPath, data.sha, data.file).then(text => {
4062
this.update(uri);
4163

42-
setTimeout(() => {
43-
let uriString = uri.toString();
44-
let editor = window.visibleTextEditors.find((e: any) => (e._documentData && e._documentData._uri && e._documentData._uri.toString()) === uriString);
45-
if (editor) {
46-
editor.setDecorations(this._blameDecoration, data.lines.map(l => new Range(l.line, 0, l.line, 1)));
47-
}
48-
}, 1500);
64+
// TODO: This only works on the first load -- not after since it is cached
65+
this._tryAddBlameDecorations(uri, data);
66+
67+
// TODO: This needs to move to selection somehow to show on the main file editor
68+
//this._addBlameDecorations(editor, data);
4969

50-
// let foo = text.split('\n');
51-
// return foo.slice(data.range.start.line, data.range.end.line).join('\n')
5270
return text;
5371
});
5472

@@ -60,18 +78,47 @@ export default class GitBlameContentProvider implements TextDocumentContentProvi
6078
// });
6179
// });
6280
}
81+
82+
private _findEditor(uri: Uri): TextEditor {
83+
let uriString = uri.toString();
84+
const matcher = (e: any) => (e._documentData && e._documentData._uri && e._documentData._uri.toString()) === uriString;
85+
if (matcher(window.activeTextEditor)) {
86+
return window.activeTextEditor;
87+
}
88+
return window.visibleTextEditors.find(matcher);
89+
}
90+
91+
private _tryAddBlameDecorations(uri: Uri, data: IGitBlameUriData) {
92+
let handle = setInterval(() => {
93+
let editor = this._findEditor(uri);
94+
if (editor) {
95+
clearInterval(handle);
96+
editor.setDecorations(this._blameDecoration, data.lines.map(l => {
97+
return {
98+
range: editor.document.validateRange(new Range(l.originalLine, 0, l.originalLine, 1000000)),
99+
hoverMessage: `${moment(l.date).fromNow()}\n${l.author}\n${l.sha}`
100+
};
101+
}));
102+
}
103+
}, 200);
104+
}
105+
106+
// private _addBlameDecorations(editor: TextEditor, data: IGitBlameUriData) {
107+
// editor.setDecorations(this._blameDecoration, data.lines.map(l => editor.document.validateRange(new Range(l.line, 0, l.line, 1000000))));
108+
// }
63109
}
64110

65111
export interface IGitBlameUriData extends IGitBlameLine {
66112
repoPath: string,
67113
range: Range,
114+
index: number,
68115
lines: IGitBlameLine[]
69116
}
70117

71118
export function toGitBlameUri(data: IGitBlameUriData) {
72119
let ext = extname(data.file);
73120
let path = `${dirname(data.file)}/${data.sha}: ${basename(data.file, ext)}${ext}`;
74-
return Uri.parse(`${DocumentSchemes.GitBlame}:${path}?${JSON.stringify(data)}`);
121+
return Uri.parse(`${DocumentSchemes.GitBlame}:${data.index}. ${moment(data.date).format('YYYY-MM-DD hh:MMa')} ${path}?${JSON.stringify(data)}`);
75122
}
76123

77124
export function fromGitBlameUri(uri: Uri): IGitBlameUriData {

src/extension.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ export function activate(context: ExtensionContext) {
1919
return commands.executeCommand(VsCodeCommands.ShowReferences, ...args);
2020
}));
2121

22-
let selector: DocumentSelector = { scheme: 'file' };
22+
const selector: DocumentSelector = { scheme: 'file' };
2323
context.subscriptions.push(languages.registerCodeLensProvider(selector, new GitCodeLensProvider(repoPath)));
2424
}).catch(reason => console.warn(reason));
2525
}

src/git.ts

Lines changed: 39 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -14,48 +14,54 @@ export declare interface IGitBlameLine {
1414
code: string;
1515
}
1616

17-
export function gitRepoPath(cwd) {
18-
const mapper = (input, output) => {
19-
output.push(input.toString().replace(/\r?\n|\r/g, ''))
20-
};
21-
22-
return new Promise<string>((resolve, reject) => {
23-
gitCommand(cwd, mapper, 'rev-parse', '--show-toplevel')
24-
.then(result => resolve(result[0]))
25-
.catch(reason => reject(reason));
26-
});
17+
export function gitRepoPath(cwd): Promise<string> {
18+
let data: Array<string> = [];
19+
const capture = input => data.push(input.toString().replace(/\r?\n|\r/g, ''));
20+
const output = () => data[0];
21+
22+
return gitCommand(cwd, capture, output, 'rev-parse', '--show-toplevel');
23+
24+
// return new Promise<string>((resolve, reject) => {
25+
// gitCommand(cwd, capture, output, 'rev-parse', '--show-toplevel')
26+
// .then(result => resolve(result[0]))
27+
// .catch(reason => reject(reason));
28+
// });
2729
}
2830

2931
//const blameMatcher = /^(.*)\t\((.*)\t(.*)\t(.*?)\)(.*)$/gm;
30-
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;
32+
//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;
33+
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;
3134

3235
export function gitBlame(fileName: string): Promise<IGitBlameLine[]> {
33-
const mapper = (input, output) => {
34-
let blame = input.toString();
35-
console.log(fileName, 'Blame:', blame);
36-
36+
let data: string = '';
37+
const capture = input => data += input.toString();
38+
const output = () => {
39+
let lines: Array<IGitBlameLine> = [];
3740
let m: Array<string>;
38-
while ((m = blameMatcher.exec(blame)) != null) {
39-
output.push({
41+
while ((m = blameMatcher.exec(data)) != null) {
42+
lines.push({
4043
sha: m[1],
4144
file: m[2].trim(),
42-
originalLine: parseInt(m[3], 10),
45+
originalLine: parseInt(m[3], 10) - 1,
4346
author: m[4].trim(),
4447
date: new Date(m[5]),
45-
line: parseInt(m[6], 10),
48+
line: parseInt(m[6], 10) - 1,
4649
code: m[7]
4750
});
4851
}
52+
return lines;
4953
};
5054

51-
return gitCommand(dirname(fileName), mapper, 'blame', '-fnw', '--', fileName);
55+
return gitCommand(dirname(fileName), capture, output, 'blame', '-fnw', '--', fileName);
5256
}
5357

5458
export function gitGetVersionFile(repoPath: string, sha: string, source: string): Promise<any> {
55-
const mapper = (input, output) => output.push(input);
59+
let data: Array<any> = [];
60+
const capture = input => data.push(input);
61+
const output = () => data;
5662

5763
return new Promise<string>((resolve, reject) => {
58-
(gitCommand(repoPath, mapper, 'show', `${sha}:${source.replace(/\\/g, '/')}`) as Promise<Array<Buffer>>).then(o => {
64+
(gitCommand(repoPath, capture, output, 'show', `${sha}:${source.replace(/\\/g, '/')}`) as Promise<Array<Buffer>>).then(o => {
5965
let ext = extname(source);
6066
tmp.file({ prefix: `${basename(source, ext)}-${sha}_`, postfix: ext }, (err, destination, fd, cleanupCallback) => {
6167
if (err) {
@@ -79,19 +85,20 @@ export function gitGetVersionFile(repoPath: string, sha: string, source: string)
7985
}
8086

8187
export function gitGetVersionText(repoPath: string, sha: string, source: string): Promise<string> {
82-
const mapper = (input, output) => output.push(input.toString());
88+
let data: Array<string> = [];
89+
const capture = input => data.push(input.toString());
90+
const output = () => data;
8391

84-
return new Promise<string>((resolve, reject) => (gitCommand(repoPath, mapper, 'show', `${sha}:${source.replace(/\\/g, '/')}`) as Promise<Array<string>>).then(o => resolve(o.join())));
92+
return new Promise<string>((resolve, reject) => (gitCommand(repoPath, capture, output, 'show', `${sha}:${source.replace(/\\/g, '/')}`) as Promise<Array<string>>).then(o => resolve(o.join())));
8593
}
8694

87-
function gitCommand(cwd: string, mapper: (input: Buffer, output: Array<any>) => void, ...args): Promise<any> {
95+
function gitCommand(cwd: string, capture: (input: Buffer) => void, output: () => any, ...args): Promise<any> {
8896
return new Promise<any>((resolve, reject) => {
8997
let spawn = require('child_process').spawn;
9098
let process = spawn('git', args, { cwd: cwd });
9199

92-
let output: Array<any> = [];
93100
process.stdout.on('data', data => {
94-
mapper(data, output);
101+
capture(data);
95102
});
96103

97104
let errors: Array<string> = [];
@@ -105,7 +112,11 @@ function gitCommand(cwd: string, mapper: (input: Buffer, output: Array<any>) =>
105112
return;
106113
}
107114

108-
resolve(output);
115+
try {
116+
resolve(output());
117+
} catch (ex) {
118+
reject(ex);
119+
}
109120
});
110121
});
111122
}

0 commit comments

Comments
 (0)