-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
API.ts
1451 lines (1295 loc) · 45.9 KB
/
API.ts
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Base64 } from 'js-base64';
import semaphore from 'semaphore';
import { initial, last, partial, result, trimStart, trim } from 'lodash';
import { oneLine } from 'common-tags';
import {
getAllResponses,
APIError,
EditorialWorkflowError,
localForage,
basename,
readFileMetadata,
CMS_BRANCH_PREFIX,
generateContentKey,
DEFAULT_PR_BODY,
MERGE_COMMIT_MESSAGE,
PreviewState,
parseContentKey,
branchFromContentKey,
isCMSLabel,
labelToStatus,
statusToLabel,
contentKeyFromBranch,
requestWithBackoff,
unsentRequest,
throwOnConflictingBranches,
} from 'netlify-cms-lib-util';
import { dirname } from 'path';
import type {
AssetProxy,
DataFile,
PersistOptions,
FetchError,
ApiRequest,
} from 'netlify-cms-lib-util';
import type { Semaphore } from 'semaphore';
import type { Octokit } from '@octokit/rest';
type GitHubUser = Octokit.UsersGetAuthenticatedResponse;
type GitCreateTreeParamsTree = Octokit.GitCreateTreeParamsTree;
type GitHubCompareCommit = Octokit.ReposCompareCommitsResponseCommitsItem;
type GitHubAuthor = Octokit.GitCreateCommitResponseAuthor;
type GitHubCommitter = Octokit.GitCreateCommitResponseCommitter;
type GitHubPull = Octokit.PullsListResponseItem;
export const API_NAME = 'GitHub';
export const MOCK_PULL_REQUEST = -1;
export interface Config {
apiRoot?: string;
token?: string;
branch?: string;
useOpenAuthoring?: boolean;
repo?: string;
originRepo?: string;
squashMerges: boolean;
initialWorkflowStatus: string;
cmsLabelPrefix: string;
}
interface TreeFile {
type: 'blob' | 'tree';
sha: string;
path: string;
raw?: string;
}
type Override<T, U> = Pick<T, Exclude<keyof T, keyof U>> & U;
type TreeEntry = Override<GitCreateTreeParamsTree, { sha: string | null }>;
type GitHubCompareCommits = GitHubCompareCommit[];
type GitHubCompareFile = Octokit.ReposCompareCommitsResponseFilesItem & {
previous_filename?: string;
};
type GitHubCompareFiles = GitHubCompareFile[];
enum GitHubCommitStatusState {
Error = 'error',
Failure = 'failure',
Pending = 'pending',
Success = 'success',
}
export enum PullRequestState {
Open = 'open',
Closed = 'closed',
All = 'all',
}
type GitHubCommitStatus = Octokit.ReposListStatusesForRefResponseItem & {
state: GitHubCommitStatusState;
};
interface MetaDataObjects {
entry: { path: string; sha: string };
files: MediaFile[];
}
export interface Metadata {
type: string;
objects: MetaDataObjects;
branch: string;
status: string;
pr?: {
number: number;
head: string | { sha: string };
};
collection: string;
commitMessage: string;
version?: string;
user: string;
title?: string;
description?: string;
timeStamp: string;
}
export interface BlobArgs {
sha: string;
repoURL: string;
parseText: boolean;
}
type Param = string | number | undefined;
type Options = RequestInit & { params?: Record<string, Param | Record<string, Param> | string[]> };
type MediaFile = {
sha: string;
path: string;
};
function withCmsLabel(pr: GitHubPull, cmsLabelPrefix: string) {
return pr.labels.some(l => isCMSLabel(l.name, cmsLabelPrefix));
}
function withoutCmsLabel(pr: GitHubPull, cmsLabelPrefix: string) {
return pr.labels.every(l => !isCMSLabel(l.name, cmsLabelPrefix));
}
function getTreeFiles(files: GitHubCompareFiles) {
const treeFiles = files.reduce((arr, file) => {
if (file.status === 'removed') {
// delete the file
arr.push({ sha: null, path: file.filename });
} else if (file.status === 'renamed') {
// delete the previous file
arr.push({ sha: null, path: file.previous_filename as string });
// add the renamed file
arr.push({ sha: file.sha, path: file.filename });
} else {
// add the file
arr.push({ sha: file.sha, path: file.filename });
}
return arr;
}, [] as { sha: string | null; path: string }[]);
return treeFiles;
}
export type Diff = {
path: string;
newFile: boolean;
sha: string;
binary: boolean;
};
let migrationNotified = false;
export default class API {
apiRoot: string;
token: string;
branch: string;
useOpenAuthoring?: boolean;
repo: string;
originRepo: string;
repoOwner: string;
repoName: string;
originRepoOwner: string;
originRepoName: string;
repoURL: string;
originRepoURL: string;
mergeMethod: string;
initialWorkflowStatus: string;
cmsLabelPrefix: string;
_userPromise?: Promise<GitHubUser>;
_metadataSemaphore?: Semaphore;
commitAuthor?: {};
constructor(config: Config) {
this.apiRoot = config.apiRoot || 'https://api.github.com';
this.token = config.token || '';
this.branch = config.branch || 'master';
this.useOpenAuthoring = config.useOpenAuthoring;
this.repo = config.repo || '';
this.originRepo = config.originRepo || this.repo;
this.repoURL = `/repos/${this.repo}`;
// when not in 'useOpenAuthoring' mode originRepoURL === repoURL
this.originRepoURL = `/repos/${this.originRepo}`;
const [repoParts, originRepoParts] = [this.repo.split('/'), this.originRepo.split('/')];
this.repoOwner = repoParts[0];
this.repoName = repoParts[1];
this.originRepoOwner = originRepoParts[0];
this.originRepoName = originRepoParts[1];
this.mergeMethod = config.squashMerges ? 'squash' : 'merge';
this.cmsLabelPrefix = config.cmsLabelPrefix;
this.initialWorkflowStatus = config.initialWorkflowStatus;
}
static DEFAULT_COMMIT_MESSAGE = 'Automatically generated by Netlify CMS';
user(): Promise<{ name: string; login: string }> {
if (!this._userPromise) {
this._userPromise = this.getUser();
}
return this._userPromise;
}
getUser() {
return this.request('/user') as Promise<GitHubUser>;
}
async hasWriteAccess() {
try {
const result: Octokit.ReposGetResponse = await this.request(this.repoURL);
// update config repoOwner to avoid case sensitivity issues with GitHub
this.repoOwner = result.owner.login;
return result.permissions.push;
} catch (error) {
console.error('Problem fetching repo data from GitHub');
throw error;
}
}
reset() {
// no op
}
requestHeaders(headers = {}) {
const baseHeader: Record<string, string> = {
'Content-Type': 'application/json; charset=utf-8',
...headers,
};
if (this.token) {
baseHeader.Authorization = `token ${this.token}`;
return Promise.resolve(baseHeader);
}
return Promise.resolve(baseHeader);
}
parseJsonResponse(response: Response) {
return response.json().then(json => {
if (!response.ok) {
return Promise.reject(json);
}
return json;
});
}
urlFor(path: string, options: Options) {
const params = [];
if (options.params) {
for (const key in options.params) {
params.push(`${key}=${encodeURIComponent(options.params[key] as string)}`);
}
}
if (params.length) {
path += `?${params.join('&')}`;
}
return this.apiRoot + path;
}
parseResponse(response: Response) {
const contentType = response.headers.get('Content-Type');
if (contentType && contentType.match(/json/)) {
return this.parseJsonResponse(response);
}
const textPromise = response.text().then(text => {
if (!response.ok) {
return Promise.reject(text);
}
return text;
});
return textPromise;
}
handleRequestError(error: FetchError, responseStatus: number) {
throw new APIError(error.message, responseStatus, API_NAME);
}
buildRequest(req: ApiRequest) {
return req;
}
async request(
path: string,
options: Options = {},
parser = (response: Response) => this.parseResponse(response),
) {
options = { cache: 'no-cache', ...options };
const headers = await this.requestHeaders(options.headers || {});
const url = this.urlFor(path, options);
let responseStatus = 500;
try {
const req = unsentRequest.fromFetchArguments(url, {
...options,
headers,
}) as unknown as ApiRequest;
const response = await requestWithBackoff(this, req);
responseStatus = response.status;
const parsedResponse = await parser(response);
return parsedResponse;
} catch (error) {
return this.handleRequestError(error, responseStatus);
}
}
nextUrlProcessor() {
return (url: string) => url;
}
async requestAllPages<T>(url: string, options: Options = {}) {
options = { cache: 'no-cache', ...options };
const headers = await this.requestHeaders(options.headers || {});
const processedURL = this.urlFor(url, options);
const allResponses = await getAllResponses(
processedURL,
{ ...options, headers },
'next',
this.nextUrlProcessor(),
);
const pages: T[][] = await Promise.all(
allResponses.map((res: Response) => this.parseResponse(res)),
);
return ([] as T[]).concat(...pages);
}
generateContentKey(collectionName: string, slug: string) {
const contentKey = generateContentKey(collectionName, slug);
if (!this.useOpenAuthoring) {
return contentKey;
}
return `${this.repo}/${contentKey}`;
}
parseContentKey(contentKey: string) {
if (!this.useOpenAuthoring) {
return parseContentKey(contentKey);
}
return parseContentKey(contentKey.substring(this.repo.length + 1));
}
checkMetadataRef() {
return this.request(`${this.repoURL}/git/refs/meta/_netlify_cms`)
.then(response => response.object)
.catch(() => {
// Meta ref doesn't exist
const readme = {
raw: '# Netlify CMS\n\nThis tree is used by the Netlify CMS to store metadata information for specific files and branches.',
};
return this.uploadBlob(readme)
.then(item =>
this.request(`${this.repoURL}/git/trees`, {
method: 'POST',
body: JSON.stringify({
tree: [{ path: 'README.md', mode: '100644', type: 'blob', sha: item.sha }],
}),
}),
)
.then(tree => this.commit('First Commit', tree))
.then(response => this.createRef('meta', '_netlify_cms', response.sha))
.then(response => response.object);
});
}
async storeMetadata(key: string, data: Metadata) {
// semaphore ensures metadata updates are always ordered, even if
// calls to storeMetadata are not. concurrent metadata updates
// will result in the metadata branch being unable to update.
if (!this._metadataSemaphore) {
this._metadataSemaphore = semaphore(1);
}
return new Promise((resolve, reject) =>
this._metadataSemaphore?.take(async () => {
try {
const branchData = await this.checkMetadataRef();
const file = { path: `${key}.json`, raw: JSON.stringify(data) };
await this.uploadBlob(file);
const changeTree = await this.updateTree(branchData.sha, [file as TreeFile]);
const { sha } = await this.commit(`Updating “${key}” metadata`, changeTree);
await this.patchRef('meta', '_netlify_cms', sha);
await localForage.setItem(`gh.meta.${key}`, {
expires: Date.now() + 300000, // In 5 minutes
data,
});
this._metadataSemaphore?.leave();
resolve();
} catch (err) {
reject(err);
}
}),
);
}
deleteMetadata(key: string) {
if (!this._metadataSemaphore) {
this._metadataSemaphore = semaphore(1);
}
return new Promise(resolve =>
this._metadataSemaphore?.take(async () => {
try {
const branchData = await this.checkMetadataRef();
const file = { path: `${key}.json`, sha: null };
const changeTree = await this.updateTree(branchData.sha, [file]);
const { sha } = await this.commit(`Deleting “${key}” metadata`, changeTree);
await this.patchRef('meta', '_netlify_cms', sha);
this._metadataSemaphore?.leave();
resolve();
} catch (err) {
this._metadataSemaphore?.leave();
resolve();
}
}),
);
}
async retrieveMetadataOld(key: string): Promise<Metadata> {
console.log(
'%c Checking for MetaData files',
'line-height: 30px;text-align: center;font-weight: bold',
);
const metadataRequestOptions = {
params: { ref: 'refs/meta/_netlify_cms' },
headers: { Accept: 'application/vnd.github.v3.raw' },
};
function errorHandler(err: Error) {
if (err.message === 'Not Found') {
console.log(
'%c %s does not have metadata',
'line-height: 30px;text-align: center;font-weight: bold',
key,
);
}
throw err;
}
if (!this.useOpenAuthoring) {
const result = await this.request(
`${this.repoURL}/contents/${key}.json`,
metadataRequestOptions,
)
.then((response: string) => JSON.parse(response))
.catch(errorHandler);
return result;
}
const [user, repo] = key.split('/');
const result = this.request(
`/repos/${user}/${repo}/contents/${key}.json`,
metadataRequestOptions,
)
.then((response: string) => JSON.parse(response))
.catch(errorHandler);
return result;
}
async getPullRequests(
head: string | undefined,
state: PullRequestState,
predicate: (pr: GitHubPull) => boolean,
) {
const pullRequests: Octokit.PullsListResponse = await this.requestAllPages(
`${this.originRepoURL}/pulls`,
{
params: {
...(head ? { head: await this.getHeadReference(head) } : {}),
base: this.branch,
state,
per_page: 100,
},
},
);
return pullRequests.filter(
pr => pr.head.ref.startsWith(`${CMS_BRANCH_PREFIX}/`) && predicate(pr),
);
}
async getOpenAuthoringPullRequest(branch: string, pullRequests: GitHubPull[]) {
// we can't use labels when using open authoring
// since the contributor doesn't have access to set labels
// a branch without a pr (or a closed pr) means a 'draft' entry
// a branch with an opened pr means a 'pending_review' entry
const data = await this.getBranch(branch).catch(() => {
throw new EditorialWorkflowError('content is not under editorial workflow', true);
});
// since we get all (open and closed) pull requests by branch name, make sure to filter by head sha
const pullRequest = pullRequests.filter(pr => pr.head.sha === data.commit.sha)[0];
// if no pull request is found for the branch we return a mocked one
if (!pullRequest) {
try {
return {
head: { sha: data.commit.sha },
number: MOCK_PULL_REQUEST,
labels: [{ name: statusToLabel(this.initialWorkflowStatus, this.cmsLabelPrefix) }],
state: PullRequestState.Open,
} as GitHubPull;
} catch (e) {
throw new EditorialWorkflowError('content is not under editorial workflow', true);
}
} else {
pullRequest.labels = pullRequest.labels.filter(l => !isCMSLabel(l.name, this.cmsLabelPrefix));
const cmsLabel =
pullRequest.state === PullRequestState.Closed
? { name: statusToLabel(this.initialWorkflowStatus, this.cmsLabelPrefix) }
: { name: statusToLabel('pending_review', this.cmsLabelPrefix) };
pullRequest.labels.push(cmsLabel as Octokit.PullsGetResponseLabelsItem);
return pullRequest;
}
}
async getBranchPullRequest(branch: string) {
if (this.useOpenAuthoring) {
const pullRequests = await this.getPullRequests(branch, PullRequestState.All, () => true);
return this.getOpenAuthoringPullRequest(branch, pullRequests);
} else {
const pullRequests = await this.getPullRequests(branch, PullRequestState.Open, pr =>
withCmsLabel(pr, this.cmsLabelPrefix),
);
if (pullRequests.length <= 0) {
throw new EditorialWorkflowError('content is not under editorial workflow', true);
}
return pullRequests[0];
}
}
async getPullRequestCommits(number: number) {
if (number === MOCK_PULL_REQUEST) {
return [];
}
try {
const commits: Octokit.PullsListCommitsResponseItem[] = await this.request(
`${this.originRepoURL}/pulls/${number}/commits`,
);
return commits;
} catch (e) {
console.log(e);
return [];
}
}
async retrieveUnpublishedEntryData(contentKey: string) {
const { collection, slug } = this.parseContentKey(contentKey);
const branch = branchFromContentKey(contentKey);
const pullRequest = await this.getBranchPullRequest(branch);
const { files } = await this.getDifferences(this.branch, pullRequest.head.sha);
const diffs = await Promise.all(files.map(file => this.diffFromFile(file)));
const label = pullRequest.labels.find(l => isCMSLabel(l.name, this.cmsLabelPrefix)) as {
name: string;
};
const status = labelToStatus(label.name, this.cmsLabelPrefix);
const updatedAt = pullRequest.updated_at;
return {
collection,
slug,
status,
diffs: diffs.map(d => ({ path: d.path, newFile: d.newFile, id: d.sha })),
updatedAt,
};
}
async readFile(
path: string,
sha?: string | null,
{
branch = this.branch,
repoURL = this.repoURL,
parseText = true,
}: {
branch?: string;
repoURL?: string;
parseText?: boolean;
} = {},
) {
if (!sha) {
sha = await this.getFileSha(path, { repoURL, branch });
}
const content = await this.fetchBlobContent({ sha: sha as string, repoURL, parseText });
return content;
}
async readFileMetadata(path: string, sha: string | null | undefined) {
const fetchFileMetadata = async () => {
try {
const result: Octokit.ReposListCommitsResponse = await this.request(
`${this.originRepoURL}/commits`,
{
params: { path, sha: this.branch },
},
);
const { commit } = result[0];
return {
author: commit.author.name || commit.author.email,
updatedOn: commit.author.date,
};
} catch (e) {
return { author: '', updatedOn: '' };
}
};
const fileMetadata = await readFileMetadata(sha, fetchFileMetadata, localForage);
return fileMetadata;
}
async fetchBlobContent({ sha, repoURL, parseText }: BlobArgs) {
const result: Octokit.GitGetBlobResponse = await this.request(`${repoURL}/git/blobs/${sha}`, {
cache: 'force-cache',
});
if (parseText) {
// treat content as a utf-8 string
const content = Base64.decode(result.content);
return content;
} else {
// treat content as binary and convert to blob
const content = Base64.atob(result.content);
const byteArray = new Uint8Array(content.length);
for (let i = 0; i < content.length; i++) {
byteArray[i] = content.charCodeAt(i);
}
const blob = new Blob([byteArray]);
return blob;
}
}
async listFiles(
path: string,
{ repoURL = this.repoURL, branch = this.branch, depth = 1 } = {},
): Promise<{ type: string; id: string; name: string; path: string; size: number }[]> {
const folder = trim(path, '/');
try {
const result: Octokit.GitGetTreeResponse = await this.request(
`${repoURL}/git/trees/${branch}:${folder}`,
{
// GitHub API supports recursive=1 for getting the entire recursive tree
// or omitting it to get the non-recursive tree
params: depth > 1 ? { recursive: 1 } : {},
},
);
return (
result.tree
// filter only files and up to the required depth
.filter(file => file.type === 'blob' && file.path.split('/').length <= depth)
.map(file => ({
type: file.type,
id: file.sha,
name: basename(file.path),
path: `${folder}/${file.path}`,
size: file.size!,
}))
);
} catch (err) {
if (err && err.status === 404) {
console.log('This 404 was expected and handled appropriately.');
return [];
} else {
throw err;
}
}
}
filterOpenAuthoringBranches = async (branch: string) => {
try {
const pullRequest = await this.getBranchPullRequest(branch);
const { state: currentState, merged_at: mergedAt } = pullRequest;
if (
pullRequest.number !== MOCK_PULL_REQUEST &&
currentState === PullRequestState.Closed &&
mergedAt
) {
// pr was merged, delete branch
await this.deleteBranch(branch);
return { branch, filter: false };
} else {
return { branch, filter: true };
}
} catch (e) {
return { branch, filter: false };
}
};
async migrateToVersion1(pullRequest: GitHubPull, metadata: Metadata) {
// hard code key/branch generation logic to ignore future changes
const oldContentKey = pullRequest.head.ref.substring(`cms/`.length);
const newContentKey = `${metadata.collection}/${oldContentKey}`;
const newBranchName = `cms/${newContentKey}`;
// retrieve or create new branch and pull request in new format
const branch = await this.getBranch(newBranchName).catch(() => undefined);
if (!branch) {
await this.createBranch(newBranchName, pullRequest.head.sha as string);
}
const pr =
(await this.getPullRequests(newBranchName, PullRequestState.All, () => true))[0] ||
(await this.createPR(pullRequest.title, newBranchName));
// store new metadata
const newMetadata = {
...metadata,
pr: {
number: pr.number,
head: pr.head.sha,
},
branch: newBranchName,
version: '1',
};
await this.storeMetadata(newContentKey, newMetadata);
// remove old data
await this.closePR(pullRequest.number);
await this.deleteBranch(pullRequest.head.ref);
await this.deleteMetadata(oldContentKey);
return { metadata: newMetadata, pullRequest: pr };
}
async migrateToPullRequestLabels(pullRequest: GitHubPull, metadata: Metadata) {
await this.setPullRequestStatus(pullRequest, metadata.status);
const contentKey = pullRequest.head.ref.substring(`cms/`.length);
await this.deleteMetadata(contentKey);
}
async migratePullRequest(pullRequest: GitHubPull, countMessage: string) {
const { number } = pullRequest;
console.log(`Migrating Pull Request '${number}' (${countMessage})`);
const contentKey = contentKeyFromBranch(pullRequest.head.ref);
let metadata = await this.retrieveMetadataOld(contentKey).catch(() => undefined);
if (!metadata) {
console.log(`Skipped migrating Pull Request '${number}' (${countMessage})`);
return;
}
let newNumber = number;
if (!metadata.version) {
console.log(`Migrating Pull Request '${number}' to version 1`);
// migrate branch from cms/slug to cms/collection/slug
try {
({ metadata, pullRequest } = await this.migrateToVersion1(pullRequest, metadata));
} catch (e) {
console.log(`Failed to migrate Pull Request '${number}' to version 1. See error below.`);
console.error(e);
return;
}
newNumber = pullRequest.number;
console.log(
`Done migrating Pull Request '${number}' to version 1. New pull request '${newNumber}' created.`,
);
}
if (metadata.version === '1') {
console.log(`Migrating Pull Request '${newNumber}' to labels`);
// migrate branch from using orphan ref to store metadata to pull requests label
await this.migrateToPullRequestLabels(pullRequest, metadata);
console.log(`Done migrating Pull Request '${newNumber}' to labels`);
}
console.log(
`Done migrating Pull Request '${
number === newNumber ? newNumber : `${number} => ${newNumber}`
}'`,
);
}
async getOpenAuthoringBranches() {
const cmsBranches = await this.requestAllPages<Octokit.GitListMatchingRefsResponseItem>(
`${this.repoURL}/git/refs/heads/cms/${this.repo}`,
).catch(() => [] as Octokit.GitListMatchingRefsResponseItem[]);
return cmsBranches;
}
async listUnpublishedBranches() {
console.log(
'%c Checking for Unpublished entries',
'line-height: 30px;text-align: center;font-weight: bold',
);
let branches: string[];
if (this.useOpenAuthoring) {
// open authoring branches can exist without a pr
const cmsBranches: Octokit.GitListMatchingRefsResponse =
await this.getOpenAuthoringBranches();
branches = cmsBranches.map(b => b.ref.substring('refs/heads/'.length));
// filter irrelevant branches
const branchesWithFilter = await Promise.all(
branches.map(b => this.filterOpenAuthoringBranches(b)),
);
branches = branchesWithFilter.filter(b => b.filter).map(b => b.branch);
} else {
// backwards compatibility code, get relevant pull requests and migrate them
const pullRequests = await this.getPullRequests(
undefined,
PullRequestState.Open,
pr => !pr.head.repo.fork && withoutCmsLabel(pr, this.cmsLabelPrefix),
);
let prCount = 0;
for (const pr of pullRequests) {
if (!migrationNotified) {
migrationNotified = true;
alert(oneLine`
Netlify CMS is adding labels to ${pullRequests.length} of your Editorial Workflow
entries. The "Workflow" tab will be unavailable during this migration. You may use other
areas of the CMS during this time. Note that closing the CMS will pause the migration.
`);
}
prCount = prCount + 1;
await this.migratePullRequest(pr, `${prCount} of ${pullRequests.length}`);
}
const cmsPullRequests = await this.getPullRequests(undefined, PullRequestState.Open, pr =>
withCmsLabel(pr, this.cmsLabelPrefix),
);
branches = cmsPullRequests.map(pr => pr.head.ref);
}
return branches;
}
/**
* Retrieve statuses for a given SHA. Unrelated to the editorial workflow
* concept of entry "status". Useful for things like deploy preview links.
*/
async getStatuses(collectionName: string, slug: string) {
const contentKey = this.generateContentKey(collectionName, slug);
const branch = branchFromContentKey(contentKey);
const pullRequest = await this.getBranchPullRequest(branch);
const sha = pullRequest.head.sha;
const resp: { statuses: GitHubCommitStatus[] } = await this.request(
`${this.originRepoURL}/commits/${sha}/status`,
);
return resp.statuses.map(s => ({
context: s.context,
target_url: s.target_url,
state:
s.state === GitHubCommitStatusState.Success ? PreviewState.Success : PreviewState.Other,
}));
}
async persistFiles(dataFiles: DataFile[], mediaFiles: AssetProxy[], options: PersistOptions) {
const files = mediaFiles.concat(dataFiles);
const uploadPromises = files.map(file => this.uploadBlob(file));
await Promise.all(uploadPromises);
if (!options.useWorkflow) {
return this.getDefaultBranch()
.then(branchData =>
this.updateTree(branchData.commit.sha, files as { sha: string; path: string }[]),
)
.then(changeTree => this.commit(options.commitMessage, changeTree))
.then(response => this.patchBranch(this.branch, response.sha));
} else {
const mediaFilesList = (mediaFiles as { sha: string; path: string }[]).map(
({ sha, path }) => ({
path: trimStart(path, '/'),
sha,
}),
);
const slug = dataFiles[0].slug;
return this.editorialWorkflowGit(files as TreeFile[], slug, mediaFilesList, options);
}
}
async getFileSha(path: string, { repoURL = this.repoURL, branch = this.branch } = {}) {
/**
* We need to request the tree first to get the SHA. We use extended SHA-1
* syntax (<rev>:<path>) to get a blob from a tree without having to recurse
* through the tree.
*/
const pathArray = path.split('/');
const filename = last(pathArray);
const directory = initial(pathArray).join('/');
const fileDataPath = encodeURIComponent(directory);
const fileDataURL = `${repoURL}/git/trees/${branch}:${fileDataPath}`;
const result: Octokit.GitGetTreeResponse = await this.request(fileDataURL);
const file = result.tree.find(file => file.path === filename);
if (file) {
return file.sha;
} else {
throw new APIError('Not Found', 404, API_NAME);
}
}
async deleteFiles(paths: string[], message: string) {
if (this.useOpenAuthoring) {
return Promise.reject('Cannot delete published entries as an Open Authoring user!');
}
const branchData = await this.getDefaultBranch();
const files = paths.map(path => ({ path, sha: null }));
const changeTree = await this.updateTree(branchData.commit.sha, files);
const commit = await this.commit(message, changeTree);
await this.patchBranch(this.branch, commit.sha);
}
async createBranchAndPullRequest(branchName: string, sha: string, commitMessage: string) {
await this.createBranch(branchName, sha);
return this.createPR(commitMessage, branchName);
}
async updatePullRequestLabels(number: number, labels: string[]) {
await this.request(`${this.repoURL}/issues/${number}/labels`, {
method: 'PUT',
body: JSON.stringify({ labels }),
});
}
// async since it is overridden in a child class
async diffFromFile(diff: Octokit.ReposCompareCommitsResponseFilesItem): Promise<Diff> {
return {
path: diff.filename,
newFile: diff.status === 'added',
sha: diff.sha,
// media files diffs don't have a patch attribute, except svg files
// renamed files don't have a patch attribute too
binary: (diff.status !== 'renamed' && !diff.patch) || diff.filename.endsWith('.svg'),
};
}
async editorialWorkflowGit(
files: TreeFile[],
slug: string,
mediaFilesList: MediaFile[],
options: PersistOptions,
) {
const contentKey = this.generateContentKey(options.collectionName as string, slug);
const branch = branchFromContentKey(contentKey);
const unpublished = options.unpublished || false;
if (!unpublished) {
const branchData = await this.getDefaultBranch();
const changeTree = await this.updateTree(branchData.commit.sha, files);
const commitResponse = await this.commit(options.commitMessage, changeTree);
if (this.useOpenAuthoring) {
await this.createBranch(branch, commitResponse.sha);
} else {
const pr = await this.createBranchAndPullRequest(
branch,
commitResponse.sha,
options.commitMessage,
);
await this.setPullRequestStatus(pr, options.status || this.initialWorkflowStatus);
}
} else {
// Entry is already on editorial review workflow - commit to existing branch
const { files: diffFiles } = await this.getDifferences(
this.branch,
await this.getHeadReference(branch),
);
const diffs = await Promise.all(diffFiles.map(file => this.diffFromFile(file)));
// mark media files to remove
const mediaFilesToRemove: { path: string; sha: string | null }[] = [];
for (const diff of diffs.filter(d => d.binary)) {
if (!mediaFilesList.some(file => file.path === diff.path)) {
mediaFilesToRemove.push({ path: diff.path, sha: null });
}
}
// rebase the branch before applying new changes
const rebasedHead = await this.rebaseBranch(branch);
const treeFiles = mediaFilesToRemove.concat(files);
const changeTree = await this.updateTree(rebasedHead.sha, treeFiles, branch);
const commit = await this.commit(options.commitMessage, changeTree);
return this.patchBranch(branch, commit.sha, { force: true });
}
}