mirror of
https://github.com/ckaczor/vscode-gitlens.git
synced 2026-02-12 11:08:34 -05:00
Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ea33560f14 | ||
|
|
70cc92ddd6 | ||
|
|
0e064f15c7 | ||
|
|
9964ea691b | ||
|
|
92beca2542 |
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "gitlens",
|
||||
"version": "0.0.2",
|
||||
"version": "0.0.3",
|
||||
"author": "Eric Amodio",
|
||||
"publisher": "eamodio",
|
||||
"engines": {
|
||||
@@ -41,9 +41,6 @@
|
||||
"typescript": "^1.8.10",
|
||||
"vscode": "^0.11.17"
|
||||
},
|
||||
"extensionDependencies": [
|
||||
"donjayamanne.githistory"
|
||||
],
|
||||
"scripts": {
|
||||
"vscode:prepublish": "node ./node_modules/vscode/bin/compile",
|
||||
"compile": "node ./node_modules/vscode/bin/compile -watch -p ./",
|
||||
|
||||
74
src/commands.ts
Normal file
74
src/commands.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
'use strict'
|
||||
import {commands, Disposable, Position, Range, Uri, window} from 'vscode';
|
||||
import {Commands, VsCodeCommands} from './constants';
|
||||
import GitProvider from './gitProvider';
|
||||
import {basename} from 'path';
|
||||
|
||||
abstract class Command extends Disposable {
|
||||
private _subscriptions: Disposable;
|
||||
|
||||
constructor(command: Commands) {
|
||||
super(() => this.dispose());
|
||||
this._subscriptions = commands.registerCommand(command, this.execute.bind(this));
|
||||
}
|
||||
|
||||
dispose() {
|
||||
this._subscriptions && this._subscriptions.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
abstract execute(...args): any;
|
||||
}
|
||||
|
||||
export class BlameCommand extends Command {
|
||||
constructor(private git: GitProvider) {
|
||||
super(Commands.ShowBlameHistory);
|
||||
}
|
||||
|
||||
execute(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 = window.activeTextEditor && window.activeTextEditor.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(VsCodeCommands.ShowReferences, uri, position, locations);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export class DiffWithPreviousCommand extends Command {
|
||||
constructor(private git: GitProvider) {
|
||||
super(Commands.DiffWithPrevious);
|
||||
}
|
||||
|
||||
execute(uri?: Uri, sha?: string, compareWithSha?: string) {
|
||||
// TODO: Execute these in parallel rather than series
|
||||
return this.git.getVersionedFile(uri.path, sha).then(source => {
|
||||
this.git.getVersionedFile(uri.path, compareWithSha).then(compare => {
|
||||
const fileName = basename(uri.path);
|
||||
return commands.executeCommand(VsCodeCommands.Diff, Uri.file(source), Uri.file(compare), `${fileName} (${sha}) ↔ ${fileName} (${compareWithSha})`);
|
||||
})
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export class DiffWithWorkingCommand extends Command {
|
||||
constructor(private git: GitProvider) {
|
||||
super(Commands.DiffWithWorking);
|
||||
}
|
||||
|
||||
execute(uri?: Uri, sha?: string) {
|
||||
return this.git.getVersionedFile(uri.path, sha).then(compare => {
|
||||
const fileName = basename(uri.path);
|
||||
return commands.executeCommand(VsCodeCommands.Diff, uri, Uri.file(compare), `${fileName} (index) ↔ ${fileName} (${sha})`);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,22 +1,29 @@
|
||||
export type WorkspaceState = 'repoPath';
|
||||
'use strict'
|
||||
|
||||
export type WorkspaceState = 'hasGitHistoryExtension' | 'repoPath';
|
||||
export const WorkspaceState = {
|
||||
HasGitHistoryExtension: 'hasGitHistoryExtension' as WorkspaceState,
|
||||
RepoPath: 'repoPath' as WorkspaceState
|
||||
}
|
||||
|
||||
export const RepoPath: string = 'repoPath';
|
||||
|
||||
export type Commands = 'git.action.showBlameHistory';
|
||||
export type Commands = 'git.action.diffWithPrevious' | 'git.action.diffWithWorking' | 'git.action.showBlameHistory';
|
||||
export const Commands = {
|
||||
DiffWithPrevious: 'git.action.diffWithPrevious' as Commands,
|
||||
DiffWithWorking: 'git.action.diffWithWorking' as Commands,
|
||||
ShowBlameHistory: 'git.action.showBlameHistory' as Commands
|
||||
}
|
||||
|
||||
export type DocumentSchemes = 'gitblame';
|
||||
export type DocumentSchemes = 'file' | 'gitblame';
|
||||
export const DocumentSchemes = {
|
||||
File: 'file' as DocumentSchemes,
|
||||
GitBlame: 'gitblame' as DocumentSchemes
|
||||
}
|
||||
|
||||
export type VsCodeCommands = 'vscode.executeDocumentSymbolProvider' | 'vscode.executeCodeLensProvider' | 'editor.action.showReferences';
|
||||
export type VsCodeCommands = 'vscode.diff' | 'vscode.executeDocumentSymbolProvider' | 'vscode.executeCodeLensProvider' | 'editor.action.showReferences';
|
||||
export const VsCodeCommands = {
|
||||
Diff: 'vscode.diff' as VsCodeCommands,
|
||||
ExecuteDocumentSymbolProvider: 'vscode.executeDocumentSymbolProvider' as VsCodeCommands,
|
||||
ExecuteCodeLensProvider: 'vscode.executeCodeLensProvider' as VsCodeCommands,
|
||||
ShowReferences: 'editor.action.showReferences' as VsCodeCommands
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
'use strict';
|
||||
import {CodeLens, commands, DocumentSelector, ExtensionContext, languages, Range, Uri, window, workspace} from 'vscode';
|
||||
import GitCodeLensProvider, {GitBlameCodeLens} from './codeLensProvider';
|
||||
import GitContentProvider from './contentProvider';
|
||||
import {gitRepoPath} from './git';
|
||||
import GitBlameProvider from './gitBlameProvider';
|
||||
import {Commands, VsCodeCommands, WorkspaceState} from './constants';
|
||||
import {CodeLens, DocumentSelector, ExtensionContext, extensions, languages, workspace} from 'vscode';
|
||||
import GitCodeLensProvider from './gitCodeLensProvider';
|
||||
import GitBlameCodeLensProvider from './gitBlameCodeLensProvider';
|
||||
import GitBlameContentProvider from './gitBlameContentProvider';
|
||||
import GitProvider from './gitProvider';
|
||||
import {BlameCommand, DiffWithPreviousCommand, DiffWithWorkingCommand} from './commands';
|
||||
import {WorkspaceState} from './constants';
|
||||
|
||||
// this method is called when your extension is activated
|
||||
export function activate(context: ExtensionContext) {
|
||||
@@ -16,33 +17,20 @@ export function activate(context: ExtensionContext) {
|
||||
}
|
||||
|
||||
console.log(`GitLens active: ${workspace.rootPath}`);
|
||||
gitRepoPath(workspace.rootPath).then(repoPath => {
|
||||
|
||||
const git = new GitProvider(context);
|
||||
context.subscriptions.push(git);
|
||||
|
||||
git.getRepoPath(workspace.rootPath).then(repoPath => {
|
||||
context.workspaceState.update(WorkspaceState.RepoPath, repoPath);
|
||||
context.workspaceState.update(WorkspaceState.HasGitHistoryExtension, extensions.getExtension('donjayamanne.githistory') !== undefined);
|
||||
|
||||
const blameProvider = new GitBlameProvider(context);
|
||||
context.subscriptions.push(blameProvider);
|
||||
|
||||
context.subscriptions.push(workspace.registerTextDocumentContentProvider(GitContentProvider.scheme, new GitContentProvider(context, blameProvider)));
|
||||
|
||||
context.subscriptions.push(commands.registerCommand(Commands.ShowBlameHistory, (uri: Uri, blameRange?: Range, range?: Range) => {
|
||||
if (!uri) {
|
||||
const doc = window.activeTextEditor && window.activeTextEditor.document;
|
||||
if (doc) {
|
||||
uri = doc.uri;
|
||||
blameRange = doc.validateRange(new Range(0, 0, 1000000, 1000000));
|
||||
range = doc.validateRange(new Range(0, 0, 0, 1000000));
|
||||
}
|
||||
|
||||
if (!uri) return;
|
||||
}
|
||||
|
||||
return blameProvider.getBlameLocations(uri.path, blameRange).then(locations => {
|
||||
return commands.executeCommand(VsCodeCommands.ShowReferences, uri, range, locations);
|
||||
});
|
||||
}));
|
||||
|
||||
const selector: DocumentSelector = { scheme: 'file' };
|
||||
context.subscriptions.push(languages.registerCodeLensProvider(selector, new GitCodeLensProvider(context, blameProvider)));
|
||||
context.subscriptions.push(workspace.registerTextDocumentContentProvider(GitBlameContentProvider.scheme, new GitBlameContentProvider(context, git)));
|
||||
context.subscriptions.push(languages.registerCodeLensProvider(GitCodeLensProvider.selector, new GitCodeLensProvider(context, git)));
|
||||
context.subscriptions.push(languages.registerCodeLensProvider(GitBlameCodeLensProvider.selector, new GitBlameCodeLensProvider(context, git)));
|
||||
context.subscriptions.push(new BlameCommand(git));
|
||||
context.subscriptions.push(new DiffWithPreviousCommand(git));
|
||||
context.subscriptions.push(new DiffWithWorkingCommand(git));
|
||||
}).catch(reason => console.warn(reason));
|
||||
}
|
||||
|
||||
|
||||
89
src/git.ts
89
src/git.ts
@@ -1,53 +1,78 @@
|
||||
'use strict';
|
||||
import {basename, dirname, extname, relative} from 'path';
|
||||
import {basename, dirname, extname, isAbsolute, relative} from 'path';
|
||||
import * as fs from 'fs';
|
||||
import * as tmp from 'tmp';
|
||||
import {spawnPromise} from 'spawn-rx';
|
||||
|
||||
export function gitRepoPath(cwd) {
|
||||
return gitCommand(cwd, 'rev-parse', '--show-toplevel').then(data => data.replace(/\r?\n|\r/g, ''));
|
||||
function gitCommand(cwd: string, ...args) {
|
||||
return spawnPromise('git', args, { cwd: cwd });
|
||||
}
|
||||
|
||||
export function gitBlame(fileName: string) {
|
||||
console.log('git', 'blame', '-fnw', '--root', '--', fileName);
|
||||
return gitCommand(dirname(fileName), 'blame', '-fnw', '--root', '--', fileName);
|
||||
}
|
||||
export default class Git {
|
||||
static normalizePath(fileName: string, repoPath: string) {
|
||||
fileName = fileName.replace(/\\/g, '/');
|
||||
return isAbsolute(fileName) ? relative(repoPath, fileName) : fileName;
|
||||
}
|
||||
|
||||
export function gitGetVersionFile(fileName: string, repoPath: string, sha: string) {
|
||||
return new Promise<string>((resolve, reject) => {
|
||||
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;
|
||||
}
|
||||
static repoPath(cwd: string) {
|
||||
return gitCommand(cwd, 'rev-parse', '--show-toplevel').then(data => data.replace(/\r?\n|\r/g, ''));
|
||||
}
|
||||
|
||||
console.log("File: ", destination);
|
||||
console.log("Filedescriptor: ", fd);
|
||||
static blame(fileName: string, repoPath: string, sha?: string) {
|
||||
fileName = Git.normalizePath(fileName, repoPath);
|
||||
|
||||
fs.appendFile(destination, data, err => {
|
||||
if (sha) {
|
||||
console.log('git', 'blame', '-fnw', '--root', `${sha}^`, '--', fileName);
|
||||
return gitCommand(repoPath, 'blame', '-fnw', '--root', `${sha}^`, '--', fileName);
|
||||
}
|
||||
|
||||
console.log('git', 'blame', '-fnw', '--root', '--', fileName);
|
||||
return gitCommand(repoPath, 'blame', '-fnw', '--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) {
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
resolve(destination);
|
||||
|
||||
console.log("File: ", destination);
|
||||
console.log("Filedescriptor: ", fd);
|
||||
|
||||
fs.appendFile(destination, data, err => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
resolve(destination);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
static getVersionedFileText(fileName: string, repoPath: string, sha: string) {
|
||||
fileName = Git.normalizePath(fileName, repoPath);
|
||||
sha = sha.replace('^', '');
|
||||
|
||||
function normalizeArgument(fileName: string, repoPath: string, sha: string) {
|
||||
return `${sha.replace('^', '')}:${relative(repoPath, fileName.replace(/\\/g, '/'))}`;
|
||||
}
|
||||
console.log('git', 'show', `${sha}:${fileName}`);
|
||||
return gitCommand(repoPath, 'show', `${sha}:${fileName}`);
|
||||
// .then(s => { console.log(s); return s; })
|
||||
// .catch(ex => console.error(ex));
|
||||
}
|
||||
|
||||
function gitCommand(cwd: string, ...args) {
|
||||
return spawnPromise('git', args, { cwd: cwd });
|
||||
static getCommitMessage(sha: string, repoPath: string) {
|
||||
sha = sha.replace('^', '');
|
||||
|
||||
console.log('git', 'show', '-s', '--format=%B', sha);
|
||||
return gitCommand(repoPath, 'show', '-s', '--format=%B', sha);
|
||||
// .then(s => { console.log(s); return s; })
|
||||
// .catch(ex => console.error(ex));
|
||||
}
|
||||
}
|
||||
87
src/gitBlameCodeLensProvider.ts
Normal file
87
src/gitBlameCodeLensProvider.ts
Normal file
@@ -0,0 +1,87 @@
|
||||
'use strict';
|
||||
import {CancellationToken, CodeLens, CodeLensProvider, commands, DocumentSelector, ExtensionContext, Location, Position, Range, SymbolInformation, SymbolKind, TextDocument, Uri} from 'vscode';
|
||||
import {Commands, DocumentSchemes, VsCodeCommands, WorkspaceState} from './constants';
|
||||
import GitProvider, {IGitBlame, IGitBlameCommit} 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;
|
||||
|
||||
return this.git.getBlameForFile(fileName).then(blame => {
|
||||
const commits = Array.from(blame.commits.values()).sort((a, b) => b.date.getTime() - a.date.getTime());
|
||||
let index = commits.findIndex(c => c.sha === data.sha) + 1;
|
||||
|
||||
let previousCommit: IGitBlameCommit;
|
||||
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 === data.sha);
|
||||
let lastLine = lines[0].originalLine;
|
||||
lines.forEach(l => {
|
||||
if (l.originalLine !== lastLine + 1) {
|
||||
lenses.push(new GitDiffWithWorkingTreeCodeLens(this.git, fileName, data.sha, new Range(l.originalLine, 0, l.originalLine, 1)));
|
||||
if (previousCommit) {
|
||||
lenses.push(new GitDiffWithPreviousCodeLens(this.git, fileName, data.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, data.sha, new Range(0, 0, 0, 1)));
|
||||
if (previousCommit) {
|
||||
lenses.push(new GitDiffWithPreviousCodeLens(this.git, fileName, data.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);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,7 @@
|
||||
'use strict';
|
||||
import {Disposable, EventEmitter, ExtensionContext, OverviewRulerLane, Range, TextEditor, TextEditorDecorationType, TextDocumentContentProvider, Uri, window, workspace} from 'vscode';
|
||||
import {DocumentSchemes, WorkspaceState} from './constants';
|
||||
import {gitGetVersionText} from './git';
|
||||
import GitBlameProvider, {IGitBlameUriData} from './gitBlameProvider';
|
||||
import GitProvider, {IGitBlameUriData} from './gitProvider';
|
||||
import * as moment from 'moment';
|
||||
|
||||
export default class GitBlameContentProvider implements TextDocumentContentProvider {
|
||||
@@ -12,7 +11,7 @@ export default class GitBlameContentProvider implements TextDocumentContentProvi
|
||||
private _onDidChange = new EventEmitter<Uri>();
|
||||
//private _subscriptions: Disposable;
|
||||
|
||||
constructor(context: ExtensionContext, public blameProvider: GitBlameProvider) {
|
||||
constructor(context: ExtensionContext, private git: GitProvider) {
|
||||
this._blameDecoration = window.createTextEditorDecorationType({
|
||||
dark: {
|
||||
backgroundColor: 'rgba(255, 255, 255, 0.15)',
|
||||
@@ -48,11 +47,11 @@ export default class GitBlameContentProvider implements TextDocumentContentProvi
|
||||
}
|
||||
|
||||
provideTextDocumentContent(uri: Uri): string | Thenable<string> {
|
||||
const data = GitBlameProvider.fromBlameUri(uri);
|
||||
const data = this.git.fromBlameUri(uri);
|
||||
|
||||
//const editor = this._findEditor(Uri.file(join(data.repoPath, data.file)));
|
||||
|
||||
return gitGetVersionText(data.fileName, this.blameProvider.repoPath, data.sha).then(text => {
|
||||
return this.git.getVersionedFileText(data.originalFileName || data.fileName, data.sha).then(text => {
|
||||
this.update(uri);
|
||||
|
||||
// TODO: This only works on the first load -- not after since it is cached
|
||||
@@ -64,7 +63,7 @@ export default class GitBlameContentProvider implements TextDocumentContentProvi
|
||||
return text;
|
||||
});
|
||||
|
||||
// return gitGetVersionFile(data.file, this.repoPath, data.sha).then(dst => {
|
||||
// return this.git.getVersionedFile(data.fileName, data.sha).then(dst => {
|
||||
// let uri = Uri.parse(`file:${dst}`)
|
||||
// return workspace.openTextDocument(uri).then(doc => {
|
||||
// this.update(uri);
|
||||
@@ -87,19 +86,21 @@ 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?
|
||||
let handle = setInterval(() => {
|
||||
let editor = this._findEditor(uri);
|
||||
if (editor) {
|
||||
clearInterval(handle);
|
||||
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}`
|
||||
};
|
||||
}));
|
||||
}
|
||||
});
|
||||
}
|
||||
if (!editor) return;
|
||||
|
||||
clearInterval(handle);
|
||||
this.git.getBlameForShaRange(data.fileName, data.sha, data.range).then(blame => {
|
||||
if (!blame.lines.length) return;
|
||||
|
||||
this.git.getCommitMessage(data.sha).then(msg => {
|
||||
editor.setDecorations(this._blameDecoration, blame.lines.map(l => {
|
||||
return {
|
||||
range: editor.document.validateRange(new Range(l.originalLine, 0, l.originalLine, 1000000)),
|
||||
hoverMessage: `${msg}\n${blame.commit.author}\n${moment(blame.commit.date).format('MMMM Do, YYYY hh:MM a')}\n${l.sha}`
|
||||
};
|
||||
}));
|
||||
})
|
||||
});
|
||||
}, 200);
|
||||
}
|
||||
|
||||
@@ -1,20 +1,16 @@
|
||||
'use strict';
|
||||
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 {CancellationToken, CodeLens, CodeLensProvider, commands, DocumentSelector, ExtensionContext, Location, Position, Range, SymbolInformation, SymbolKind, TextDocument, Uri} from 'vscode';
|
||||
import {Commands, DocumentSchemes, VsCodeCommands, WorkspaceState} from './constants';
|
||||
import GitProvider, {IGitBlame, IGitBlameCommit} from './gitProvider';
|
||||
import * as moment from 'moment';
|
||||
|
||||
export class GitBlameCodeLens extends CodeLens {
|
||||
constructor(private blameProvider: GitBlameProvider, public fileName: string, public blameRange: Range, range: Range) {
|
||||
export class GitCodeLens extends CodeLens {
|
||||
constructor(private git: GitProvider, public fileName: string, public blameRange: Range, range: Range) {
|
||||
super(range);
|
||||
}
|
||||
|
||||
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);
|
||||
return this.git.getBlameForRange(this.fileName, this.blameRange);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,33 +18,39 @@ export class GitHistoryCodeLens extends CodeLens {
|
||||
constructor(public repoPath: string, public fileName: string, range: Range) {
|
||||
super(range);
|
||||
}
|
||||
|
||||
// static toUri(lens: GitHistoryCodeLens, index: number): Uri {
|
||||
// return GitBlameProvider.toBlameUri(Object.assign({ repoPath: lens.repoPath, index: index, range: lens.blameRange, lines: lines }, line));
|
||||
// }
|
||||
}
|
||||
|
||||
export default class GitCodeLensProvider implements CodeLensProvider {
|
||||
constructor(context: ExtensionContext, public blameProvider: GitBlameProvider) { }
|
||||
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[]> {
|
||||
this.blameProvider.blameFile(document.fileName);
|
||||
const fileName = document.fileName;
|
||||
|
||||
this.git.getBlameForFile(fileName);
|
||||
|
||||
return (commands.executeCommand(VsCodeCommands.ExecuteDocumentSymbolProvider, document.uri) as Promise<SymbolInformation[]>).then(symbols => {
|
||||
let lenses: CodeLens[] = [];
|
||||
symbols.forEach(sym => this._provideCodeLens(document, sym, lenses));
|
||||
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 docRange = document.validateRange(new Range(0, 1000000, 1000000, 1000000));
|
||||
lenses.push(new GitBlameCodeLens(this.blameProvider, document.fileName, docRange, new Range(0, 0, 0, docRange.start.character)));
|
||||
lenses.push(new GitHistoryCodeLens(this.blameProvider.repoPath, document.fileName, docRange.with(new Position(docRange.start.line, docRange.start.character + 1))));
|
||||
const blameRange = document.validateRange(new Range(0, 1000000, 1000000, 1000000));
|
||||
lenses.push(new GitCodeLens(this.git, fileName, blameRange, new Range(0, 0, 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(document: TextDocument, symbol: SymbolInformation, lenses: CodeLens[]): void {
|
||||
private _provideCodeLens(fileName: string, document: TextDocument, symbol: SymbolInformation, lenses: CodeLens[]): void {
|
||||
switch (symbol.kind) {
|
||||
case SymbolKind.Package:
|
||||
case SymbolKind.Module:
|
||||
@@ -67,23 +69,25 @@ export default class GitCodeLensProvider implements CodeLensProvider {
|
||||
|
||||
const line = document.lineAt(symbol.location.range.start);
|
||||
|
||||
let startChar = line.text.indexOf(symbol.name); //line.firstNonWhitespaceCharacterIndex;
|
||||
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) - 1;
|
||||
startChar += Math.floor(symbol.name.length / 2);
|
||||
}
|
||||
|
||||
lenses.push(new GitBlameCodeLens(this.blameProvider, document.fileName, symbol.location.range, line.range.with(new Position(line.range.start.line, startChar))));
|
||||
lenses.push(new GitHistoryCodeLens(this.blameProvider.repoPath, document.fileName, line.range.with(new Position(line.range.start.line, startChar + 1))));
|
||||
lenses.push(new GitCodeLens(this.git, fileName, symbol.location.range, line.range.with(new Position(line.range.start.line, startChar))));
|
||||
if (this.hasGitHistoryExtension) {
|
||||
lenses.push(new GitHistoryCodeLens(this.git.repoPath, fileName, line.range.with(new Position(line.range.start.line, startChar + 1))));
|
||||
}
|
||||
}
|
||||
|
||||
resolveCodeLens(lens: CodeLens, token: CancellationToken): Thenable<CodeLens> {
|
||||
if (lens instanceof GitBlameCodeLens) return this._resolveGitBlameCodeLens(lens, token);
|
||||
if (lens instanceof GitCodeLens) return this._resolveGitBlameCodeLens(lens, token);
|
||||
if (lens instanceof GitHistoryCodeLens) return this._resolveGitHistoryCodeLens(lens, token);
|
||||
}
|
||||
|
||||
_resolveGitBlameCodeLens(lens: GitBlameCodeLens, token: CancellationToken): Thenable<CodeLens> {
|
||||
_resolveGitBlameCodeLens(lens: GitCodeLens, token: CancellationToken): Thenable<CodeLens> {
|
||||
return new Promise<CodeLens>((resolve, reject) => {
|
||||
lens.getBlame().then(blame => {
|
||||
if (!blame.lines.length) {
|
||||
@@ -94,9 +98,9 @@ export default class GitCodeLensProvider implements CodeLensProvider {
|
||||
|
||||
const recentCommit = Array.from(blame.commits.values()).sort((a, b) => b.date.getTime() - a.date.getTime())[0];
|
||||
lens.command = {
|
||||
title: `${recentCommit.author}, ${moment(recentCommit.date).fromNow()}`,
|
||||
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] //, lens.locations]
|
||||
arguments: [Uri.file(lens.fileName), lens.blameRange, lens.range.start]
|
||||
};
|
||||
resolve(lens);
|
||||
});
|
||||
@@ -112,4 +116,4 @@ export default class GitCodeLensProvider implements CodeLensProvider {
|
||||
};
|
||||
return Promise.resolve(lens);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,74 +1,94 @@
|
||||
'use strict'
|
||||
import {Disposable, ExtensionContext, Location, Position, Range, Uri, workspace} from 'vscode';
|
||||
import {DocumentSchemes, WorkspaceState} from './constants';
|
||||
import {gitBlame} from './git';
|
||||
import {basename, dirname, extname, join} from 'path';
|
||||
import Git from './git';
|
||||
import {basename, dirname, extname} 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 {
|
||||
export default class GitProvider extends Disposable {
|
||||
public repoPath: string;
|
||||
|
||||
private _files: Map<string, Promise<IGitBlame>>;
|
||||
private _subscriptions: Disposable;
|
||||
private _blames: Map<string, Promise<IGitBlame>>;
|
||||
private _subscription: Disposable;
|
||||
|
||||
constructor(context: ExtensionContext) {
|
||||
super(() => this.dispose());
|
||||
|
||||
this.repoPath = context.workspaceState.get(WorkspaceState.RepoPath) as string;
|
||||
|
||||
this._files = new Map();
|
||||
this._subscriptions = Disposable.from(workspace.onDidCloseTextDocument(d => this._removeFile(d.fileName)),
|
||||
workspace.onDidChangeTextDocument(e => this._removeFile(e.document.fileName)));
|
||||
this._blames = new Map();
|
||||
this._subscription = 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();
|
||||
this._blames.clear();
|
||||
this._subscription && this._subscription.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
blameFile(fileName: string) {
|
||||
let blame = this._files.get(fileName);
|
||||
private _removeFile(fileName: string) {
|
||||
this._blames.delete(fileName);
|
||||
}
|
||||
|
||||
getRepoPath(cwd: string) {
|
||||
return Git.repoPath(cwd);
|
||||
}
|
||||
|
||||
getCommitMessage(sha: string) {
|
||||
return Git.getCommitMessage(sha, this.repoPath);
|
||||
}
|
||||
|
||||
getBlameForFile(fileName: string) {
|
||||
fileName = Git.normalizePath(fileName, this.repoPath);
|
||||
|
||||
let blame = this._blames.get(fileName);
|
||||
if (blame !== undefined) return blame;
|
||||
|
||||
blame = gitBlame(fileName)
|
||||
blame = Git.blame(fileName, this.repoPath)
|
||||
.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(),
|
||||
fileName: fileName,
|
||||
author: m[4].trim(),
|
||||
date: new Date(m[5])
|
||||
});
|
||||
}
|
||||
|
||||
lines.push({
|
||||
const line: IGitBlameLine = {
|
||||
sha,
|
||||
line: parseInt(m[6], 10) - 1,
|
||||
originalLine: parseInt(m[3], 10) - 1,
|
||||
line: parseInt(m[6], 10) - 1
|
||||
//code: m[7]
|
||||
});
|
||||
}
|
||||
|
||||
let file = m[2].trim();
|
||||
if (!fileName.toLowerCase().endsWith(file.toLowerCase())) {
|
||||
line.originalFileName = file;
|
||||
}
|
||||
|
||||
lines.push(line);
|
||||
}
|
||||
|
||||
return { commits, lines };
|
||||
});
|
||||
// .catch(ex => {
|
||||
// console.error(ex);
|
||||
// });
|
||||
|
||||
this._files.set(fileName, blame);
|
||||
this._blames.set(fileName, blame);
|
||||
return blame;
|
||||
}
|
||||
|
||||
getBlameForRange(fileName: string, range: Range): Promise<IGitBlame> {
|
||||
return this.blameFile(fileName).then(blame => {
|
||||
return this.getBlameForFile(fileName).then(blame => {
|
||||
if (!blame.lines.length) return blame;
|
||||
|
||||
const lines = blame.lines.slice(range.start.line, range.end.line + 1);
|
||||
@@ -80,7 +100,7 @@ export default class GitBlameProvider extends Disposable {
|
||||
}
|
||||
|
||||
getBlameForShaRange(fileName: string, sha: string, range: Range): Promise<{commit: IGitBlameCommit, lines: IGitBlameLine[]}> {
|
||||
return this.blameFile(fileName).then(blame => {
|
||||
return this.getBlameForFile(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)
|
||||
@@ -96,31 +116,42 @@ export default class GitBlameProvider extends Disposable {
|
||||
Array.from(blame.commits.values())
|
||||
.sort((a, b) => b.date.getTime() - a.date.getTime())
|
||||
.forEach((c, i) => {
|
||||
const uri = GitBlameProvider.toBlameUri(this.repoPath, c, range, i + 1, commitCount);
|
||||
const uri = this.toBlameUri(c, range, i + 1, commitCount);
|
||||
blame.lines
|
||||
.filter(l => l.sha === c.sha)
|
||||
.forEach(l => locations.push(new Location(uri, new Position(l.originalLine, 0))));
|
||||
.forEach(l => locations.push(new Location(l.originalFileName
|
||||
? this.toBlameUri(c, range, i + 1, commitCount, l.originalFileName)
|
||||
: uri,
|
||||
new Position(l.originalLine, 0))));
|
||||
});
|
||||
|
||||
return locations;
|
||||
});
|
||||
}
|
||||
|
||||
private _removeFile(fileName: string) {
|
||||
this._files.delete(fileName);
|
||||
getVersionedFile(fileName: string, sha: string) {
|
||||
return Git.getVersionedFile(fileName, this.repoPath, sha);
|
||||
}
|
||||
|
||||
static toBlameUri(repoPath: string, commit: IGitBlameCommit, range: Range, index: number, commitCount: number) {
|
||||
getVersionedFileText(fileName: string, sha: string) {
|
||||
return Git.getVersionedFileText(fileName, this.repoPath, sha);
|
||||
}
|
||||
|
||||
toBlameUri(commit: IGitBlameCommit, range: Range, index: number, commitCount: number, originalFileName?: string) {
|
||||
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 };
|
||||
const fileName = originalFileName || commit.fileName;
|
||||
const ext = extname(fileName);
|
||||
const path = `${dirname(fileName)}/${commit.sha}: ${basename(fileName, ext)}${ext}`;
|
||||
const data: IGitBlameUriData = { fileName: commit.fileName, sha: commit.sha, range: range, index: index };
|
||||
if (originalFileName) {
|
||||
data.originalFileName = originalFileName;
|
||||
}
|
||||
// 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)}`);
|
||||
return Uri.parse(`${DocumentSchemes.GitBlame}:${pad(index)}. ${commit.author}, ${moment(commit.date).format('MMM D, YYYY hh:MM a')} - ${path}?${JSON.stringify(data)}`);
|
||||
}
|
||||
|
||||
static fromBlameUri(uri: Uri): IGitBlameUriData {
|
||||
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;
|
||||
@@ -138,14 +169,18 @@ export interface IGitBlameCommit {
|
||||
author: string;
|
||||
date: Date;
|
||||
}
|
||||
|
||||
export interface IGitBlameLine {
|
||||
sha: string;
|
||||
originalLine: number;
|
||||
line: number;
|
||||
originalLine: number;
|
||||
originalFileName?: string;
|
||||
code?: string;
|
||||
}
|
||||
|
||||
export interface IGitBlameUriData {
|
||||
fileName: string,
|
||||
originalFileName?: string;
|
||||
sha: string,
|
||||
range: Range,
|
||||
index: number
|
||||
Reference in New Issue
Block a user