17 Commits
0.0.1 ... 0.0.4

Author SHA1 Message Date
Eric Amodio
fbcd0a9cd6 Changes description to be more generic 2016-09-05 17:52:43 -04:00
Eric Amodio
e929db0106 Preps for 0.0.4 release 2016-09-05 17:49:25 -04:00
Eric Amodio
b7920f3c3d Fixes (read: hacks) blame with visible whitespace
Adds diff menu commands always
Attempts to move the diff file to the correct line number
Fixes code action provider -- works again
Deletes deprecated code
2016-09-05 16:40:38 -04:00
Eric Amodio
d04696ac1d Adds code actions to open diffs
Adds context menus for toggling blame
Adds context menus for opening diffs
More refactoring and many bug fixes
2016-09-04 21:46:40 -04:00
Eric Amodio
ebb1085562 Switches to porcelain blame format
Provides more data (commit message, previous commit, etc)
2016-09-04 03:43:35 -04:00
Eric Amodio
47ce5c5132 Adds author count + leader CodeLens
Upgrades to TypeScript 2
Lots of refactoring and many bug fixes
2016-09-04 00:49:02 -04:00
Eric Amodio
f08339335d Adds full blame UI support 2016-09-02 21:24:53 -04:00
Eric Amodio
f4d3d1718d Reverses diff ordering
Only adds blame code lens within the specified range
2016-09-02 00:53:13 -04:00
Eric Amodio
ea33560f14 Removes hard dependency on donjayamanne.githistory
Provides optional additional code lens
2016-08-31 21:24:03 -04:00
Eric Amodio
70cc92ddd6 Adds CodeLens for Diff'ing in blame
Other fixes and refactoring
2016-08-31 21:15:06 -04:00
Eric Amodio
0e064f15c7 Reworks git abstraction and acccess
Adds commands module
Adds git commit message to blame hover decorator
2016-08-31 17:20:53 -04:00
Eric Amodio
9964ea691b Fixes issue with executing blame command
And minor other positioning issues
2016-08-31 15:55:33 -04:00
Eric Amodio
92beca2542 Fixes issues with file renames
And other git related edge cases
2016-08-31 15:03:22 -04:00
Eric Amodio
0ccac8da8c Preps 0.0.2 release 2016-08-31 05:05:09 -04:00
Eric Amodio
a22b8b1ddd Reworks location processing
Decoupled from the CodeLens and less processing before it is required
2016-08-31 05:03:20 -04:00
Eric Amodio
84becec23f Moves lens start char to center on symbol
Also helps move lens after other lenses
2016-08-31 03:54:03 -04:00
Eric Amodio
c395a583b7 Renamed to GitLens
Reworked Uri scheme to drastically reduce encoded data (big perf improvement)
2016-08-31 03:34:16 -04:00
22 changed files with 19802 additions and 312 deletions

View File

@@ -2,11 +2,13 @@
{ {
"files.exclude": { "files.exclude": {
"out": false, // set this to true to hide the "out" folder with the compiled JS files "out": false, // set this to true to hide the "out" folder with the compiled JS files
"node_modules": false "node_modules": true,
"typings": true
}, },
"search.exclude": { "search.exclude": {
"out": true, // set this to false to include "out" folder in search results "out": true, // set this to false to include "out" folder in search results
"node_modules": true "node_modules": true,
"typings": true
}, },
"typescript.tsdk": "./node_modules/typescript/lib" // we want to use the TS server from our node_modules folder to control its version "typescript.tsdk": "./node_modules/typescript/lib" // we want to use the TS server from our node_modules folder to control its version
} }

View File

@@ -1,16 +1,16 @@
# 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 blame history CodeLens for many supported Visual Studio Code languages (in theory -- the language must support symbol searching).
## Features ## Features
Provides CodeLens with the author and date of the last check-in. Provides two CodeLens on code blocks :
- **Recent Change** - author and date of the most recent check-in
> Clicking on the CodeLens opens a **Blame explorer** with the commits and changed lines in the right pane and the commit (file) contents on the left
- **Blame** - number of authors of a block and the most prominent author (if there are more than one)
> Clicking on the CodeLens toggles Git blame overlay
> ![CodeLens](https://raw.githubusercontent.com/eamodio/vscode-git-codelens/master/images/preview-codelens.png) > ![GitLens preview](https://raw.githubusercontent.com/eamodio/vscode-git-codelens/master/images/preview-gitlens.gif)
Clicking on a CodeLens opens a blame "explorer" with the commits and changed lines in the right pane and the commit (file) contents on the left.
> ![Blame Explorer](https://raw.githubusercontent.com/eamodio/vscode-git-codelens/master/images/preview-blame.png)
## Requirements ## Requirements
@@ -22,10 +22,17 @@ None yet.
## Known Issues ## Known Issues
Too many to count -- this is still very much a work in progress. - Content in the **Blame explorer** disappears after a bit: [Open vscode issue](https://github.com/Microsoft/vscode/issues/11360)
- Highlighted lines disappear in **Blame explorer** after changing selection and returning to a previous selection: [Open vscode issue](https://github.com/Microsoft/vscode/issues/11360)
- CodeLens aren't updated properly after a file is saved: [Open vscode issue](https://github.com/Microsoft/vscode/issues/11546)
- Visible whitespace causes issue with blame overlay (currently fixed with a hack, but fails randomly): [Open vscode issue](https://github.com/Microsoft/vscode/issues/11485)
## Release Notes ## Release Notes
### 0.0.4
Candidate for preview release on the vscode marketplace.
### 0.0.1 ### 0.0.1
Initial release but still heavily a work in progress. Initial release but still heavily a work in progress.

BIN
images/preview-gitlens.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

View File

@@ -1,19 +1,19 @@
{ {
"name": "git-codelens", "name": "gitlens",
"version": "0.0.1", "version": "0.0.4",
"author": "Eric Amodio", "author": "Eric Amodio",
"publisher": "eamodio", "publisher": "eamodio",
"engines": { "engines": {
"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 information in CodeLens",
"categories": [ "categories": [
"Other" "Other"
], ],
"keywords": [ "keywords": [
"git", "gitblame", "blame" "git", "gitblame", "blame", "codelens"
], ],
"galleryBanner": { "galleryBanner": {
"color": "#0000FF", "color": "#0000FF",
@@ -23,9 +23,53 @@
"main": "./out/src/extension", "main": "./out/src/extension",
"contributes": { "contributes": {
"commands": [{ "commands": [{
"command": "git.codelen.showBlameHistory", "command": "gitlens.diffWithPrevious",
"title": "Show Blame History", "title": "GitLens: Open Diff with Previous Commit",
"category": "Git" "category": "GitLens"
},
{
"command": "gitlens.diffWithWorking",
"title": "GitLens: Open Diff with Working Tree",
"category": "GitLens"
},
{
"command": "gitlens.showBlame",
"title": "GitLens: Show Git Blame",
"category": "GitLens"
},
{
"command": "gitlens.toggleBlame",
"title": "GitLens: Toggle Git Blame",
"category": "GitLens"
}],
"menus": {
"editor/title": [{
"when": "editorTextFocus",
"command": "gitlens.toggleBlame",
"group": "gitlens"
}],
"editor/context": [
{
"when": "editorTextFocus",
"command": "gitlens.diffWithWorking",
"group": "gitlens@1.0"
},
{
"when": "editorTextFocus",
"command": "gitlens.diffWithPrevious",
"group": "gitlens@1.1"
},
{
"when": "editorTextFocus",
"command": "gitlens.toggleBlame",
"group": "gitlens-blame@1.2"
}]
},
"keybindings": [{
"command": "gitlens.toggleBlame",
"key": "alt+b",
"mac": "alt+b",
"when": "editorTextFocus"
}] }]
}, },
"activationEvents": [ "activationEvents": [
@@ -38,15 +82,12 @@
"tmp": "^0.0.28" "tmp": "^0.0.28"
}, },
"devDependencies": { "devDependencies": {
"typescript": "^1.8.10", "typescript": "^2.0.0",
"vscode": "^0.11.17" "vscode": "^0.11.17"
}, },
"extensionDependencies": [
"donjayamanne.githistory"
],
"scripts": { "scripts": {
"vscode:prepublish": "node ./node_modules/vscode/bin/compile", "vscode:prepublish": "node ./node_modules/vscode/bin/compile",
"compile": "node ./node_modules/vscode/bin/compile -watch -p ./", "compile": "node ./node_modules/vscode/bin/compile -watch -p ./",
"postinstall": "node ./node_modules/vscode/bin/install && tsc" "postinstall": "node ./node_modules/vscode/bin/install"
} }
} }

View File

@@ -1,136 +0,0 @@
'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 * 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) {
super(range);
}
getBlameLines(): Promise<IGitBlameLine[]> {
return this.blame.then(allLines => allLines.slice(this.blameRange.start.line, this.blameRange.end.line + 1));
}
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));
}
}
export class GitHistoryCodeLens extends CodeLens {
constructor(public repoPath: string, public fileName: string, range: Range) {
super(range);
}
// static toUri(lens: GitHistoryCodeLens, index: number): Uri {
// return toGitBlameUri(Object.assign({ repoPath: lens.repoPath, index: index, range: lens.blameRange, lines: lines }, line));
// }
}
export default class GitCodeLensProvider implements CodeLensProvider {
constructor(public repoPath: string) { }
provideCodeLenses(document: TextDocument, token: CancellationToken): CodeLens[] | Thenable<CodeLens[]> {
// TODO: Should I wait here?
const blame = gitBlame(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));
// 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 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 {
switch (symbol.kind) {
case SymbolKind.Package:
case SymbolKind.Module:
case SymbolKind.Class:
case SymbolKind.Interface:
case SymbolKind.Constructor:
case SymbolKind.Method:
case SymbolKind.Property:
case SymbolKind.Field:
case SymbolKind.Function:
case SymbolKind.Enum:
break;
default:
return;
}
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 GitHistoryCodeLens(this.repoPath, document.fileName, line.range.with(new Position(line.range.start.line, line.firstNonWhitespaceCharacterIndex + 1))));
}
resolveCodeLens(lens: CodeLens, token: CancellationToken): Thenable<CodeLens> {
if (lens instanceof GitBlameCodeLens) return this._resolveGitBlameCodeLens(lens, token);
if (lens instanceof GitHistoryCodeLens) return this._resolveGitHistoryCodeLens(lens, token);
}
_resolveGitBlameCodeLens(lens: GitBlameCodeLens, token: CancellationToken): Thenable<CodeLens> {
return new Promise<CodeLens>((resolve, reject) => {
lens.getBlameLines().then(lines => {
if (!lines.length) {
console.error('No blame lines found', lens);
reject(null);
return;
}
let recentLine = lines[0];
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]);
}
});
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))));
});
} else {
locations = [new Location(GitBlameCodeLens.toUri(lens, 1, recentLine, lines, [recentLine.sha]), lens.range.start)];
}
lens.command = {
title: `${recentLine.author}, ${moment(recentLine.date).fromNow()}`,
command: Commands.ShowBlameHistory,
arguments: [Uri.file(lens.fileName), lens.range.start, locations]
};
resolve(lens);
});
});//.catch(ex => Promise.reject(ex)); // TODO: Figure out a better way to stop the codelens from appearing
}
_resolveGitHistoryCodeLens(lens: GitHistoryCodeLens, token: CancellationToken): Thenable<CodeLens> {
// TODO: Play with this more -- get this to open the correct diff to the right place
lens.command = {
title: `View History`,
command: 'git.viewFileHistory', // viewLineHistory
arguments: [Uri.file(lens.fileName)]
};
return Promise.resolve(lens);
}
}

143
src/commands.ts Normal file
View File

@@ -0,0 +1,143 @@
'use strict'
import {commands, DecorationOptions, Disposable, OverviewRulerLane, Position, Range, TextEditor, TextEditorEdit, TextEditorDecorationType, Uri, window} from 'vscode';
import {BuiltInCommands, Commands} from './constants';
import GitProvider from './gitProvider';
import GitBlameController from './gitBlameController';
import {basename} from 'path';
import * as moment from 'moment';
abstract class Command extends Disposable {
private _subscriptions: Disposable;
constructor(command: Commands) {
super(() => this.dispose());
this._subscriptions = commands.registerCommand(command, this.execute, this);
}
dispose() {
this._subscriptions && this._subscriptions.dispose();
}
abstract execute(...args): any;
}
abstract class EditorCommand extends Disposable {
private _subscriptions: Disposable;
constructor(command: Commands) {
super(() => this.dispose());
this._subscriptions = commands.registerTextEditorCommand(command, this.execute, this);
}
dispose() {
this._subscriptions && this._subscriptions.dispose();
}
abstract execute(editor: TextEditor, edit: TextEditorEdit, ...args): any;
}
export class DiffWithPreviousCommand extends EditorCommand {
constructor(private git: GitProvider) {
super(Commands.DiffWithPrevious);
}
execute(editor: TextEditor, edit: TextEditorEdit, uri?: Uri, sha?: string, compareWithSha?: string, line?: number) {
line = line || editor.selection.active.line;
if (!sha) {
return this.git.getBlameForLine(uri.path, line)
.then(blame => commands.executeCommand(Commands.DiffWithPrevious, uri, blame.commit.sha, blame.commit.previousSha));
}
if (!compareWithSha) {
return window.showInformationMessage(`Commit ${sha} has no previous commit`);
}
return Promise.all([this.git.getVersionedFile(uri.path, sha), this.git.getVersionedFile(uri.path, compareWithSha)])
.then(values => {
const [source, compare] = values;
const fileName = basename(uri.path);
return commands.executeCommand(BuiltInCommands.Diff, Uri.file(compare), Uri.file(source), `${fileName} (${compareWithSha}) ↔ ${fileName} (${sha})`)
// TODO: Moving doesn't always seem to work -- or more accurately it seems like it moves down that number of lines from the current line
// which for a diff could be the first difference
.then(() => commands.executeCommand(BuiltInCommands.CursorMove, { to: 'down', value: line }));
});
}
}
export class DiffWithWorkingCommand extends EditorCommand {
constructor(private git: GitProvider) {
super(Commands.DiffWithWorking);
}
execute(editor: TextEditor, edit: TextEditorEdit, uri?: Uri, sha?: string, line?: number) {
line = line || editor.selection.active.line;
if (!sha) {
return this.git.getBlameForLine(uri.path, line)
.then(blame => commands.executeCommand(Commands.DiffWithWorking, uri, blame.commit.sha));
};
return this.git.getVersionedFile(uri.path, sha).then(compare => {
const fileName = basename(uri.path);
return commands.executeCommand(BuiltInCommands.Diff, Uri.file(compare), uri, `${fileName} (${sha}) ↔ ${fileName} (index)`)
// TODO: Moving doesn't always seem to work -- or more accurately it seems like it moves down that number of lines from the current line
// which for a diff could be the first difference
.then(() => commands.executeCommand(BuiltInCommands.CursorMove, { to: 'down', value: line }));
});
}
}
export class ShowBlameCommand extends EditorCommand {
constructor(private git: GitProvider, private blameController: GitBlameController) {
super(Commands.ShowBlame);
}
execute(editor: TextEditor, edit: TextEditorEdit, uri?: Uri, sha?: string) {
if (sha) {
return this.blameController.toggleBlame(editor, sha);
}
const activeLine = editor.selection.active.line;
return this.git.getBlameForLine(editor.document.fileName, activeLine)
.then(blame => this.blameController.showBlame(editor, blame.commit.sha));
}
}
export class ShowBlameHistoryCommand extends EditorCommand {
constructor(private git: GitProvider) {
super(Commands.ShowBlameHistory);
}
execute(editor: TextEditor, edit: TextEditorEdit, uri?: Uri, range?: Range, position?: Position) {
// If the command is executed manually -- treat it as a click on the root lens (i.e. show blame for the whole file)
if (!uri) {
const doc = editor.document;
if (doc) {
uri = doc.uri;
range = doc.validateRange(new Range(0, 0, 1000000, 1000000));
position = doc.validateRange(new Range(0, 0, 0, 1000000)).start;
}
if (!uri) return;
}
return this.git.getBlameLocations(uri.path, range).then(locations => {
return commands.executeCommand(BuiltInCommands.ShowReferences, uri, position, locations);
});
}
}
export class ToggleBlameCommand extends EditorCommand {
constructor(private git: GitProvider, private blameController: GitBlameController) {
super(Commands.ToggleBlame);
}
execute(editor: TextEditor, edit: TextEditorEdit, uri?: Uri, sha?: string) {
if (sha) {
return this.blameController.toggleBlame(editor, sha);
}
const activeLine = editor.selection.active.line;
return this.git.getBlameForLine(editor.document.fileName, activeLine)
.then(blame => this.blameController.toggleBlame(editor, blame.commit.sha));
}
}

View File

@@ -1,15 +1,37 @@
export type Commands = 'git.action.showBlameHistory'; 'use strict'
export const Commands = {
ShowBlameHistory: 'git.action.showBlameHistory' as Commands export const DiagnosticCollectionName = 'gitlens';
export const DiagnosticSource = 'GitLens';
export const RepoPath = 'repoPath';
export type BuiltInCommands = 'cursorMove' | 'vscode.diff' | 'vscode.executeDocumentSymbolProvider' | 'vscode.executeCodeLensProvider' | 'editor.action.showReferences' | 'editor.action.toggleRenderWhitespace';
export const BuiltInCommands = {
CursorMove: 'cursorMove' as BuiltInCommands,
Diff: 'vscode.diff' as BuiltInCommands,
ExecuteDocumentSymbolProvider: 'vscode.executeDocumentSymbolProvider' as BuiltInCommands,
ExecuteCodeLensProvider: 'vscode.executeCodeLensProvider' as BuiltInCommands,
ShowReferences: 'editor.action.showReferences' as BuiltInCommands,
ToggleRenderWhitespace: 'editor.action.toggleRenderWhitespace' as BuiltInCommands
} }
export type DocumentSchemes = 'gitblame'; export type Commands = 'gitlens.diffWithPrevious' | 'gitlens.diffWithWorking' | 'gitlens.showBlame' | 'gitlens.showHistory' | 'gitlens.toggleBlame';
export const Commands = {
DiffWithPrevious: 'gitlens.diffWithPrevious' as Commands,
DiffWithWorking: 'gitlens.diffWithWorking' as Commands,
ShowBlame: 'gitlens.showBlame' as Commands,
ShowBlameHistory: 'gitlens.showHistory' as Commands,
ToggleBlame: 'gitlens.toggleBlame' as Commands,
}
export type DocumentSchemes = 'file' | 'git' | 'gitblame';
export const DocumentSchemes = { export const DocumentSchemes = {
File: 'file' as DocumentSchemes,
Git: 'git' as DocumentSchemes,
GitBlame: 'gitblame' as DocumentSchemes GitBlame: 'gitblame' as DocumentSchemes
} }
export type VsCodeCommands = 'vscode.executeDocumentSymbolProvider' | 'editor.action.showReferences'; export type WorkspaceState = 'hasGitHistoryExtension' | 'repoPath';
export const VsCodeCommands = { export const WorkspaceState = {
ExecuteDocumentSymbolProvider: 'vscode.executeDocumentSymbolProvider' as VsCodeCommands, HasGitHistoryExtension: 'hasGitHistoryExtension' as WorkspaceState,
ShowReferences: 'editor.action.showReferences' as VsCodeCommands RepoPath: 'repoPath' as WorkspaceState
} }

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,44 @@
'use strict'; 'use strict';
import {commands, DocumentSelector, ExtensionContext, languages, workspace} from 'vscode'; import {CodeLens, DocumentSelector, ExtensionContext, extensions, languages, OverviewRulerLane, window, workspace} from 'vscode';
import GitCodeLensProvider from './codeLensProvider'; import GitContentProvider from './gitContentProvider';
import GitContentProvider from './contentProvider'; import GitBlameCodeLensProvider from './gitBlameCodeLensProvider';
import {gitRepoPath} from './git'; import GitBlameContentProvider from './gitBlameContentProvider';
import {Commands, VsCodeCommands} from './constants'; import GitBlameController from './gitBlameController';
import GitProvider from './gitProvider';
import {DiffWithPreviousCommand, DiffWithWorkingCommand, ShowBlameCommand, ShowBlameHistoryCommand, ToggleBlameCommand} from './commands';
import {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 => { const git = new GitProvider(context);
context.subscriptions.push(workspace.registerTextDocumentContentProvider(GitContentProvider.scheme, new GitContentProvider(context))); context.subscriptions.push(git);
context.subscriptions.push(commands.registerCommand(Commands.ShowBlameHistory, (...args) => { git.getRepoPath(workspace.rootPath).then(repoPath => {
return commands.executeCommand(VsCodeCommands.ShowReferences, ...args); context.workspaceState.update(WorkspaceState.RepoPath, repoPath);
})); //context.workspaceState.update(WorkspaceState.HasGitHistoryExtension, extensions.getExtension('donjayamanne.githistory') !== undefined);
const selector: DocumentSelector = { scheme: 'file' }; context.subscriptions.push(workspace.registerTextDocumentContentProvider(GitContentProvider.scheme, new GitContentProvider(context, git)));
context.subscriptions.push(languages.registerCodeLensProvider(selector, new GitCodeLensProvider(repoPath))); context.subscriptions.push(workspace.registerTextDocumentContentProvider(GitBlameContentProvider.scheme, new GitBlameContentProvider(context, git)));
context.subscriptions.push(languages.registerCodeLensProvider(GitBlameCodeLensProvider.selector, new GitBlameCodeLensProvider(context, git)));
const blameController = new GitBlameController(context, git);
context.subscriptions.push(blameController);
context.subscriptions.push(new DiffWithWorkingCommand(git));
context.subscriptions.push(new DiffWithPreviousCommand(git));
context.subscriptions.push(new ShowBlameCommand(git, blameController));
context.subscriptions.push(new ToggleBlameCommand(git, blameController));
context.subscriptions.push(new ShowBlameHistoryCommand(git));
}).catch(reason => console.warn(reason)); }).catch(reason => console.warn(reason));
} }

View File

@@ -1,75 +1,94 @@
'use strict'; 'use strict';
import {basename, dirname, extname} from 'path'; import {basename, dirname, extname, isAbsolute, 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 { function gitCommand(cwd: string, ...args) {
sha: string; console.log('git', ...args);
file: string; return spawnPromise('git', args, { cwd: cwd });
originalLine: number;
author: string;
date: Date;
line: number;
//code: string;
} }
export function gitRepoPath(cwd) { export default class Git {
return gitCommand(cwd, 'rev-parse', '--show-toplevel').then(data => data.replace(/\r?\n|\r/g, '')); static normalizePath(fileName: string, repoPath: string) {
} fileName = fileName.replace(/\\/g, '/');
return isAbsolute(fileName) ? relative(repoPath, fileName) : fileName;
}
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; static repoPath(cwd: string) {
return gitCommand(cwd, 'rev-parse', '--show-toplevel').then(data => data.replace(/\r?\n|\r/g, ''));
}
export function gitBlame(fileName: string) { static blame(fileName: string, repoPath: string, sha?: string) {
console.log('git', 'blame', '-fnw', '--root', '--', fileName); fileName = Git.normalizePath(fileName, repoPath);
return gitCommand(dirname(fileName), 'blame', '-fnw', '--root', '--', fileName).then(data => {
let lines: Array<IGitBlameLine> = []; if (sha) {
let m: Array<string>; return gitCommand(repoPath, 'blame', '-fn', '--root', `${sha}^`, '--', fileName);
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> { return gitCommand(repoPath, 'blame', '-fn', '--root', '--', fileName);
return new Promise<string>((resolve, reject) => { // .then(s => { console.log(s); return s; })
gitCommand(repoPath, 'show', `${sha.replace('^', '')}:${source.replace(/\\/g, '/')}`).then(data => { // .catch(ex => console.error(ex));
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); static blamePorcelain(fileName: string, repoPath: string, sha?: string) {
console.log("Filedescriptor: ", fd); fileName = Git.normalizePath(fileName, repoPath);
fs.appendFile(destination, data, err => { if (sha) {
return gitCommand(repoPath, 'blame', '--porcelain', '--root', `${sha}^`, '--', fileName);
}
return gitCommand(repoPath, 'blame', '--porcelain', '--root', '--', fileName);
// .then(s => { console.log(s); return s; })
// .catch(ex => console.error(ex));
}
static getVersionedFile(fileName: string, repoPath: string, sha: string) {
return new Promise<string>((resolve, reject) => {
Git.getVersionedFileText(fileName, repoPath, sha).then(data => {
let ext = extname(fileName);
tmp.file({ prefix: `${basename(fileName, ext)}-${sha}_`, postfix: ext }, (err, destination, fd, cleanupCallback) => {
if (err) { if (err) {
reject(err); reject(err);
return; return;
} }
resolve(destination);
//console.log(`getVersionedFile(${fileName}, ${sha}); destination=${destination}`);
fs.appendFile(destination, data, err => {
if (err) {
reject(err);
return;
}
resolve(destination);
});
}); });
}); });
}); });
}); }
}
export function gitGetVersionText(repoPath: string, sha: string, source: string) { static getVersionedFileText(fileName: string, repoPath: string, sha: string) {
console.log('git', 'show', `${sha}:${source.replace(/\\/g, '/')}`); fileName = Git.normalizePath(fileName, repoPath);
return gitCommand(repoPath, 'show', `${sha}:${source.replace(/\\/g, '/')}`); sha = sha.replace('^', '');
}
function gitCommand(cwd: string, ...args) { return gitCommand(repoPath, 'show', `${sha}:${fileName}`);
return spawnPromise('git', args, { cwd: cwd }); // .then(s => { console.log(s); return s; })
// .catch(ex => console.error(ex));
}
// static getCommitMessage(sha: string, repoPath: string) {
// sha = sha.replace('^', '');
// return gitCommand(repoPath, 'show', '-s', '--format=%B', sha);
// // .then(s => { console.log(s); return s; })
// // .catch(ex => console.error(ex));
// }
// static getCommitMessages(fileName: string, repoPath: string) {
// fileName = Git.normalizePath(fileName, repoPath);
// // git log --format="%h (%aN %x09 %ai) %s" --
// return gitCommand(repoPath, 'log', '--oneline', '--', fileName);
// // .then(s => { console.log(s); return s; })
// // .catch(ex => console.error(ex));
// }
} }

View File

@@ -0,0 +1,88 @@
'use strict';
import {CancellationToken, CodeLens, CodeLensProvider, commands, DocumentSelector, ExtensionContext, Location, Position, Range, SymbolInformation, SymbolKind, TextDocument, Uri} from 'vscode';
import {BuiltInCommands, Commands, DocumentSchemes, WorkspaceState} from './constants';
import GitProvider, {IGitBlame, IGitCommit} from './gitProvider';
import {join} from 'path';
import * as moment from 'moment';
export class GitDiffWithWorkingTreeCodeLens extends CodeLens {
constructor(private git: GitProvider, public fileName: string, public sha: string, range: Range) {
super(range);
}
}
export class GitDiffWithPreviousCodeLens extends CodeLens {
constructor(private git: GitProvider, public fileName: string, public sha: string, public compareWithSha: string, range: Range) {
super(range);
}
}
export default class GitBlameCodeLensProvider implements CodeLensProvider {
static selector: DocumentSelector = { scheme: DocumentSchemes.GitBlame };
constructor(context: ExtensionContext, private git: GitProvider) { }
provideCodeLenses(document: TextDocument, token: CancellationToken): CodeLens[] | Thenable<CodeLens[]> {
const data = this.git.fromBlameUri(document.uri);
const fileName = data.fileName;
const sha = data.sha;
return this.git.getBlameForFile(fileName).then(blame => {
const commits = Array.from(blame.commits.values());
let index = commits.findIndex(c => c.sha === sha) + 1;
let previousCommit: IGitCommit;
if (index < commits.length) {
previousCommit = commits[index];
}
const lenses: CodeLens[] = [];
// Add codelens to each "group" of blame lines
const lines = blame.lines.filter(l => l.sha === sha && l.originalLine >= data.range.start.line && l.originalLine <= data.range.end.line);
let lastLine = lines[0].originalLine;
lines.forEach(l => {
if (l.originalLine !== lastLine + 1) {
lenses.push(new GitDiffWithWorkingTreeCodeLens(this.git, fileName, sha, new Range(l.originalLine, 0, l.originalLine, 1)));
if (previousCommit) {
lenses.push(new GitDiffWithPreviousCodeLens(this.git, fileName, sha, previousCommit.sha, new Range(l.originalLine, 1, l.originalLine, 2)));
}
}
lastLine = l.originalLine;
});
// 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)) {
lenses.push(new GitDiffWithWorkingTreeCodeLens(this.git, fileName, sha, new Range(0, 0, 0, 1)));
if (previousCommit) {
lenses.push(new GitDiffWithPreviousCodeLens(this.git, fileName, sha, previousCommit.sha, new Range(0, 1, 0, 2)));
}
}
return lenses;
});
}
resolveCodeLens(lens: CodeLens, token: CancellationToken): Thenable<CodeLens> {
if (lens instanceof GitDiffWithWorkingTreeCodeLens) return this._resolveDiffWithWorkingTreeCodeLens(lens, token);
if (lens instanceof GitDiffWithPreviousCodeLens) return this._resolveGitDiffWithPreviousCodeLens(lens, token);
}
_resolveDiffWithWorkingTreeCodeLens(lens: GitDiffWithWorkingTreeCodeLens, token: CancellationToken): Thenable<CodeLens> {
lens.command = {
title: `Compare with Working Tree`,
command: Commands.DiffWithWorking,
arguments: [Uri.file(join(this.git.repoPath, lens.fileName)), lens.sha]
};
return Promise.resolve(lens);
}
_resolveGitDiffWithPreviousCodeLens(lens: GitDiffWithPreviousCodeLens, token: CancellationToken): Thenable<CodeLens> {
lens.command = {
title: `Compare with Previous (${lens.compareWithSha})`,
command: Commands.DiffWithPrevious,
arguments: [Uri.file(join(this.git.repoPath, lens.fileName)), lens.sha, lens.compareWithSha]
};
return Promise.resolve(lens);
}
}

View File

@@ -1,8 +1,7 @@
'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 GitProvider, {IGitBlameUriData} from './gitProvider';
import {fromGitBlameUri, IGitBlameUriData} from './gitBlameUri';
import * as moment from 'moment'; import * as moment from 'moment';
export default class GitBlameContentProvider implements TextDocumentContentProvider { export default class GitBlameContentProvider implements TextDocumentContentProvider {
@@ -10,10 +9,9 @@ export default class GitBlameContentProvider implements TextDocumentContentProvi
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) { constructor(context: ExtensionContext, private git: GitProvider) {
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 +28,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 +47,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 = this.git.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 this.git.getVersionedFileText(data.originalFileName || data.fileName, 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 +63,7 @@ export default class GitBlameContentProvider implements TextDocumentContentProvi
return text; return text;
}); });
// return gitGetVersionFile(data.repoPath, data.sha, data.file).then(dst => { // return this.git.getVersionedFile(data.fileName, 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);
@@ -100,15 +86,19 @@ export default class GitBlameContentProvider implements TextDocumentContentProvi
// Needs to be on a timer for some reason because we won't find the editor otherwise -- is there an event? // Needs to be on a timer for some reason because we won't find the editor otherwise -- is there an event?
let handle = setInterval(() => { let handle = setInterval(() => {
let editor = this._findEditor(uri); let editor = this._findEditor(uri);
if (editor) { if (!editor) return;
clearInterval(handle);
editor.setDecorations(this._blameDecoration, data.lines.map(l => { clearInterval(handle);
this.git.getBlameForShaRange(data.fileName, data.sha, data.range).then(blame => {
if (!blame.lines.length) return;
editor.setDecorations(this._blameDecoration, blame.lines.map(l => {
return { return {
range: editor.document.validateRange(new Range(l.originalLine, 0, l.originalLine, 1000000)), 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}` hoverMessage: `${blame.commit.message}\n${blame.commit.author}\n${moment(blame.commit.date).format('MMMM Do, YYYY hh:MM a')}\n${l.sha}`
}; };
})); }));
} });
}, 200); }, 200);
} }

188
src/gitBlameController.ts Normal file
View File

@@ -0,0 +1,188 @@
'use strict'
import {commands, DecorationOptions, Diagnostic, DiagnosticCollection, DiagnosticSeverity, Disposable, ExtensionContext, languages, OverviewRulerLane, Position, Range, TextEditor, TextEditorDecorationType, Uri, window, workspace} from 'vscode';
import {BuiltInCommands, Commands, DocumentSchemes} from './constants';
import GitProvider, {IGitBlame} from './gitProvider';
import GitCodeActionsProvider from './gitCodeActionProvider';
import {DiagnosticCollectionName, DiagnosticSource} from './constants';
import * as moment from 'moment';
const blameDecoration: TextEditorDecorationType = window.createTextEditorDecorationType({
before: {
color: '#5a5a5a',
margin: '0 1em 0 0',
width: '5em'
},
});
let highlightDecoration: TextEditorDecorationType;
export default class GitBlameController extends Disposable {
private _controller: GitBlameEditorController;
private _disposable: Disposable;
private _blameDecoration: TextEditorDecorationType;
private _highlightDecoration: TextEditorDecorationType;
constructor(private context: ExtensionContext, private git: GitProvider) {
super(() => this.dispose());
if (!highlightDecoration) {
highlightDecoration = window.createTextEditorDecorationType({
dark: {
backgroundColor: 'rgba(255, 255, 255, 0.15)',
gutterIconPath: context.asAbsolutePath('images/blame-dark.png'),
overviewRulerColor: 'rgba(255, 255, 255, 0.75)',
},
light: {
backgroundColor: 'rgba(0, 0, 0, 0.15)',
gutterIconPath: context.asAbsolutePath('images/blame-light.png'),
overviewRulerColor: 'rgba(0, 0, 0, 0.75)',
},
gutterIconSize: 'contain',
overviewRulerLane: OverviewRulerLane.Right,
isWholeLine: true
});
}
const subscriptions: Disposable[] = [];
subscriptions.push(window.onDidChangeActiveTextEditor(e => {
if (!this._controller || this._controller.editor === e) return;
this.clear();
}));
this._disposable = Disposable.from(...subscriptions);
}
dispose() {
this.clear();
this._disposable && this._disposable.dispose();
}
clear() {
this._controller && this._controller.dispose();
this._controller = null;
}
showBlame(editor: TextEditor, sha: string) {
if (!editor) {
this.clear();
return;
}
if (!this._controller) {
this._controller = new GitBlameEditorController(this.context, this.git, editor);
return this._controller.applyBlame(sha);
}
}
toggleBlame(editor: TextEditor, sha: string) {
if (!editor || this._controller) {
this.clear();
return;
}
return this.showBlame(editor, sha);
}
}
class GitBlameEditorController extends Disposable {
private _disposable: Disposable;
private _blame: Promise<IGitBlame>;
private _diagnostics: DiagnosticCollection;
private _toggleWhitespace: boolean;
constructor(private context: ExtensionContext, private git: GitProvider, public editor: TextEditor) {
super(() => this.dispose());
const fileName = this.editor.document.uri.path;
this._blame = this.git.getBlameForFile(fileName);
const subscriptions: Disposable[] = [];
this._diagnostics = languages.createDiagnosticCollection(DiagnosticCollectionName);
subscriptions.push(this._diagnostics);
subscriptions.push(languages.registerCodeActionsProvider(GitCodeActionsProvider.selector, new GitCodeActionsProvider(this.context, this.git)));
subscriptions.push(window.onDidChangeTextEditorSelection(e => {
const activeLine = e.selections[0].active.line;
this._diagnostics.clear();
this.git.getBlameForLine(e.textEditor.document.fileName, activeLine)
.then(blame => {
// Add the bogus diagnostics to provide code actions for this sha
this._diagnostics.set(editor.document.uri, [this._getDiagnostic(editor, activeLine, blame.commit.sha)]);
this.applyHighlight(blame.commit.sha);
});
}));
this._disposable = Disposable.from(...subscriptions);
}
dispose() {
if (this.editor) {
if (this._toggleWhitespace) {
commands.executeCommand(BuiltInCommands.ToggleRenderWhitespace);
}
this.editor.setDecorations(blameDecoration, []);
this.editor.setDecorations(highlightDecoration, []);
this.editor = null;
}
this._disposable && this._disposable.dispose();
}
_getDiagnostic(editor, line, sha) {
const diag = new Diagnostic(editor.document.validateRange(new Range(line, 0, line, 1000000)), `Diff commit ${sha}`, DiagnosticSeverity.Hint);
diag.source = DiagnosticSource;
return diag;
}
applyBlame(sha: string) {
return this._blame.then(blame => {
if (!blame.lines.length) return;
// HACK: Until https://github.com/Microsoft/vscode/issues/11485 is fixed -- toggle whitespace off
this._toggleWhitespace = workspace.getConfiguration('editor').get('renderWhitespace') as boolean;
if (this._toggleWhitespace) {
commands.executeCommand(BuiltInCommands.ToggleRenderWhitespace);
}
const blameDecorationOptions: DecorationOptions[] = blame.lines.map(l => {
const c = blame.commits.get(l.sha);
return {
range: this.editor.document.validateRange(new Range(l.line, 0, l.line, 0)),
hoverMessage: `${c.message}\n${c.author}, ${moment(c.date).format('MMMM Do, YYYY hh:MM a')}`,
renderOptions: { before: { contentText: `${l.sha.substring(0, 8)}`, } }
};
});
this.editor.setDecorations(blameDecoration, blameDecorationOptions);
sha = sha || blame.commits.values().next().value.sha;
// Add the bogus diagnostics to provide code actions for this sha
const activeLine = this.editor.selection.active.line;
this._diagnostics.clear();
this._diagnostics.set(this.editor.document.uri, [this._getDiagnostic(this.editor, activeLine, sha)]);
return this.applyHighlight(sha);
});
}
applyHighlight(sha: string) {
return this._blame.then(blame => {
if (!blame.lines.length) return;
const highlightDecorationRanges = blame.lines
.filter(l => l.sha === sha)
.map(l => this.editor.document.validateRange(new Range(l.line, 0, l.line, 1000000)));
this.editor.setDecorations(highlightDecoration, highlightDecorationRanges);
});
}
}

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

@@ -0,0 +1,39 @@
'use strict';
import {CancellationToken, CodeActionContext, CodeActionProvider, Command, DocumentSelector, ExtensionContext, Range, TextDocument, Uri, window} from 'vscode';
import {Commands, DocumentSchemes} from './constants';
import GitProvider from './gitProvider';
import {DiagnosticSource} from './constants';
export default class GitCodeActionProvider implements CodeActionProvider {
static selector: DocumentSelector = { scheme: DocumentSchemes.File };
constructor(context: ExtensionContext, private git: GitProvider) { }
provideCodeActions(document: TextDocument, range: Range, context: CodeActionContext, token: CancellationToken): Command[] | Thenable<Command[]> {
if (!context.diagnostics.some(d => d.source === DiagnosticSource)) {
return [];
}
return this.git.getBlameForLine(document.fileName, range.start.line)
.then(blame => {
const actions: Command[] = [];
if (blame.commit.sha) {
actions.push({
title: `GitLens: Diff ${blame.commit.sha} with working tree`,
command: Commands.DiffWithWorking,
arguments: [Uri.file(document.fileName), blame.commit.sha, blame.line.line]
});
}
if (blame.commit.sha && blame.commit.previousSha) {
actions.push({
title: `GitLens: Diff ${blame.commit.sha} with previous ${blame.commit.previousSha}`,
command: Commands.DiffWithPrevious,
arguments: [Uri.file(document.fileName), blame.commit.sha, blame.commit.previousSha, blame.line.line]
});
}
return actions;
});
}
}

156
src/gitCodeLensProvider.ts Normal file
View File

@@ -0,0 +1,156 @@
'use strict';
import {CancellationToken, CodeLens, CodeLensProvider, commands, DocumentSelector, ExtensionContext, Location, Position, Range, SymbolInformation, SymbolKind, TextDocument, Uri, window} from 'vscode';
import {BuiltInCommands, Commands, DocumentSchemes, WorkspaceState} from './constants';
import GitProvider, {IGitBlame, IGitBlameLines, IGitCommit} from './gitProvider';
import * as moment from 'moment';
export class GitRecentChangeCodeLens extends CodeLens {
constructor(private git: GitProvider, public fileName: string, public blameRange: Range, range: Range) {
super(range);
}
getBlame(): Promise<IGitBlameLines> {
return this.git.getBlameForRange(this.fileName, this.blameRange);
}
}
export class GitBlameCodeLens extends CodeLens {
constructor(private git: GitProvider, public fileName: string, public blameRange: Range, range: Range) {
super(range);
}
getBlame(): Promise<IGitBlameLines> {
return this.git.getBlameForRange(this.fileName, this.blameRange);
}
}
// export class GitHistoryCodeLens extends CodeLens {
// constructor(public repoPath: string, public fileName: string, range: Range) {
// super(range);
// }
// }
export default class GitCodeLensProvider implements CodeLensProvider {
static selector: DocumentSelector = { scheme: DocumentSchemes.File };
// private hasGitHistoryExtension: boolean;
constructor(context: ExtensionContext, private git: GitProvider) {
// this.hasGitHistoryExtension = context.workspaceState.get(WorkspaceState.HasGitHistoryExtension, false);
}
provideCodeLenses(document: TextDocument, token: CancellationToken): CodeLens[] | Thenable<CodeLens[]> {
const fileName = document.fileName;
const promise = Promise.all([this.git.getBlameForFile(fileName) as Promise<any>, (commands.executeCommand(BuiltInCommands.ExecuteDocumentSymbolProvider, document.uri) as Promise<any>)]);
return promise.then(values => {
const blame = values[0] as IGitBlame;
if (!blame || !blame.lines.length) return [];
const symbols = values[1] as SymbolInformation[];
const lenses: CodeLens[] = [];
symbols.forEach(sym => this._provideCodeLens(fileName, 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 blameRange = document.validateRange(new Range(0, 1000000, 1000000, 1000000));
lenses.push(new GitRecentChangeCodeLens(this.git, fileName, blameRange, new Range(0, 0, 0, blameRange.start.character)));
lenses.push(new GitBlameCodeLens(this.git, fileName, blameRange, new Range(0, 1, 0, blameRange.start.character)));
// if (this.hasGitHistoryExtension) {
// lenses.push(new GitHistoryCodeLens(this.git.repoPath, fileName, new Range(0, 1, 0, blameRange.start.character)));
// }
}
return lenses;
});
}
private _provideCodeLens(fileName: string, document: TextDocument, symbol: SymbolInformation, lenses: CodeLens[]): void {
let multiline = false;
switch (symbol.kind) {
case SymbolKind.Package:
case SymbolKind.Module:
case SymbolKind.Class:
case SymbolKind.Interface:
case SymbolKind.Constructor:
case SymbolKind.Method:
case SymbolKind.Function:
case SymbolKind.Enum:
multiline = true;
break;
case SymbolKind.Property:
multiline = (symbol.location.range.end.line - symbol.location.range.start.line) > 1;
break;
case SymbolKind.Field:
multiline = false;
break;
default:
return;
}
const line = document.lineAt(symbol.location.range.start);
if (lenses.length && lenses[lenses.length - 1].range.start.line === line.lineNumber) {
return;
}
let startChar = line.text.search(`\\b${symbol.name}\\b`); //line.firstNonWhitespaceCharacterIndex;
if (startChar === -1) {
startChar = line.firstNonWhitespaceCharacterIndex;
} else {
startChar += Math.floor(symbol.name.length / 2);
}
lenses.push(new GitRecentChangeCodeLens(this.git, fileName, symbol.location.range, line.range.with(new Position(line.range.start.line, startChar))));
startChar++;
if (multiline) {
lenses.push(new GitBlameCodeLens(this.git, fileName, symbol.location.range, line.range.with(new Position(line.range.start.line, startChar))));
startChar++;
}
// if (this.hasGitHistoryExtension) {
// lenses.push(new GitHistoryCodeLens(this.git.repoPath, fileName, line.range.with(new Position(line.range.start.line, startChar))));
// }
}
resolveCodeLens(lens: CodeLens, token: CancellationToken): Thenable<CodeLens> {
if (lens instanceof GitRecentChangeCodeLens) return this._resolveGitRecentChangeCodeLens(lens, token);
if (lens instanceof GitBlameCodeLens) return this._resolveGitBlameCodeLens(lens, token);
// if (lens instanceof GitHistoryCodeLens) return this._resolveGitHistoryCodeLens(lens, token);
}
_resolveGitRecentChangeCodeLens(lens: GitRecentChangeCodeLens, token: CancellationToken): Thenable<CodeLens> {
return lens.getBlame().then(blame => {
const recentCommit = blame.commits.values().next().value;
lens.command = {
title: `${recentCommit.author}, ${moment(recentCommit.date).fromNow()}`, // - lines(${lens.blameRange.start.line + 1}-${lens.blameRange.end.line + 1})`,
command: Commands.ShowBlameHistory,
arguments: [Uri.file(lens.fileName), lens.blameRange, lens.range.start]
};
return lens;
});
}
_resolveGitBlameCodeLens(lens: GitBlameCodeLens, token: CancellationToken): Thenable<CodeLens> {
return lens.getBlame().then(blame => {
const editor = window.activeTextEditor;
const activeLine = editor.selection.active.line;
const count = blame.authors.size;
lens.command = {
title: `${count} ${count > 1 ? 'authors' : 'author'} (${blame.authors.values().next().value.name}${count > 1 ? ' and others' : ''})`,
command: Commands.ToggleBlame,
arguments: [Uri.file(lens.fileName), blame.allLines[activeLine].sha]
};
return lens;
});
}
// _resolveGitHistoryCodeLens(lens: GitHistoryCodeLens, token: CancellationToken): Thenable<CodeLens> {
// // TODO: Play with this more -- get this to open the correct diff to the right place
// lens.command = {
// title: `View History`,
// command: 'git.viewFileHistory', // viewLineHistory
// arguments: [Uri.file(lens.fileName)]
// };
// return Promise.resolve(lens);
// }
}

15
src/gitContentProvider.ts Normal file
View File

@@ -0,0 +1,15 @@
'use strict';
import {ExtensionContext, TextDocumentContentProvider, Uri} from 'vscode';
import {DocumentSchemes} from './constants';
import GitProvider from './gitProvider';
export default class GitContentProvider implements TextDocumentContentProvider {
static scheme = DocumentSchemes.Git;
constructor(context: ExtensionContext, private git: GitProvider) { }
provideTextDocumentContent(uri: Uri): string | Thenable<string> {
const data = this.git.fromGitUri(uri);
return this.git.getVersionedFileText(data.originalFileName || data.fileName, data.sha);
}
}

391
src/gitProvider.ts Normal file
View File

@@ -0,0 +1,391 @@
'use strict'
import {Disposable, ExtensionContext, languages, Location, Position, Range, Uri, workspace} from 'vscode';
import {DocumentSchemes, WorkspaceState} from './constants';
import GitCodeLensProvider from './gitCodeLensProvider';
import Git from './git';
import {basename, dirname, extname} from 'path';
import * as moment from 'moment';
import * as _ from 'lodash';
const commitMessageMatcher = /^([\^0-9a-fA-F]{7})\s(.*)$/gm;
const blamePorcelainMatcher = /^([\^0-9a-fA-F]{40})\s([0-9]+)\s([0-9]+)(?:\s([0-9]+))?$\n(?:^author\s(.*)$\n^author-mail\s(.*)$\n^author-time\s(.*)$\n^author-tz\s(.*)$\n^committer\s(.*)$\n^committer-mail\s(.*)$\n^committer-time\s(.*)$\n^committer-tz\s(.*)$\n^summary\s(.*)$\n(?:^previous\s(.*)?\s(.*)$\n)?^filename\s(.*)$\n)?^(.*)$/gm;
export default class GitProvider extends Disposable {
public repoPath: string;
private _blames: Map<string, Promise<IGitBlame>>;
private _disposable: Disposable;
private _codeLensProviderSubscription: Disposable;
// TODO: Needs to be a Map so it can debounce per file
private _clearCacheFn: ((string, boolean) => void) & _.Cancelable;
constructor(private context: ExtensionContext) {
super(() => this.dispose());
this.repoPath = context.workspaceState.get(WorkspaceState.RepoPath) as string;
// TODO: Cache needs to be cleared on file changes -- createFileSystemWatcher or timeout?
this._blames = new Map();
this._registerCodeLensProvider();
this._clearCacheFn = _.debounce(this._clearBlame.bind(this), 2500);
const subscriptions: Disposable[] = [];
subscriptions.push(workspace.onDidCloseTextDocument(d => this._clearBlame(d.fileName)));
subscriptions.push(workspace.onDidSaveTextDocument(d => this._clearCacheFn(d.fileName, true)));
subscriptions.push(workspace.onDidChangeTextDocument(e => this._clearCacheFn(e.document.fileName, false)));
this._disposable = Disposable.from(...subscriptions);
}
dispose() {
this._blames.clear();
this._disposable && this._disposable.dispose();
this._codeLensProviderSubscription && this._codeLensProviderSubscription.dispose();
}
private _registerCodeLensProvider() {
if (this._codeLensProviderSubscription) {
this._codeLensProviderSubscription.dispose();
}
this._codeLensProviderSubscription = languages.registerCodeLensProvider(GitCodeLensProvider.selector, new GitCodeLensProvider(this.context, this));
}
private _clearBlame(fileName: string, reset?: boolean) {
fileName = Git.normalizePath(fileName, this.repoPath);
reset = !!reset;
if (this._blames.delete(fileName.toLowerCase())) {
console.log(`GitProvider._clearBlame(${fileName}, ${reset})`);
if (reset) {
// TODO: Killing the code lens provider is too drastic -- makes the editor jump around, need to figure out how to trigger a refresh
//this._registerCodeLensProvider();
}
}
}
getRepoPath(cwd: string) {
return Git.repoPath(cwd);
}
getBlameForFile(fileName: string) {
fileName = Git.normalizePath(fileName, this.repoPath);
let blame = this._blames.get(fileName.toLowerCase());
if (blame !== undefined) return blame;
blame = Git.blamePorcelain(fileName, this.repoPath)
.then(data => {
const authors: Map<string, IGitAuthor> = new Map();
const commits: Map<string, IGitCommit> = new Map();
const lines: Array<IGitCommitLine> = [];
let m: Array<string>;
while ((m = blamePorcelainMatcher.exec(data)) != null) {
const sha = m[1].substring(0, 8);
let commit = commits.get(sha);
if (!commit) {
const authorName = m[5].trim();
let author = authors.get(authorName);
if (!author) {
author = {
name: authorName,
lineCount: 0
};
authors.set(authorName, author);
}
commit = {
sha,
fileName: fileName,
author: authorName,
date: moment(`${m[7]} ${m[8]}`, 'X Z').toDate(),
message: m[13],
lines: []
};
const originalFileName = m[16];
if (!fileName.toLowerCase().endsWith(originalFileName.toLowerCase())) {
commit.originalFileName = originalFileName;
}
const previousSha = m[14];
if (previousSha) {
commit.previousSha = previousSha.substring(0, 8);
commit.previousFileName = m[15];
}
commits.set(sha, commit);
}
const line: IGitCommitLine = {
sha,
line: parseInt(m[3], 10) - 1,
originalLine: parseInt(m[2], 10) - 1
//code: m[17]
}
commit.lines.push(line);
lines.push(line);
}
commits.forEach(c => authors.get(c.author).lineCount += c.lines.length);
const sortedAuthors: Map<string, IGitAuthor> = new Map();
const values = Array.from(authors.values())
.sort((a, b) => b.lineCount - a.lineCount)
.forEach(a => sortedAuthors.set(a.name, a));
const sortedCommits: Map<string, IGitCommit> = new Map();
Array.from(commits.values())
.sort((a, b) => b.date.getTime() - a.date.getTime())
.forEach(c => sortedCommits.set(c.sha, c));
return {
authors: sortedAuthors,
commits: sortedCommits,
lines: lines
};
});
this._blames.set(fileName.toLowerCase(), blame);
return blame;
}
getBlameForLine(fileName: string, line: number): Promise<IGitBlameLine> {
return this.getBlameForFile(fileName).then(blame => {
const blameLine = blame.lines[line];
const commit = blame.commits.get(blameLine.sha);
return {
author: Object.assign({}, blame.authors.get(commit.author), { lineCount: commit.lines.length }),
commit: commit,
line: blameLine
};
});
}
getBlameForRange(fileName: string, range: Range): Promise<IGitBlameLines> {
return this.getBlameForFile(fileName).then(blame => {
if (!blame.lines.length) return Object.assign({ allLines: blame.lines }, blame);
if (range.start.line === 0 && range.end.line === blame.lines.length - 1) {
return Object.assign({ allLines: blame.lines }, blame);
}
const lines = blame.lines.slice(range.start.line, range.end.line + 1);
const shas: Set<string> = new Set();
lines.forEach(l => shas.add(l.sha));
const authors: Map<string, IGitAuthor> = new Map();
const commits: Map<string, IGitCommit> = new Map();
blame.commits.forEach(c => {
if (!shas.has(c.sha)) return;
const commit: IGitCommit = Object.assign({}, c, { lines: c.lines.filter(l => l.line >= range.start.line && l.line <= range.end.line) });
commits.set(c.sha, commit);
let author = authors.get(commit.author);
if (!author) {
author = {
name: commit.author,
lineCount: 0
};
authors.set(author.name, author);
}
author.lineCount += commit.lines.length;
});
const sortedAuthors: Map<string, IGitAuthor> = new Map();
Array.from(authors.values())
.sort((a, b) => b.lineCount - a.lineCount)
.forEach(a => sortedAuthors.set(a.name, a));
return {
authors: sortedAuthors,
commits: commits,
lines: lines,
allLines: blame.lines
};
});
}
getBlameForShaRange(fileName: string, sha: string, range: Range): Promise<IGitBlameCommitLines> {
return this.getBlameForFile(fileName).then(blame => {
const lines = blame.lines.slice(range.start.line, range.end.line + 1).filter(l => l.sha === sha);
const commit = Object.assign({}, blame.commits.get(sha), { lines: lines });
return {
author: Object.assign({}, blame.authors.get(commit.author), { lineCount: commit.lines.length }),
commit: commit,
lines: lines
};
});
}
getBlameLocations(fileName: string, range: Range) {
return this.getBlameForRange(fileName, range).then(blame => {
const commitCount = blame.commits.size;
const locations: Array<Location> = [];
Array.from(blame.commits.values())
.forEach((c, i) => {
const uri = this.toBlameUri(c, i + 1, commitCount, range);
c.lines.forEach(l => locations.push(new Location(c.originalFileName
? this.toBlameUri(c, i + 1, commitCount, range, c.originalFileName)
: uri,
new Position(l.originalLine, 0))));
});
return locations;
});
}
// getHistoryLocations(fileName: string, range: Range) {
// return this.getBlameForRange(fileName, range).then(blame => {
// const commitCount = blame.commits.size;
// const locations: Array<Location> = [];
// Array.from(blame.commits.values())
// .forEach((c, i) => {
// const uri = this.toBlameUri(c, i + 1, commitCount, range);
// c.lines.forEach(l => locations.push(new Location(c.originalFileName
// ? this.toBlameUri(c, i + 1, commitCount, range, c.originalFileName)
// : uri,
// new Position(l.originalLine, 0))));
// });
// return locations;
// });
// }
// getCommitMessage(sha: string) {
// return Git.getCommitMessage(sha, this.repoPath);
// }
// getCommitMessages(fileName: string) {
// return Git.getCommitMessages(fileName, this.repoPath).then(data => {
// const commits: Map<string, string> = new Map();
// let m: Array<string>;
// while ((m = commitMessageMatcher.exec(data)) != null) {
// commits.set(m[1], m[2]);
// }
// return commits;
// });
// }
getVersionedFile(fileName: string, sha: string) {
return Git.getVersionedFile(fileName, this.repoPath, sha);
}
getVersionedFileText(fileName: string, sha: string) {
return Git.getVersionedFileText(fileName, this.repoPath, sha);
}
fromBlameUri(uri: Uri): IGitBlameUriData {
if (uri.scheme !== DocumentSchemes.GitBlame) throw new Error(`fromGitUri(uri=${uri}) invalid scheme`);
const data = this._fromGitUri<IGitBlameUriData>(uri);
data.range = new Range(data.range[0].line, data.range[0].character, data.range[1].line, data.range[1].character);
return data;
}
fromGitUri(uri: Uri) {
if (uri.scheme !== DocumentSchemes.Git) throw new Error(`fromGitUri(uri=${uri}) invalid scheme`);
return this._fromGitUri<IGitUriData>(uri);
}
private _fromGitUri<T extends IGitUriData>(uri: Uri): T {
return JSON.parse(uri.query) as T;
}
toBlameUri(commit: IGitCommit, index: number, commitCount: number, range: Range, originalFileName?: string) {
return this._toGitUri(DocumentSchemes.GitBlame, commit, commitCount, this._toGitBlameUriData(commit, index, range, originalFileName));
}
toGitUri(commit: IGitCommit, index: number, commitCount: number, originalFileName?: string) {
return this._toGitUri(DocumentSchemes.Git, commit, commitCount, this._toGitUriData(commit, index, originalFileName));
}
private _toGitUri(scheme: DocumentSchemes, commit: IGitCommit, commitCount: number, data: IGitUriData | IGitBlameUriData) {
const pad = n => ("0000000" + n).slice(-("" + commitCount).length);
const ext = extname(data.fileName);
const path = `${dirname(data.fileName)}/${commit.sha}: ${basename(data.fileName, ext)}${ext}`;
// NOTE: Need to specify an index here, since I can't control the sort order -- just alphabetic or by file location
return Uri.parse(`${scheme}:${pad(data.index)}. ${commit.author}, ${moment(commit.date).format('MMM D, YYYY hh:MM a')} - ${path}?${JSON.stringify(data)}`);
}
private _toGitUriData<T extends IGitUriData>(commit: IGitCommit, index: number, originalFileName?: string): T {
const fileName = originalFileName || commit.fileName;
const data = { fileName: commit.fileName, sha: commit.sha, index: index } as T;
if (originalFileName) {
data.originalFileName = originalFileName;
}
return data;
}
private _toGitBlameUriData(commit: IGitCommit, index: number, range: Range, originalFileName?: string) {
const data = this._toGitUriData<IGitBlameUriData>(commit, index, originalFileName);
data.range = range;
return data;
}
}
export interface IGitBlame {
authors: Map<string, IGitAuthor>;
commits: Map<string, IGitCommit>;
lines: IGitCommitLine[];
}
export interface IGitBlameLine {
author: IGitAuthor;
commit: IGitCommit;
line: IGitCommitLine;
}
export interface IGitBlameLines extends IGitBlame {
allLines: IGitCommitLine[];
}
export interface IGitBlameCommitLines {
author: IGitAuthor;
commit: IGitCommit;
lines: IGitCommitLine[];
}
export interface IGitAuthor {
name: string;
lineCount: number;
}
export interface IGitCommit {
sha: string;
fileName: string;
author: string;
date: Date;
message: string;
lines: IGitCommitLine[];
originalFileName?: string;
previousSha?: string;
previousFileName?: string;
}
export interface IGitCommitLine {
sha: string;
line: number;
originalLine: number;
code?: string;
}
export interface IGitUriData {
fileName: string,
originalFileName?: string;
sha: string,
index: number
}
export interface IGitBlameUriData extends IGitUriData {
range: Range
}

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"
}
}