Skip to content

Commit

Permalink
Code refactoring, and improved error handling.
Browse files Browse the repository at this point in the history
  • Loading branch information
mhutchie committed Mar 4, 2019
1 parent 82bb557 commit 863b53d
Show file tree
Hide file tree
Showing 6 changed files with 60 additions and 41 deletions.
25 changes: 14 additions & 11 deletions src/dataSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@ const gitLogFormat = ['%H', '%P', '%an', '%ae', '%at', '%s'].join(gitLogSeparato
const gitCommitDetailsFormat = ['%H', '%P', '%an', '%ae', '%at', '%cn', '%B'].join(gitLogSeparator);

export class DataSource {
private execOptions: cp.ExecOptions;
private workspaceDir: string;
private gitPath!: string;
private gitExecPath!: string;

constructor(workspaceDir: string) {
this.execOptions = { cwd: workspaceDir };
this.workspaceDir = workspaceDir;
this.registerGitPath();
}

Expand All @@ -33,25 +33,28 @@ export class DataSource {
}

public getBranches(showRemoteBranches: boolean) {
return new Promise<string[]>((resolve) => {
return new Promise<{branches: string[], head: string | null}>((resolve) => {
this.execGit('branch' + (showRemoteBranches ? ' -a' : ''), (err, stdout) => {
let branchData = {
branches: <string[]> [],
head: <string | null> null
};

if (!err) {
let lines = stdout.split(eolRegex);
let branches: string[] = [];
for (let i = 0; i < lines.length - 1; i++) {
let name = lines[i].substring(2).split(' -> ')[0];
if (name.match(headRegex) !== null) continue;

if (lines[i][0] === '*') {
branches.unshift(name);
branchData.head = name;
branchData.branches.unshift(name);
} else {
branches.push(name);
branchData.branches.push(name);
}
}
resolve(branches);
} else {
resolve([]);
}
resolve(branchData);
});
});
}
Expand Down Expand Up @@ -285,13 +288,13 @@ export class DataSource {
}

private execGit(command: string, callback: { (error: Error | null, stdout: string, stderr: string): void }) {
cp.exec(this.gitExecPath + ' ' + command, this.execOptions, callback);
cp.exec(this.gitExecPath + ' ' + command, { cwd: this.workspaceDir }, callback);
}

private spawnGit<T>(args: string[], successValue: { (stdout: string): T }, errorValue: T) {
return new Promise<T>((resolve) => {
let stdout = '', err = false;
const cmd = cp.spawn(this.gitPath, args, this.execOptions);
const cmd = cp.spawn(this.gitPath, args, { cwd: this.workspaceDir });
cmd.stdout.on('data', (d) => { stdout += d; });
cmd.on('error', () => {
resolve(errorValue);
Expand Down
28 changes: 15 additions & 13 deletions src/gitGraphView.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Config } from './config';
import { DataSource } from './dataSource';
import { encodeDiffDocUri } from './diffDocProvider';
import { GitFileChangeType, GitGraphViewSettings, RequestMessage, ResponseMessage } from './types';
import { abbrevCommit } from './utils';
import { abbrevCommit, copyToClipboard } from './utils';

export class GitGraphView {
public static currentPanel: GitGraphView | undefined;
Expand Down Expand Up @@ -73,7 +73,10 @@ export class GitGraphView {
});
return;
case 'copyCommitHashToClipboard':
this.copyCommitHashToClipboard(msg.commitHash);
this.sendMessage({
command: 'copyCommitHashToClipboard',
success: await copyToClipboard(msg.commitHash)
});
return;
case 'createBranch':
this.sendMessage({
Expand All @@ -96,7 +99,7 @@ export class GitGraphView {
case 'loadBranches':
this.sendMessage({
command: 'loadBranches',
branches: await this.dataSource.getBranches(msg.showRemoteBranches)
... await this.dataSource.getBranches(msg.showRemoteBranches)
});
return;
case 'loadCommits':
Expand Down Expand Up @@ -130,7 +133,10 @@ export class GitGraphView {
});
return;
case 'viewDiff':
this.viewDiff(msg.commitHash, msg.oldFilePath, msg.newFilePath, msg.type);
this.sendMessage({
command: 'viewDiff',
success: await this.viewDiff(msg.commitHash, msg.oldFilePath, msg.newFilePath, msg.type)
});
return;
}
}, null, this.disposables);
Expand Down Expand Up @@ -208,19 +214,15 @@ export class GitGraphView {
this.panel.webview.postMessage(msg);
}

private copyCommitHashToClipboard(commitHash: string) {
vscode.env.clipboard.writeText(commitHash).then(
() => this.sendMessage({ command: 'copyCommitHashToClipboard', success: true }),
() => this.sendMessage({ command: 'copyCommitHashToClipboard', success: false })
);
}

private viewDiff(commitHash: string, oldFilePath: string, newFilePath: string, type: GitFileChangeType) {
let abbrevHash = abbrevCommit(commitHash);
let pathComponents = newFilePath.split('/');
let title = pathComponents[pathComponents.length - 1] + ' (' + (type === 'A' ? 'Added in ' + abbrevHash : type === 'D' ? 'Deleted in ' + abbrevHash : abbrevCommit(commitHash) + '^ ↔ ' + abbrevCommit(commitHash)) + ')';
vscode.commands.executeCommand('vscode.diff', encodeDiffDocUri(oldFilePath, commitHash + '^'), encodeDiffDocUri(newFilePath, commitHash), title, { preview: true });
this.sendMessage({ command: 'viewDiff', success: true });
return new Promise<boolean>((resolve) => {
vscode.commands.executeCommand('vscode.diff', encodeDiffDocUri(oldFilePath, commitHash + '^'), encodeDiffDocUri(newFilePath, commitHash), title, { preview: true })
.then(() => resolve(true))
.then(() => resolve(false));
});
}
}

Expand Down
1 change: 1 addition & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,7 @@ export interface RequestLoadBranches {
export interface ResponseLoadBranches {
command: 'loadBranches';
branches: string[];
head: string | null;
}

export interface RequestLoadCommits {
Expand Down
8 changes: 8 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
import * as vscode from 'vscode';

export function abbrevCommit(commitHash: string) {
return commitHash.substring(0, 8);
}

export function copyToClipboard(text: string) {
return new Promise<boolean>((resolve) => {
vscode.env.clipboard.writeText(text).then(() => resolve(true), () => resolve(false));
});
}
15 changes: 8 additions & 7 deletions web/global.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,14 @@ declare global {
}

interface WebViewState {
branchOptions: string[];
commits: GG.GitCommitNode[],
moreCommitsAvailable: boolean,
selectedBranch: string | null,
maxCommits: number,
showRemoteBranches: boolean,
expandedCommit: ExpandedCommit | null
gitBranches: string[];
gitHead: string | null;
commits: GG.GitCommitNode[];
moreCommitsAvailable: boolean;
selectedBranch: string | null;
maxCommits: number;
showRemoteBranches: boolean;
expandedCommit: ExpandedCommit | null;
}
}

Expand Down
24 changes: 14 additions & 10 deletions web/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,8 @@
}

class GitGraph {
private branchOptions: string[] = [];
private gitBranches: string[] = [];
private gitHead: string | null = null;
private commits: GG.GitCommitNode[] = [];
private selectedBranch: string | null = null;
private moreCommitsAvailable: boolean = false;
Expand Down Expand Up @@ -271,20 +272,21 @@
this.maxCommits = prevState.maxCommits;
this.expandedCommit = prevState.expandedCommit;
if (prevState.commits.length > 0) this.loadCommits(prevState.commits, prevState.moreCommitsAvailable);
if (prevState.branchOptions.length > 0) this.loadBranchOptions(prevState.branchOptions, false);
if (prevState.gitBranches.length > 0 || prevState.gitHead !== null) this.loadBranchOptions(prevState.gitBranches, prevState.gitHead, false);
}
this.requestLoadBranchOptions();
}

/* Loading Data */
public loadBranchOptions(branchOptions: string[], reloadCommits: boolean) {
this.branchOptions = branchOptions;
if (this.selectedBranch !== null && this.branchOptions.indexOf(this.selectedBranch) === -1) this.selectedBranch = '';
public loadBranchOptions(branchOptions: string[], branchHead: string | null, reloadCommits: boolean) {
this.gitBranches = branchOptions;
this.gitHead = branchHead;
if (this.selectedBranch !== null && this.gitBranches.indexOf(this.selectedBranch) === -1) this.selectedBranch = '';
this.saveState();

let html = '<option' + (this.selectedBranch === null || this.selectedBranch === '' ? ' selected' : '') + ' value="">Show All</option>';
for (let i = 0; i < this.branchOptions.length; i++) {
html += '<option value="' + this.branchOptions[i] + '"' + (this.selectedBranch === this.branchOptions[i] ? ' selected' : '') + '>' + (this.branchOptions[i].indexOf('remotes/') === 0 ? this.branchOptions[i].substring(8) : this.branchOptions[i]) + '</option>';
for (let i = 0; i < this.gitBranches.length; i++) {
html += '<option value="' + this.gitBranches[i] + '"' + (this.selectedBranch === this.gitBranches[i] ? ' selected' : '') + '>' + (this.gitBranches[i].indexOf('remotes/') === 0 ? this.gitBranches[i].substring(8) : this.gitBranches[i]) + '</option>';
}
this.branchSelectElem.innerHTML = html;
if (reloadCommits) this.requestLoadCommits();
Expand Down Expand Up @@ -350,7 +352,8 @@
/* State */
private saveState() {
vscode.setState({
branchOptions: this.branchOptions,
gitBranches: this.gitBranches,
gitHead: this.gitHead,
commits: this.commits,
moreCommitsAvailable: this.moreCommitsAvailable,
selectedBranch: this.selectedBranch,
Expand Down Expand Up @@ -482,6 +485,7 @@
this.expandedCommit = null;
this.saveState();
} else {
this.expandedCommit.id = parseInt(elem.dataset.id!);
this.expandedCommit.srcElem = elem;
this.saveState();
if (this.expandedCommit.commitDetails !== null && this.expandedCommit.fileTree !== null) {
Expand Down Expand Up @@ -622,7 +626,7 @@
}
}
);
if (this.branchOptions.length > 0 && this.branchOptions[0] !== refName) {
if (this.gitHead !== refName && this.gitHead !== null) {
menu.push({
title: 'Merge into current branch',
onClick: () => {
Expand Down Expand Up @@ -768,7 +772,7 @@
refreshGraphOrDisplayError(msg.status, 'Unable to Delete Tag');
break;
case 'loadBranches':
gitGraph.loadBranchOptions(msg.branches, true);
gitGraph.loadBranchOptions(msg.branches, msg.head, true);
break;
case 'loadCommits':
gitGraph.loadCommits(msg.commits, msg.moreCommitsAvailable);
Expand Down

0 comments on commit 863b53d

Please sign in to comment.