-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathcreate-or-update-files.js
349 lines (307 loc) · 8.44 KB
/
create-or-update-files.js
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
function isBase64(str) {
// Handle buffer inputs
if (Buffer.isBuffer(str)) {
str = str.toString("utf8");
}
var notBase64 = /[^A-Z0-9+\/=]/i;
const isString = typeof str === "string" || str instanceof String;
if (!isString) {
let invalidType;
if (str === null) {
invalidType = "null";
} else {
invalidType = typeof str;
if (
invalidType === "object" &&
str.constructor &&
str.constructor.hasOwnProperty("name")
) {
invalidType = str.constructor.name;
} else {
invalidType = `a ${invalidType}`;
}
}
throw new TypeError(`Expected string but received ${invalidType}.`);
}
const len = str.length;
if (!len || len % 4 !== 0 || notBase64.test(str)) {
return false;
}
const firstPaddingChar = str.indexOf("=");
return (
firstPaddingChar === -1 ||
firstPaddingChar === len - 1 ||
(firstPaddingChar === len - 2 && str[len - 1] === "=")
);
}
module.exports = function (octokit, opts) {
return new Promise(async (resolve, reject) => {
// Up front validation
try {
for (const req of ["owner", "repo", "branch"]) {
if (!opts[req]) {
return reject(`'${req}' is a required parameter`);
}
}
if (!opts.changes || !opts.changes.length) {
return reject("No changes provided");
}
if (!opts.batchSize) {
opts.batchSize = 1;
}
if (typeof opts.batchSize !== "number") {
return reject(`batchSize must be a number`);
}
// Destructuring for easier access later
let {
owner,
repo,
base,
branch: branchName,
createBranch,
committer,
author,
changes,
batchSize,
forkFromBaseBranch,
} = opts;
let branchAlreadyExists = true;
let baseTree;
// Does the target branch already exist?
baseTree = await loadRef(octokit, owner, repo, branchName);
if (!baseTree || forkFromBaseBranch) {
if (!createBranch && !baseTree) {
return reject(
`The branch '${branchName}' doesn't exist and createBranch is 'false'`,
);
}
if (!baseTree) {
branchAlreadyExists = false;
}
// If not we use the base branch. If not provided, use the
// default from the repo
if (!base) {
// Work out the default branch
base = (
await octokit.rest.repos.get({
owner,
repo,
})
).data.default_branch;
}
baseTree = await loadRef(octokit, owner, repo, base);
if (!baseTree) {
return reject(`The branch '${base}' doesn't exist`);
}
}
// Create blobs
const commits = [];
for (const change of changes) {
const message = change.message;
if (!message) {
return reject(`changes[].message is a required parameter`);
}
const hasFiles = change.files && Object.keys(change.files).length > 0;
const hasFilesToDelete =
Array.isArray(change.filesToDelete) &&
change.filesToDelete.length > 0;
if (!hasFiles && !hasFilesToDelete) {
return reject(
`either changes[].files or changes[].filesToDelete are required`,
);
}
const treeItems = [];
// Handle file deletions
if (hasFilesToDelete) {
for (const batch of chunk(change.filesToDelete, batchSize)) {
await Promise.all(
batch.map(async (fileName) => {
const exists = await fileExistsInRepo(
octokit,
owner,
repo,
fileName,
baseTree,
);
// If it doesn't exist, and we're not ignoring missing files
// reject the promise
if (!exists && !change.ignoreDeletionFailures) {
return reject(
`The file ${fileName} could not be found in the repo`,
);
}
// At this point it either exists, or we're ignoring failures
if (exists) {
treeItems.push({
path: fileName,
sha: null, // sha as null implies that the file should be deleted
mode: "100644",
type: "commit",
});
}
}),
);
}
}
if (hasFiles) {
for (const batch of chunk(Object.keys(change.files), batchSize)) {
await Promise.all(
batch.map(async (fileName) => {
const properties = change.files[fileName] || "";
const contents = properties.contents || properties;
const mode = properties.mode || "100644";
const type = properties.type || "blob";
if (!contents) {
return reject(`No file contents provided for ${fileName}`);
}
const fileSha = await createBlob(
octokit,
owner,
repo,
contents,
type,
);
treeItems.push({
path: fileName,
sha: fileSha,
mode: mode,
type: type,
});
}),
);
}
}
// no need to issue further requests if there are no updates, creations and deletions
if (treeItems.length === 0) {
continue;
}
// Add those blobs to a tree
const tree = await createTree(
octokit,
owner,
repo,
treeItems,
baseTree,
);
// Create a commit that points to that tree
const commit = await createCommit(
octokit,
owner,
repo,
committer,
author,
message,
tree,
baseTree,
);
// Update the base tree if we have another commit to make
baseTree = commit.sha;
commits.push(commit);
}
// Create a ref that points to that tree
let action = "createRef";
let updateRefBase = "refs/";
// Or if it already exists, we'll update that existing ref
if (branchAlreadyExists) {
action = "updateRef";
updateRefBase = "";
}
await octokit.rest.git[action]({
owner,
repo,
force: true,
ref: `${updateRefBase}heads/${branchName}`,
sha: baseTree,
});
// Return the new branch name so that we can use it later
// e.g. to create a pull request
return resolve({ commits });
} catch (e) {
return reject(e);
}
});
};
async function fileExistsInRepo(octokit, owner, repo, path, branch) {
try {
await octokit.rest.repos.getContent({
method: "HEAD",
owner,
repo,
path,
ref: branch,
});
return true;
} catch (e) {
return false;
}
}
async function createCommit(
octokit,
owner,
repo,
committer,
author,
message,
tree,
baseTree,
) {
return (
await octokit.rest.git.createCommit({
owner,
repo,
message,
committer,
author,
tree: tree.sha,
parents: [baseTree],
})
).data;
}
async function createTree(octokit, owner, repo, treeItems, baseTree) {
return (
await octokit.rest.git.createTree({
owner,
repo,
tree: treeItems,
base_tree: baseTree,
})
).data;
}
async function createBlob(octokit, owner, repo, contents, type) {
if (type === "commit") {
return contents;
} else {
let content = contents;
if (!isBase64(content)) {
content = Buffer.from(contents).toString("base64");
}
const file = (
await octokit.rest.git.createBlob({
owner,
repo,
content,
encoding: "base64",
})
).data;
return file.sha;
}
}
async function loadRef(octokit, owner, repo, ref) {
try {
const x = await octokit.rest.git.getRef({
owner,
repo,
ref: `heads/${ref}`,
});
return x.data.object.sha;
} catch (e) {
// console.log(e);
}
}
const chunk = (input, size) => {
return input.reduce((arr, item, idx) => {
return idx % size === 0
? [...arr, [item]]
: [...arr.slice(0, -1), [...arr.slice(-1)[0], item]];
}, []);
};