-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathcore.ts
More file actions
259 lines (220 loc) · 6.22 KB
/
Copy pathcore.ts
File metadata and controls
259 lines (220 loc) · 6.22 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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
import type { GetRepositoryMetadataQuery } from "./github/graphql/generated/operations.js";
import {
createCommitOnBranchQuery,
getRepositoryMetadata,
} from "./github/graphql/queries.ts";
import type {
CommitFilesFromBase64Args,
CommitFilesResult,
GitBase,
} from "./interface.ts";
import { normalizeCommitMessage } from "./utils.ts";
const getBaseRef = (base: GitBase): string => {
if ("branch" in base) {
return `refs/heads/${base.branch}`;
} else if ("tag" in base) {
return `refs/tags/${base.tag}`;
} else {
// For explicit commit bases we don't resolve the base oid from a ref,
// but the shared metadata query still expects a valid qualified ref name.
return "HEAD";
}
};
const getOidFromRef = (
base: GitBase,
ref: (GetRepositoryMetadataQuery["repository"] &
Record<never, never>)["baseRef"],
) => {
if ("commit" in base) {
return base.commit;
}
if (!ref?.target) {
throw new Error(`Could not determine oid from ref: ${JSON.stringify(ref)}`);
}
if ("target" in ref.target) {
return ref.target.target.oid;
}
return ref.target.oid;
};
const isAlreadyExistingRefError = (error: unknown) =>
typeof error === "object" &&
error !== null &&
"status" in error &&
"message" in error &&
typeof error.status === "number" &&
typeof error.message === "string" &&
error.status === 422 &&
error.message.includes("Reference already exists");
const createCommit = async ({
octokit,
refId,
baseOid,
message,
fileChanges,
}: Pick<CommitFilesFromBase64Args, "octokit" | "message" | "fileChanges"> & {
refId: string;
baseOid: string;
}) => {
// we have to stick to GraphQL here as with REST, each file change would become a separate API call
return createCommitOnBranchQuery(octokit, {
input: {
branch: {
id: refId,
},
expectedHeadOid: baseOid,
message: normalizeCommitMessage(message),
fileChanges,
},
});
};
export const commitFilesFromBase64 = async ({
octokit,
owner,
repo,
branch,
base,
force = false,
message,
fileChanges,
log,
}: CommitFilesFromBase64Args): Promise<CommitFilesResult> => {
const repositoryNameWithOwner = `${owner}/${repo}`;
const baseRef = getBaseRef(base);
const targetRef = `refs/heads/${branch}`;
log?.debug(`Getting repo info ${repositoryNameWithOwner}`);
const info = await getRepositoryMetadata(octokit, {
owner,
repo,
baseRef,
targetRef,
});
log?.debug(`Repo info: ${JSON.stringify(info, null, 2)}`);
if (!info) {
throw new Error(
`Repository ${JSON.stringify(repositoryNameWithOwner)} not found`,
);
}
if (!("commit" in base) && !info.baseRef) {
throw new Error(`Ref ${JSON.stringify(baseRef)} not found`);
}
const resolvedBaseRef = info.baseRef;
/**
* The commit oid to base the new commit on.
*
* Used both to create the new commit,
* and to determine whether an existing branch can be updated.
*/
const baseOid = getOidFromRef(base, info.baseRef);
const targetOid = info.targetBranch?.target?.oid ?? null;
const sameBranchBase = "branch" in base && base.branch === branch;
let mode: "create" | "update" | "force-update";
if (sameBranchBase) {
mode = force ? "force-update" : "update";
} else if (targetOid === null) {
// TODO: legit *creation* failure should be retried if `force === true`
mode = "create";
} else if (force) {
mode = "force-update";
} else if (targetOid === baseOid) {
mode = "update";
} else {
throw new Error(
`Branch ${branch} exists already and does not match base ${baseOid}, force is set to false`,
);
}
if (mode === "force-update") {
// Use a stable temp branch name so a later run can recover and reuse it
// if an earlier run failed before cleanup completed.
const tempBranch = `changesets-ghcommit-temp/${branch}`;
let tempRefId: string;
try {
const createdTempRef = await octokit.rest.git.createRef({
owner,
repo,
ref: `refs/heads/${tempBranch}`,
sha: baseOid,
});
const refIdStr = createdTempRef.data.node_id;
if (!refIdStr) {
throw new Error(`Failed to create temporary branch ${tempBranch}`);
}
tempRefId = refIdStr;
} catch (error) {
if (!isAlreadyExistingRefError(error)) {
throw error;
}
const updatedTempRef = await octokit.rest.git.updateRef({
owner,
repo,
ref: `heads/${tempBranch}`,
sha: baseOid,
force: true,
});
const refIdStr = updatedTempRef.data.node_id;
if (!refIdStr) {
throw new Error(`Failed to update temporary branch ${tempBranch}`);
}
tempRefId = refIdStr;
}
log?.debug(`Creating commit on branch ${tempBranch}`);
const tempCommit = await createCommit({
octokit,
refId: tempRefId,
baseOid,
message,
fileChanges,
});
const tempHeadOid = tempCommit.createCommitOnBranch?.commit?.oid;
if (!tempHeadOid) {
throw new Error(
`Failed to determine head commit of temporary branch ${tempBranch}`,
);
}
const updatedTargetRef = await octokit.rest.git.updateRef({
owner,
repo,
ref: `heads/${branch}`,
sha: tempHeadOid,
force: true,
});
const updatedTargetRefId = updatedTargetRef.data.node_id;
if (!updatedTargetRefId) {
throw new Error(`Failed to update branch ${branch}`);
}
await octokit.rest.git.deleteRef({
owner,
repo,
ref: `heads/${tempBranch}`,
});
return {
refId: updatedTargetRefId,
};
}
let refId: string;
if (mode === "create") {
const createdRef = await octokit.rest.git.createRef({
owner,
repo,
ref: `refs/heads/${branch}`,
sha: baseOid,
});
const refIdStr = createdRef.data.node_id;
if (!refIdStr) {
throw new Error(`Failed to create branch ${branch}`);
}
refId = refIdStr;
} else {
refId = sameBranchBase ? resolvedBaseRef!.id : info.targetBranch!.id;
}
log?.debug(`Creating commit on branch ${branch}`);
const newCommit = await createCommit({
octokit,
refId,
baseOid,
message,
fileChanges,
});
return {
refId: newCommit.createCommitOnBranch?.ref?.id ?? null,
};
};