Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#10 add safeguard for loadBackup #23

Merged
merged 1 commit into from
Mar 31, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,21 @@ class GitBackupSync {
);
}

private async checkBranchesInSync(branchName1: string, branchName2: string, expectedBranch1Ahead: number, expectedBranch2Ahead: number): Promise<boolean> {
let result = await this._git.raw(["rev-list", "--left-right", "--count", `${branchName1}...${branchName2}`]);
console.log(result);
const diffCountParsingRegex = /(\d+)\s+(\d+)/;
const match = diffCountParsingRegex.exec(result);
if (match !== null && match.length === 3) {
const branch1Ahead = parseInt(match[1]);
const branch2Ahead = parseInt(match[2]);
return (branch1Ahead === expectedBranch1Ahead) && (branch2Ahead === expectedBranch2Ahead);
} else {
this.showErrorMessage(`git rev-list failed, are you using an up-to-date git?`);
return false;
}
}

public async createBackupBranch(branchName?: string): Promise<string | undefined> {
if (!this.isEnabled) {
return;
Expand Down Expand Up @@ -317,6 +332,22 @@ class GitBackupSync {
console.log(await this._git.fetch());
// pulls in the most up to date backup branch
console.log(await this._git.reset(["--hard", this._config.defaultBackupUpstreamName + "/" + backupBranchName]));

// Check if backup branch is out of sync
// only acceptable output is "0 1", where backup branch is ahead by only 1 commit; which is the backup commit
let checkResult = await this.checkBranchesInSync(currentBranchName, backupBranchName, 0, 1);
if (checkResult === false) {
// switch back to current branch temporarily, in case user ignores UI
console.log(await this._git.checkout(currentBranchName));
let selection = await vscode.window.showWarningMessage(`"${backupBranchName}" is out of sync with your local branch. Do you still want to continue Loading Backup?`, "Yes", "No");
// continue only if the user insists
if (selection !== "Yes") {
return false;
}
// switch back to backup branch to load backup
console.log(await this._git.checkout(backupBranchName));
}

// undoes the last commit
console.log(await this._git.reset(["--mixed", "HEAD~1"]));
// brings those changes in the last commit over to the current branch
Expand Down