forked from microsoft/vscode-pull-request-github
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpullRequestGitHelper.ts
More file actions
242 lines (209 loc) · 9.54 KB
/
pullRequestGitHelper.ts
File metadata and controls
242 lines (209 loc) · 9.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/*
* Inspired by and includes code from GitHub/VisualStudio project, obtained from https://github.com/github/VisualStudio/blob/165a97bdcab7559e0c4393a571b9ff2aed4ba8a7/src/GitHub.App/Services/PullRequestService.cs
*/
import Logger from '../common/logger';
import { Protocol } from '../common/protocol';
import { Remote, parseRepositoryRemotes } from '../common/remote';
import { GitHubRepository } from './githubRepository';
import { Repository, Branch } from '../api/api';
import { PullRequestModel } from './pullRequestModel';
const PullRequestRemoteMetadataKey = 'github-pr-remote';
const PullRequestMetadataKey = 'github-pr-owner-number';
const PullRequestBranchRegex = /branch\.(.+)\.github-pr-owner-number/;
export interface PullRequestMetadata {
owner: string;
repositoryName: string;
prNumber: number;
}
export class PullRequestGitHelper {
static ID = 'PullRequestGitHelper';
static async checkoutFromFork(repository: Repository, pullRequest: PullRequestModel) {
// the branch is from a fork
let localBranchName = await PullRequestGitHelper.calculateUniqueBranchNameForPR(repository, pullRequest);
// create remote for this fork
Logger.appendLine(`Branch ${localBranchName} is from a fork. Create a remote first.`, PullRequestGitHelper.ID);
let remoteName = await PullRequestGitHelper.createRemote(repository, pullRequest.remote, pullRequest.head.repositoryCloneUrl);
// fetch the branch
let ref = `${pullRequest.head.ref}:${localBranchName}`;
Logger.debug(`Fetch ${remoteName}/${pullRequest.head.ref}:${localBranchName} - start`, PullRequestGitHelper.ID);
await repository.fetch(remoteName, ref, 1);
Logger.debug(`Fetch ${remoteName}/${pullRequest.head.ref}:${localBranchName} - done`, PullRequestGitHelper.ID);
await repository.checkout(localBranchName);
// set remote tracking branch for the local branch
await repository.setBranchUpstream(localBranchName, `refs/remotes/${remoteName}/${pullRequest.head.ref}`);
await repository.pull(true);
PullRequestGitHelper.associateBranchWithPullRequest(repository, pullRequest, localBranchName);
}
static async fetchAndCheckout(repository: Repository, githubRepositories: GitHubRepository[], pullRequest: PullRequestModel): Promise<void> {
const remote = PullRequestGitHelper.getHeadRemoteForPullRequest(repository, githubRepositories, pullRequest);
if (!remote) {
return PullRequestGitHelper.checkoutFromFork(repository, pullRequest);
}
const branchName = pullRequest.head.ref;
let remoteName = remote.remoteName;
let branch: Branch;
try {
branch = await repository.getBranch(branchName);
Logger.debug(`Checkout ${branchName}`, PullRequestGitHelper.ID);
await repository.checkout(branchName);
if (!branch.upstream) {
// this branch is not associated with upstream yet
const trackedBranchName = `refs/remotes/${remoteName}/${branchName}`;
await repository.setBranchUpstream(branchName, trackedBranchName);
}
if (branch.behind !== undefined && branch.behind > 0 && branch.ahead === 0) {
Logger.debug(`Pull from upstream`, PullRequestGitHelper.ID);
await repository.pull();
}
} catch (err) {
// there is no local branch with the same name, so we are good to fetch, create and checkout the remote branch.
Logger.appendLine(`Branch ${remoteName}/${branchName} doesn't exist on local disk yet.`, PullRequestGitHelper.ID);
const trackedBranchName = `refs/remotes/${remoteName}/${branchName}`;
Logger.appendLine(`Fetch tracked branch ${trackedBranchName}`, PullRequestGitHelper.ID);
await repository.fetch(remoteName, branchName, 1);
const trackedBranch = await repository.getBranch(trackedBranchName);
// create branch
await repository.createBranch(branchName, true, trackedBranch.commit);
await repository.setBranchUpstream(branchName, trackedBranchName);
await repository.pull(true);
}
await PullRequestGitHelper.associateBranchWithPullRequest(repository, pullRequest, branchName);
}
static async checkoutExistingPullRequestBranch(repository: Repository, githubRepositories: GitHubRepository[], pullRequest: PullRequestModel) {
let key = PullRequestGitHelper.buildPullRequestMetadata(pullRequest);
let configs = await repository.getConfigs();
let branchInfos = configs.map(config => {
let matches = PullRequestBranchRegex.exec(config.key);
return {
branch: matches && matches.length ? matches[1] : null,
value: config.value
};
}).filter(c => c.branch && c.value === key);
if (branchInfos && branchInfos.length) {
// let's immediately checkout to branchInfos[0].branch
await repository.checkout(branchInfos[0].branch!);
const branch = await repository.getBranch(branchInfos[0].branch!);
if (branch.behind !== undefined && branch.behind > 0 && branch.ahead === 0) {
Logger.debug(`Pull from upstream`, PullRequestGitHelper.ID);
await repository.pull();
}
return true;
} else {
return false;
}
}
static buildPullRequestMetadata(pullRequest: PullRequestModel) {
return pullRequest.base.repositoryCloneUrl.owner + '#' + pullRequest.base.repositoryCloneUrl.repositoryName + '#' + pullRequest.prNumber;
}
static parsePullRequestMetadata(value: string): PullRequestMetadata | undefined {
if (value) {
let matches = /(.*)#(.*)#(.*)/g.exec(value);
if (matches && matches.length === 4) {
const [, owner, repo, prNumber] = matches;
return {
owner: owner,
repositoryName: repo,
prNumber: Number(prNumber)
};
}
}
}
static async getMatchingPullRequestMetadataForBranch(repository: Repository, branchName: string): Promise<PullRequestMetadata | undefined> {
try {
let configKey = `branch.${branchName}.${PullRequestMetadataKey}`;
let configValue = await repository.getConfig(configKey);
return PullRequestGitHelper.parsePullRequestMetadata(configValue);
} catch (_) {
return;
}
}
static async createRemote(repository: Repository, baseRemote: Remote, cloneUrl: Protocol) {
Logger.appendLine(`create remote for ${cloneUrl}.`, PullRequestGitHelper.ID);
let remotes = parseRepositoryRemotes(repository);
for (let remote of remotes) {
if (new Protocol(remote.url).equals(cloneUrl)) {
return remote.remoteName;
}
}
let remoteName = PullRequestGitHelper.getUniqueRemoteName(repository, cloneUrl.owner);
cloneUrl.update({
type: baseRemote.gitProtocol.type
});
await repository.addRemote(remoteName, cloneUrl.toString()!);
await repository.setConfig(`remote.${remoteName}.${PullRequestRemoteMetadataKey}`, 'true');
return remoteName;
}
static async getUserCreatedRemotes(repository: Repository, remotes: Remote[]): Promise<Remote[]> {
try {
Logger.debug(`Get user created remotes - start`, PullRequestGitHelper.ID);
const allConfigs = await repository.getConfigs();
let remotesForPullRequest: string[] = [];
for (let i = 0; i < allConfigs.length; i++) {
let key = allConfigs[i].key;
let matches = /^remote\.(.*)\.github-pr-remote$/.exec(key);
if (matches && matches.length === 2 && allConfigs[i].value) {
// this remote is created for pull requests
remotesForPullRequest.push(matches[1]);
}
}
let ret = remotes.filter(function (e) {
return remotesForPullRequest.indexOf(e.remoteName) < 0;
});
Logger.debug(`Get user created remotes - end`, PullRequestGitHelper.ID);
return ret;
} catch (_) {
return [];
}
}
static async isRemoteCreatedForPullRequest(repository: Repository, remoteName: string) {
try {
Logger.debug(`Check if remote '${remoteName}' is created for pull request - start`, PullRequestGitHelper.ID);
const isForPR = await repository.getConfig(`remote.${remoteName}.${PullRequestRemoteMetadataKey}`);
Logger.debug(`Check if remote '${remoteName}' is created for pull request - end`, PullRequestGitHelper.ID);
return isForPR === 'true';
} catch (_) {
return false;
}
}
static async calculateUniqueBranchNameForPR(repository: Repository, pullRequest: PullRequestModel): Promise<string> {
let branchName = `pr/${pullRequest.author.login}/${pullRequest.prNumber}`;
let result = branchName;
let number = 1;
while (true) {
try {
await repository.getBranch(result);
result = branchName + '-' + number++;
} catch (err) {
break;
}
}
return result;
}
static getUniqueRemoteName(repository: Repository, name: string) {
let uniqueName = name;
let number = 1;
const remotes = parseRepositoryRemotes(repository);
while (remotes.find(e => e.remoteName === uniqueName)) {
uniqueName = name + number++;
}
return uniqueName;
}
static getHeadRemoteForPullRequest(repository: Repository, githubRepositories: GitHubRepository[], pullRequest: PullRequestModel): Remote | undefined {
for (let i = 0; i < githubRepositories.length; i++) {
let remote = githubRepositories[i].remote;
if (remote.gitProtocol && remote.gitProtocol.equals(pullRequest.head.repositoryCloneUrl)) {
return remote;
}
}
return;
}
static async associateBranchWithPullRequest(repository: Repository, pullRequest: PullRequestModel, branchName: string) {
Logger.appendLine(`associate ${branchName} with Pull Request #${pullRequest.prNumber}`, PullRequestGitHelper.ID);
let prConfigKey = `branch.${branchName}.${PullRequestMetadataKey}`;
await repository.setConfig(prConfigKey, PullRequestGitHelper.buildPullRequestMetadata(pullRequest));
}
}