mirror of
https://github.com/ckaczor/vscode-gitlens.git
synced 2026-02-12 11:08:34 -05:00
Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ea33560f14 | ||
|
|
70cc92ddd6 | ||
|
|
0e064f15c7 | ||
|
|
9964ea691b | ||
|
|
92beca2542 | ||
|
|
0ccac8da8c | ||
|
|
a22b8b1ddd | ||
|
|
84becec23f | ||
|
|
c395a583b7 |
@@ -1,4 +1,4 @@
|
||||
# Git CodeLens
|
||||
# GitLens
|
||||
|
||||
Provides Git blame (and history eventually) CodeLens for many supported Visual Studio Code languages (in theory -- the language must support symbol searching).
|
||||
|
||||
|
||||
13
package.json
13
package.json
@@ -1,19 +1,19 @@
|
||||
{
|
||||
"name": "git-codelens",
|
||||
"version": "0.0.1",
|
||||
"name": "gitlens",
|
||||
"version": "0.0.3",
|
||||
"author": "Eric Amodio",
|
||||
"publisher": "eamodio",
|
||||
"engines": {
|
||||
"vscode": "^1.3.0"
|
||||
},
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"displayName": "Git CodeLens",
|
||||
"displayName": "GitLens",
|
||||
"description": "Provides Git blame information in CodeLens",
|
||||
"categories": [
|
||||
"Other"
|
||||
],
|
||||
"keywords": [
|
||||
"git", "gitblame", "blame"
|
||||
"git", "gitblame", "blame", "codelens"
|
||||
],
|
||||
"galleryBanner": {
|
||||
"color": "#0000FF",
|
||||
@@ -23,7 +23,7 @@
|
||||
"main": "./out/src/extension",
|
||||
"contributes": {
|
||||
"commands": [{
|
||||
"command": "git.codelen.showBlameHistory",
|
||||
"command": "git.action.showBlameHistory",
|
||||
"title": "Show Blame History",
|
||||
"category": "Git"
|
||||
}]
|
||||
@@ -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 ./",
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
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,15 +1,30 @@
|
||||
export type Commands = 'git.action.showBlameHistory';
|
||||
'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.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' | '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,21 +0,0 @@
|
||||
// 'use strict';
|
||||
// import {CancellationToken, CodeLens, commands, DefinitionProvider, Position, Location, TextDocument, Uri} from 'vscode';
|
||||
// import {GitCodeLens} from './codeLensProvider';
|
||||
|
||||
// export default class GitDefinitionProvider implements DefinitionProvider {
|
||||
// public provideDefinition(document: TextDocument, position: Position, token: CancellationToken): Promise<Location> {
|
||||
// return (commands.executeCommand('vscode.executeCodeLensProvider', document.uri) as Promise<CodeLens[]>).then(lenses => {
|
||||
// let matches: CodeLens[] = [];
|
||||
// lenses.forEach(lens => {
|
||||
// if (lens instanceof GitCodeLens && lens.blameRange.contains(position)) {
|
||||
// matches.push(lens);
|
||||
// }
|
||||
// });
|
||||
|
||||
// if (matches.length) {
|
||||
// return new Location(Uri.parse(), position);
|
||||
// }
|
||||
// return null;
|
||||
// });
|
||||
// }
|
||||
// }
|
||||
@@ -1,30 +1,36 @@
|
||||
'use strict';
|
||||
import {commands, DocumentSelector, ExtensionContext, languages, workspace} from 'vscode';
|
||||
import GitCodeLensProvider from './codeLensProvider';
|
||||
import GitContentProvider from './contentProvider';
|
||||
import {gitRepoPath} from './git';
|
||||
import {Commands, VsCodeCommands} 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) {
|
||||
// Workspace not using a folder. No access to git repo.
|
||||
if (!workspace.rootPath) {
|
||||
console.warn('Git CodeLens inactive: no rootPath');
|
||||
console.warn('GitLens inactive: no rootPath');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`Git CodeLens active: ${workspace.rootPath}`);
|
||||
console.log(`GitLens active: ${workspace.rootPath}`);
|
||||
|
||||
gitRepoPath(workspace.rootPath).then(repoPath => {
|
||||
context.subscriptions.push(workspace.registerTextDocumentContentProvider(GitContentProvider.scheme, new GitContentProvider(context)));
|
||||
const git = new GitProvider(context);
|
||||
context.subscriptions.push(git);
|
||||
|
||||
context.subscriptions.push(commands.registerCommand(Commands.ShowBlameHistory, (...args) => {
|
||||
return commands.executeCommand(VsCodeCommands.ShowReferences, ...args);
|
||||
}));
|
||||
git.getRepoPath(workspace.rootPath).then(repoPath => {
|
||||
context.workspaceState.update(WorkspaceState.RepoPath, repoPath);
|
||||
context.workspaceState.update(WorkspaceState.HasGitHistoryExtension, extensions.getExtension('donjayamanne.githistory') !== undefined);
|
||||
|
||||
const selector: DocumentSelector = { scheme: 'file' };
|
||||
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(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));
|
||||
}
|
||||
|
||||
|
||||
109
src/git.ts
109
src/git.ts
@@ -1,75 +1,78 @@
|
||||
'use strict';
|
||||
import {basename, dirname, extname} 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 declare interface IGitBlameLine {
|
||||
sha: string;
|
||||
file: string;
|
||||
originalLine: number;
|
||||
author: string;
|
||||
date: Date;
|
||||
line: number;
|
||||
//code: string;
|
||||
function gitCommand(cwd: string, ...args) {
|
||||
return spawnPromise('git', args, { cwd: cwd });
|
||||
}
|
||||
|
||||
export function gitRepoPath(cwd) {
|
||||
return gitCommand(cwd, 'rev-parse', '--show-toplevel').then(data => data.replace(/\r?\n|\r/g, ''));
|
||||
}
|
||||
export default class Git {
|
||||
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) {
|
||||
console.log('git', 'blame', '-fnw', '--root', '--', fileName);
|
||||
return gitCommand(dirname(fileName), 'blame', '-fnw', '--root', '--', fileName).then(data => {
|
||||
let lines: Array<IGitBlameLine> = [];
|
||||
let m: Array<string>;
|
||||
while ((m = blameMatcher.exec(data)) != null) {
|
||||
lines.push({
|
||||
sha: m[1],
|
||||
file: m[2].trim(),
|
||||
originalLine: parseInt(m[3], 10) - 1,
|
||||
author: m[4].trim(),
|
||||
date: new Date(m[5]),
|
||||
line: parseInt(m[6], 10) - 1
|
||||
//code: m[7]
|
||||
});
|
||||
static blame(fileName: string, repoPath: string, sha?: string) {
|
||||
fileName = Git.normalizePath(fileName, repoPath);
|
||||
|
||||
if (sha) {
|
||||
console.log('git', 'blame', '-fnw', '--root', `${sha}^`, '--', fileName);
|
||||
return gitCommand(repoPath, 'blame', '-fnw', '--root', `${sha}^`, '--', fileName);
|
||||
}
|
||||
return lines;
|
||||
});
|
||||
}
|
||||
|
||||
export function gitGetVersionFile(repoPath: string, sha: string, source: string): Promise<string> {
|
||||
return new Promise<string>((resolve, reject) => {
|
||||
gitCommand(repoPath, 'show', `${sha.replace('^', '')}:${source.replace(/\\/g, '/')}`).then(data => {
|
||||
let ext = extname(source);
|
||||
tmp.file({ prefix: `${basename(source, ext)}-${sha}_`, postfix: ext }, (err, destination, fd, cleanupCallback) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
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));
|
||||
}
|
||||
|
||||
console.log("File: ", destination);
|
||||
console.log("Filedescriptor: ", fd);
|
||||
|
||||
fs.appendFile(destination, data, err => {
|
||||
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(repoPath: string, sha: string, source: string) {
|
||||
console.log('git', 'show', `${sha}:${source.replace(/\\/g, '/')}`);
|
||||
return gitCommand(repoPath, 'show', `${sha}:${source.replace(/\\/g, '/')}`);
|
||||
}
|
||||
static getVersionedFileText(fileName: string, repoPath: string, sha: string) {
|
||||
fileName = Git.normalizePath(fileName, repoPath);
|
||||
sha = sha.replace('^', '');
|
||||
|
||||
function gitCommand(cwd: string, ...args) {
|
||||
return spawnPromise('git', args, { cwd: cwd });
|
||||
console.log('git', 'show', `${sha}:${fileName}`);
|
||||
return gitCommand(repoPath, 'show', `${sha}:${fileName}`);
|
||||
// .then(s => { console.log(s); return s; })
|
||||
// .catch(ex => console.error(ex));
|
||||
}
|
||||
|
||||
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} from './constants';
|
||||
import {gitGetVersionText} from './git';
|
||||
import {fromGitBlameUri, IGitBlameUriData} from './gitBlameUri';
|
||||
import {DocumentSchemes, WorkspaceState} from './constants';
|
||||
import GitProvider, {IGitBlameUriData} from './gitProvider';
|
||||
import * as moment from 'moment';
|
||||
|
||||
export default class GitBlameContentProvider implements TextDocumentContentProvider {
|
||||
@@ -10,10 +9,9 @@ export default class GitBlameContentProvider implements TextDocumentContentProvi
|
||||
|
||||
private _blameDecoration: TextEditorDecorationType;
|
||||
private _onDidChange = new EventEmitter<Uri>();
|
||||
// private _subscriptions: Disposable;
|
||||
// private _dataMap: Map<string, IGitBlameUriData>;
|
||||
//private _subscriptions: Disposable;
|
||||
|
||||
constructor(context: ExtensionContext) {
|
||||
constructor(context: ExtensionContext, private git: GitProvider) {
|
||||
this._blameDecoration = window.createTextEditorDecorationType({
|
||||
dark: {
|
||||
backgroundColor: 'rgba(255, 255, 255, 0.15)',
|
||||
@@ -30,25 +28,14 @@ export default class GitBlameContentProvider implements TextDocumentContentProvi
|
||||
isWholeLine: true
|
||||
});
|
||||
|
||||
// this._dataMap = new Map();
|
||||
// this._subscriptions = Disposable.from(
|
||||
//this._subscriptions = Disposable.from(
|
||||
// window.onDidChangeActiveTextEditor(e => e ? console.log(e.document.uri) : console.log('active missing')),
|
||||
// workspace.onDidOpenTextDocument(d => {
|
||||
// let data = this._dataMap.get(d.uri.toString());
|
||||
// if (!data) return;
|
||||
|
||||
// // TODO: This only works on the first load -- not after since it is cached
|
||||
// this._tryAddBlameDecorations(d.uri, data);
|
||||
// }),
|
||||
// workspace.onDidCloseTextDocument(d => {
|
||||
// this._dataMap.delete(d.uri.toString());
|
||||
// })
|
||||
// );
|
||||
//);
|
||||
}
|
||||
|
||||
dispose() {
|
||||
this._onDidChange.dispose();
|
||||
// this._subscriptions && this._subscriptions.dispose();
|
||||
//this._subscriptions && this._subscriptions.dispose();
|
||||
}
|
||||
|
||||
get onDidChange() {
|
||||
@@ -60,12 +47,11 @@ export default class GitBlameContentProvider implements TextDocumentContentProvi
|
||||
}
|
||||
|
||||
provideTextDocumentContent(uri: Uri): string | Thenable<string> {
|
||||
const data = fromGitBlameUri(uri);
|
||||
// this._dataMap.set(uri.toString(), data);
|
||||
const data = this.git.fromBlameUri(uri);
|
||||
|
||||
//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);
|
||||
|
||||
// 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 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}`)
|
||||
// return workspace.openTextDocument(uri).then(doc => {
|
||||
// this.update(uri);
|
||||
@@ -100,15 +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);
|
||||
editor.setDecorations(this._blameDecoration, data.lines.map(l => {
|
||||
return {
|
||||
range: editor.document.validateRange(new Range(l.originalLine, 0, l.originalLine, 1000000)),
|
||||
hoverMessage: `${moment(l.date).format('MMMM Do, YYYY hh:MMa')}\n${l.author}\n${l.sha}`
|
||||
};
|
||||
}));
|
||||
}
|
||||
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,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;
|
||||
}
|
||||
119
src/gitCodeLensProvider.ts
Normal file
119
src/gitCodeLensProvider.ts
Normal file
@@ -0,0 +1,119 @@
|
||||
'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 * as moment from 'moment';
|
||||
|
||||
export class GitCodeLens extends CodeLens {
|
||||
constructor(private git: GitProvider, public fileName: string, public blameRange: Range, range: Range) {
|
||||
super(range);
|
||||
}
|
||||
|
||||
getBlame(): Promise<IGitBlame> {
|
||||
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;
|
||||
|
||||
this.git.getBlameForFile(fileName);
|
||||
|
||||
return (commands.executeCommand(VsCodeCommands.ExecuteDocumentSymbolProvider, document.uri) as Promise<SymbolInformation[]>).then(symbols => {
|
||||
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 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(fileName: string, document: TextDocument, symbol: SymbolInformation, 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);
|
||||
|
||||
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 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 GitCodeLens) return this._resolveGitBlameCodeLens(lens, token);
|
||||
if (lens instanceof GitHistoryCodeLens) return this._resolveGitHistoryCodeLens(lens, token);
|
||||
}
|
||||
|
||||
_resolveGitBlameCodeLens(lens: GitCodeLens, token: CancellationToken): Thenable<CodeLens> {
|
||||
return new Promise<CodeLens>((resolve, reject) => {
|
||||
lens.getBlame().then(blame => {
|
||||
if (!blame.lines.length) {
|
||||
console.error('No blame lines found', lens);
|
||||
reject(null);
|
||||
return;
|
||||
}
|
||||
|
||||
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()}`, // - lines(${lens.blameRange.start.line + 1}-${lens.blameRange.end.line + 1})`,
|
||||
command: Commands.ShowBlameHistory,
|
||||
arguments: [Uri.file(lens.fileName), lens.blameRange, lens.range.start]
|
||||
};
|
||||
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);
|
||||
}
|
||||
}
|
||||
187
src/gitProvider.ts
Normal file
187
src/gitProvider.ts
Normal file
@@ -0,0 +1,187 @@
|
||||
'use strict'
|
||||
import {Disposable, ExtensionContext, Location, Position, Range, Uri, workspace} from 'vscode';
|
||||
import {DocumentSchemes, WorkspaceState} from './constants';
|
||||
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 GitProvider extends Disposable {
|
||||
public repoPath: string;
|
||||
|
||||
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._blames = new Map();
|
||||
this._subscription = Disposable.from(workspace.onDidCloseTextDocument(d => this._removeFile(d.fileName)),
|
||||
workspace.onDidChangeTextDocument(e => this._removeFile(e.document.fileName)));
|
||||
}
|
||||
|
||||
dispose() {
|
||||
this._blames.clear();
|
||||
this._subscription && this._subscription.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
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 = 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: fileName,
|
||||
author: m[4].trim(),
|
||||
date: new Date(m[5])
|
||||
});
|
||||
}
|
||||
|
||||
const line: IGitBlameLine = {
|
||||
sha,
|
||||
line: parseInt(m[6], 10) - 1,
|
||||
originalLine: parseInt(m[3], 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 };
|
||||
});
|
||||
|
||||
this._blames.set(fileName, blame);
|
||||
return blame;
|
||||
}
|
||||
|
||||
getBlameForRange(fileName: string, range: Range): Promise<IGitBlame> {
|
||||
return this.getBlameForFile(fileName).then(blame => {
|
||||
if (!blame.lines.length) return blame;
|
||||
|
||||
const lines = blame.lines.slice(range.start.line, range.end.line + 1);
|
||||
const commits = new Map();
|
||||
_.uniqBy(lines, 'sha').forEach(l => commits.set(l.sha, blame.commits.get(l.sha)));
|
||||
|
||||
return { commits, lines };
|
||||
});
|
||||
}
|
||||
|
||||
getBlameForShaRange(fileName: string, sha: string, range: Range): Promise<{commit: IGitBlameCommit, lines: IGitBlameLine[]}> {
|
||||
return this.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)
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
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())
|
||||
.sort((a, b) => b.date.getTime() - a.date.getTime())
|
||||
.forEach((c, i) => {
|
||||
const uri = this.toBlameUri(c, range, i + 1, commitCount);
|
||||
blame.lines
|
||||
.filter(l => l.sha === c.sha)
|
||||
.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;
|
||||
});
|
||||
}
|
||||
|
||||
getVersionedFile(fileName: string, sha: string) {
|
||||
return Git.getVersionedFile(fileName, this.repoPath, sha);
|
||||
}
|
||||
|
||||
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 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:MM a')} - ${path}?${JSON.stringify(data)}`);
|
||||
}
|
||||
|
||||
fromBlameUri(uri: Uri): IGitBlameUriData {
|
||||
const data = JSON.parse(uri.query);
|
||||
data.range = new Range(data.range[0].line, data.range[0].character, data.range[1].line, data.range[1].character);
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
export interface IGitBlame {
|
||||
commits: Map<string, IGitBlameCommit>;
|
||||
lines: IGitBlameLine[];
|
||||
}
|
||||
|
||||
export interface IGitBlameCommit {
|
||||
sha: string;
|
||||
fileName: string;
|
||||
author: string;
|
||||
date: Date;
|
||||
}
|
||||
|
||||
export interface IGitBlameLine {
|
||||
sha: string;
|
||||
line: number;
|
||||
originalLine: number;
|
||||
originalFileName?: string;
|
||||
code?: string;
|
||||
}
|
||||
|
||||
export interface IGitBlameUriData {
|
||||
fileName: string,
|
||||
originalFileName?: string;
|
||||
sha: string,
|
||||
range: Range,
|
||||
index: number
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
{
|
||||
"globalDependencies": {
|
||||
"tmp": "registry:dt/tmp#0.0.0+20160514170650"
|
||||
},
|
||||
"dependencies": {
|
||||
"lodash": "registry:npm/lodash#4.0.0+20160723033700"
|
||||
}
|
||||
}
|
||||
|
||||
1
typings/index.d.ts
vendored
1
typings/index.d.ts
vendored
@@ -1 +1,2 @@
|
||||
/// <reference path="globals/tmp/index.d.ts" />
|
||||
/// <reference path="modules/lodash/index.d.ts" />
|
||||
|
||||
18545
typings/modules/lodash/index.d.ts
vendored
Normal file
18545
typings/modules/lodash/index.d.ts
vendored
Normal file
File diff suppressed because it is too large
Load Diff
11
typings/modules/lodash/typings.json
Normal file
11
typings/modules/lodash/typings.json
Normal file
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"resolution": "main",
|
||||
"tree": {
|
||||
"src": "https://raw.githubusercontent.com/types/npm-lodash/9b83559bbd3454f0cd9e4020c920e36eee80d5a3/typings.json",
|
||||
"raw": "registry:npm/lodash#4.0.0+20160723033700",
|
||||
"main": "index.d.ts",
|
||||
"version": "4.0.0",
|
||||
"name": "lodash",
|
||||
"type": "typings"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user