-
Notifications
You must be signed in to change notification settings - Fork 595
/
Copy pathgithub.ts
1475 lines (1305 loc) · 52.4 KB
/
github.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
namespace pxt.github {
export interface GHRef {
ref: string;
url: string;
object: {
sha: string;
type: string;
url: string;
}
}
/**
* Commit user info
*/
export interface UserInfo {
date: string; // "2014-11-07T22:01:45Z",
name: string; // "Scott Chacon",
email: string; // "schacon@gmail.com"
}
export interface SHAObject {
url: string;
sha: string;
}
export interface TreeEntry extends SHAObject {
path: string; // ".clang-format",
mode: string; // "100644",
type: "blob" | "tree";
size?: number; // 126,
blobContent?: string; // this is added for caching
}
export interface Tree extends SHAObject {
tree: TreeEntry[];
truncated: boolean;
}
export interface CommitInfo extends SHAObject {
author: UserInfo;
committer: UserInfo;
message: string; // "added readme, because im a good github citizen",
tree: SHAObject;
}
export interface Commit extends SHAObject {
author: UserInfo;
committer: UserInfo;
message: string; // "added readme, because im a good github citizen",
tag?: string;
parents: SHAObject[]; // commit[]
tree: Tree; // tree
}
export let token: string = null;
export interface RefsResult {
refs: pxt.Map<string>;
head?: string;
}
export interface FileContent {
encoding: string;
content: string;
size: number;
sha: string;
download_url: string;
}
interface CommitComment {
id: number;
body: string;
path?: string;
position?: number;
user: User;
}
export interface GHTutorialResponse {
path: string;
markdown: string | { filename: string, repo: GHTutorialRepoInfo };
dependencies: GHTutorialRepoInfo[];
}
export interface GHTutorialRepoInfo {
repo: string;
files: pxt.Map<string>;
sha: string;
fileHash: string;
subPath?: string;
version?: string;
latestVersion?: string;
}
export let forceProxy = false;
function hasProxy() {
if (forceProxy)
return true;
if (U.isNodeJS)
return false // bypass proxy for CLI
if (pxt?.appTarget?.cloud?.noGithubProxy)
return false // target requests no proxy
return true
}
function shouldUseProxy(force?: boolean) {
if (forceProxy)
return true;
if (token && !force)
return false
return hasProxy();
}
export let handleGithubNetworkError: (opts: U.HttpRequestOptions, e: any) => boolean;
const isPrivateRepoCache: pxt.Map<boolean> = {};
export interface CachedPackage {
files: Map<string>;
}
// caching
export interface IGithubDb {
latestVersionAsync(repopath: string, config: PackagesConfig): Promise<string>;
loadConfigAsync(repopath: string, tag: string): Promise<pxt.PackageConfig>;
loadPackageAsync(repopath: string, tag: string): Promise<CachedPackage>;
loadTutorialMarkdown(repopath: string, tag?: string): Promise<CachedPackage>;
cacheReposAsync(response: GHTutorialResponse): Promise<void>;
}
function ghRequestAsync(options: U.HttpRequestOptions) {
options.method = options.method ?? "GET";
// call github request with existing token
// if the request fails and the token is clear, try again with the token
return workAsync(!!token)
function workAsync(canRetry: boolean): Promise<U.HttpResponse> {
const opts = U.clone(options) as U.HttpRequestOptions;
if (token) {
if (!opts.headers) opts.headers = {}
if (opts.url == GRAPHQL_URL)
opts.headers['Authorization'] = `bearer ${token}`
else {
// defeat browser cache when signed in
opts.url = pxt.BrowserUtils.cacheBustingUrl(opts.url);
opts.headers['Authorization'] = `token ${token}`
}
}
opts.allowHttpErrors = opts.allowHttpErrors ?? false;
return U.requestAsync(opts)
.catch(e => {
pxt.tickEvent("github.error", { statusCode: e.statusCode });
if (handleGithubNetworkError) {
const retry = handleGithubNetworkError(opts, e)
// retry if it may fix the issue
if (retry) return workAsync(false);
}
throw e;
});
}
}
function ghGetJsonAsync(url: string) {
return ghRequestAsync({ url, method: "GET" }).then(resp => resp.json)
}
function ghProxyWithCdnJsonAsync(path: string) {
return Cloud.apiRequestWithCdnAsync({
url: "gh/" + path,
forceLiveEndpoint: true
}).then(r => r.json);
}
function ghProxyHandleException(e: any) {
pxt.log(`github proxy error: ${e.message}`)
pxt.debug(e);
}
export function isOrgAsync(owner: string): Promise<boolean> {
return ghRequestAsync({ url: `https://api.github.com/orgs/${owner}`, method: "GET", allowHttpErrors: true })
.then(resp => resp.statusCode == 200);
}
export class MemoryGithubDb implements IGithubDb {
private latestVersions: pxt.Map<string> = {};
private configs: pxt.Map<pxt.PackageConfig> = {};
private packages: pxt.Map<CachedPackage> = {};
private proxyWithCdnLoadPackageAsync(repopath: string, tag: string): Promise<CachedPackage> {
// cache lookup
const key = `${repopath}/${tag}`;
let res = this.packages[key];
if (res) {
pxt.debug(`github cache ${repopath}/${tag}/text`);
return Promise.resolve(res);
}
// load and cache
const parsed = parseRepoId(repopath)
return ghProxyWithCdnJsonAsync(join(parsed.slug, tag, parsed.fileName, "text"))
.then(v => this.packages[key] = { files: v });
}
private cacheConfig(key: string, v: string) {
const cfg = pxt.Package.parseAndValidConfig(v);
this.configs[key] = cfg;
return U.clone(cfg);
}
async loadConfigAsync(repopath: string, tag: string): Promise<pxt.PackageConfig> {
if (!tag) {
pxt.debug(`dep: default to master branch`)
tag = "master";
}
// cache lookup
const key = `${repopath}/${tag}`;
let res = this.configs[key];
if (res) {
pxt.debug(`github cache ${repopath}/${tag}/config`);
return U.clone(res);
}
// download and cache
// try proxy if available
if (hasProxy()) {
try {
const gpkg = await this.proxyWithCdnLoadPackageAsync(repopath, tag)
return this.cacheConfig(key, gpkg.files[pxt.CONFIG_NAME]);
} catch (e) {
ghProxyHandleException(e);
}
}
// if failed, try github apis
const cfg = await downloadTextAsync(repopath, tag, pxt.CONFIG_NAME);
return this.cacheConfig(key, cfg);
}
async latestVersionAsync(repopath: string, config: PackagesConfig): Promise<string> {
let resolved = this.latestVersions[repopath]
if (!resolved) {
pxt.debug(`dep: resolve latest version of ${repopath}`)
this.latestVersions[repopath] = resolved = await pxt.github.latestVersionAsync(repopath, config, true, false)
}
return resolved
}
async loadPackageAsync(repopath: string, tag: string): Promise<CachedPackage> {
if (!tag) {
pxt.debug(`load pkg: default to master branch`)
tag = "master";
}
// try using github proxy first
if (hasProxy()) {
try {
return await this.proxyWithCdnLoadPackageAsync(repopath, tag).then(v => U.clone(v));
} catch (e) {
ghProxyHandleException(e);
}
}
// try using github apis
return await this.githubLoadPackageAsync(repopath, tag);
}
private githubLoadPackageAsync(repopath: string, tag: string): Promise<CachedPackage> {
return tagToShaAsync(repopath, tag)
.then(sha => {
// cache lookup
const key = `${repopath}/${sha}`;
let res = this.packages[key];
if (res) {
pxt.debug(`github cache ${repopath}/${tag}/text`);
return Promise.resolve(U.clone(res));
}
// load and cache
pxt.log(`Downloading ${repopath}/${tag} -> ${sha}`)
return downloadTextAsync(repopath, sha, pxt.CONFIG_NAME)
.then(pkg => {
const current: CachedPackage = {
files: {}
}
current.files[pxt.CONFIG_NAME] = pkg
const cfg: pxt.PackageConfig = JSON.parse(pkg)
return U.promiseMapAll(pxt.allPkgFiles(cfg).slice(1),
fn => downloadTextAsync(repopath, sha, fn)
.then(text => {
current.files[fn] = text
}))
.then(() => {
// cache!
this.packages[key] = current;
return U.clone(current);
})
})
})
}
async loadTutorialMarkdown(repopath: string, tag?: string) {
repopath = normalizeTutorialPath(repopath);
const tutorialResponse = (await downloadMarkdownTutorialInfoAsync(repopath, tag)).resp;
const repo = tutorialResponse.markdown as { filename: string, repo: GHTutorialRepoInfo };
pxt.Util.assert(typeof repo === "object");
await this.cacheReposAsync(tutorialResponse);
return repo.repo;
}
async cacheReposAsync(resp: GHTutorialResponse) {
if (typeof resp.markdown === "object") {
const repo = resp.markdown as { filename: string, repo: GHTutorialRepoInfo };
this.cacheRepo(repo.repo);
}
for (const dep of resp.dependencies) {
this.cacheRepo(dep);
}
}
private cacheRepo(repo: GHTutorialRepoInfo) {
let repopath = repo.repo;
if (repo.subPath) {
repopath += "/" + repo.subPath;
}
let key = repopath
key += "/" + repo.sha;
this.packages[key] = {
files: repo.files
};
if (repo.latestVersion) {
this.cacheLatestVersion(repopath, repo.latestVersion);
}
const config = repo.files["pxt.json"];
if (config) {
const alternateConfigKey = key + "/" + (repo.version || "master");
this.cacheConfig(key, config);
this.cacheConfig(alternateConfigKey, config);
}
}
private cacheLatestVersion(repopath: string, version: string) {
this.latestVersions[repopath] = version;
}
}
function fallbackDownloadTextAsync(parsed: ParsedRepo, commitid: string, filepath: string) {
return ghRequestAsync({
url: "https://api.github.com/repos/" + join(parsed.slug, "contents", parsed.fileName, filepath + "?ref=" + commitid),
method: "GET"
}).then(resp => {
const f = resp.json as FileContent
isPrivateRepoCache[parsed.slug] = true
// if they give us content, just return it
if (f && f.encoding == "base64" && f.content != null) {
return Util.fromUTF8(atob(f.content));
}
// otherwise, go to download URL
return U.httpGetTextAsync(f.download_url);
})
}
export function downloadTextAsync(repopath: string, commitid: string, filepath: string) {
const parsed = parseRepoId(repopath);
// raw.githubusercontent.com doesn't accept ?access_token=... and has wrong CORS settings
// for Authorization: header; so try anonymous access first, and otherwise fetch using API
if (isPrivateRepoCache[parsed.slug])
return fallbackDownloadTextAsync(parsed, commitid, filepath)
return U.requestAsync({
url: "https://raw.githubusercontent.com/" + join(parsed.slug, commitid, parsed.fileName, filepath),
allowHttpErrors: true
}).then(resp => {
if (resp.statusCode == 200)
return resp.text
return fallbackDownloadTextAsync(parsed, commitid, filepath)
})
}
export async function downloadMarkdownTutorialInfoAsync(repopath: string, tag?: string, noCache?: boolean, etag?: string): Promise<{ resp?: GHTutorialResponse, etag?: string }> {
let request = pxt.Cloud.apiRequestWithCdnAsync;
const queryParams = new URLSearchParams();
if (tag) {
queryParams.set("ref", tag);
}
if (noCache) {
queryParams.set("noCache", "1");
request = pxt.Cloud.privateRequestAsync;
}
let url = `ghtutorial/${repopath}`;
url = pxt.BrowserUtils.appendUrlQueryParams(url, queryParams);
const headers: pxt.Map<string> = etag ? { "If-None-Match": etag } : undefined;
const resp = await request(
{
url,
method: "GET",
headers
}
);
let body: GHTutorialResponse;
if (resp.statusCode === 304) {
body = undefined;
}
else {
body = resp.json;
}
return (
{
resp: body,
etag: resp.headers["etag"] as string
}
);
}
export async function downloadTutorialMarkdownAsync(repopath: string, tag?: string) {
return db.loadTutorialMarkdown(repopath, tag);
}
// overriden by client
export let db: IGithubDb = new MemoryGithubDb();
export function authenticatedUserAsync(): Promise<User> {
if (!token) return Promise.resolve(undefined); // no token, bail out
return ghGetJsonAsync("https://api.github.com/user");
}
export function getCommitsAsync(repopath: string, sha: string): Promise<CommitInfo[]> {
const parsed = parseRepoId(repopath);
return ghGetJsonAsync("https://api.github.com/repos/" + parsed.slug + "/commits?sha=" + sha)
.then(objs => objs.map((obj: any) => {
const c = obj.commit;
c.url = obj.url;
c.sha = obj.sha;
return c;
}));
}
export function getCommitAsync(repopath: string, sha: string) {
const parsed = parseRepoId(repopath);
return ghGetJsonAsync("https://api.github.com/repos/" + parsed.slug + "/git/commits/" + sha)
.then((commit: Commit) => ghGetJsonAsync(commit.tree.url + "?recursive=1")
.then((tree: Tree) => {
commit.tree = tree
return commit
}))
}
// type=blob
export interface CreateBlobReq {
content: string;
encoding: "utf-8" | "base64";
}
// type=tree
export interface CreateTreeReq {
base_tree: string; // sha
tree: TreeEntry[];
}
// type=commit
export interface CreateCommitReq {
message: string;
parents: string[]; // shas
tree: string; // sha
}
function ghPostAsync(path: string, data: any, headers?: any, method?: string): Promise<any> {
// need to handle 204
return ghRequestAsync({
url: /^https:/.test(path) ? path : "https://api.github.com/repos/" + path,
headers,
method: method || "POST",
data: data,
successCodes: [200, 201, 202, 204]
}).then(resp => resp.json);
}
export function createObjectAsync(repopath: string, type: string, data: any) {
const parsed = parseRepoId(repopath);
return ghPostAsync(parsed.slug + "/git/" + type + "s", data)
.then((resp: SHAObject) => resp.sha)
}
export function postCommitComment(repopath: string, commitSha: string, body: string, path?: string, position?: number) {
const parsed = parseRepoId(repopath);
return ghPostAsync(`${parsed.slug}/commits/${commitSha}/comments`, {
body, path, position
})
.then((resp: CommitComment) => resp.id);
}
export async function fastForwardAsync(repopath: string, branch: string, commitid: string) {
const parsed = parseRepoId(repopath);
const resp = await ghRequestAsync({
url: `https://api.github.com/repos/${parsed.slug}/git/refs/heads/${branch}`,
method: "PATCH",
allowHttpErrors: true,
data: {
sha: commitid,
force: false
}
})
return (resp.statusCode == 200)
}
export async function putFileAsync(repopath: string, path: string, content: string) {
const parsed = parseRepoId(repopath);
await ghRequestAsync({
url: `https://api.github.com/repos/${pxt.github.join(parsed.slug, "contents", parsed.fileName, path)}`,
method: "PUT",
allowHttpErrors: true,
data: {
message: lf("Initialize empty repo"),
content: btoa(U.toUTF8(content)),
branch: "master"
},
successCodes: [201]
})
}
export async function createTagAsync(repopath: string, tag: string, commitid: string) {
await ghPostAsync(repopath + "/git/refs", {
ref: "refs/tags/" + tag,
sha: commitid
})
}
export async function createReleaseAsync(repopath: string, tag: string, commitid: string) {
await ghPostAsync(repopath + "/releases", {
tag_name: tag,
target_commitish: commitid,
name: tag,
draft: false,
prerelease: false
})
}
export async function createPRFromBranchAsync(repopath: string, baseBranch: string,
headBranch: string, title: string, msg?: string) {
const res = await ghPostAsync(repopath + "/pulls", {
title: title,
body: msg || lf("Automatically created from MakeCode."),
head: headBranch,
base: baseBranch,
maintainer_can_modify: true
})
return res?.html_url as string
}
export function mergeAsync(repopath: string, base: string, head: string, message?: string) {
const parsed = parseRepoId(repopath);
return ghRequestAsync({
url: `https://api.github.com/repos/${parsed.slug}/merges`,
method: "POST",
successCodes: [201, 204, 409],
data: {
base,
head,
commit_message: message
}
}).then(resp => {
if (resp.statusCode == 201 || resp.statusCode == 204)
return (resp.json as SHAObject).sha
if (resp.statusCode == 409) {
// conflict
return null
}
throw U.userError(lf("Cannot merge in github.com/{1}; code: {2}", repopath, resp.statusCode))
})
}
export function getRefAsync(repopath: string, branch: string) {
branch = branch || "master";
return ghGetJsonAsync("https://api.github.com/repos/" + repopath + "/git/refs/heads/" + branch)
.then(resolveRefAsync)
.catch(err => {
if (err.statusCode == 404) return undefined;
else Promise.reject(err);
})
}
function generateNextRefName(res: RefsResult, pref: string): string {
let n = 1
while (res.refs[pref + n])
n++
return pref + n
}
export async function getNewBranchNameAsync(repopath: string, pref = "patch-") {
const res = await listRefsExtAsync(repopath, "heads")
return generateNextRefName(res, pref);
}
export async function createNewBranchAsync(repopath: string, branchName: string, commitid: string) {
await ghPostAsync(repopath + "/git/refs", {
ref: "refs/heads/" + branchName,
sha: commitid
})
return branchName
}
export async function forkRepoAsync(repopath: string, commitid: string, pref = "pr-") {
const parsed = parseRepoId(repopath);
const res = await ghPostAsync(`${parsed.slug}/forks`, {})
const repoInfo = mkRepo(res, { fullName: parsed.fullName, fileName: parsed.fileName })
const endTm = Date.now() + 5 * 60 * 1000
let refs: RefsResult = null
while (!refs && Date.now() < endTm) {
await U.delay(1000)
try {
refs = await listRefsExtAsync(repoInfo.slug, "heads");
} catch (err) {
// not created
}
}
if (!refs)
throw new Error(lf("Timeout waiting for fork"))
const branchName = generateNextRefName(refs, pref);
await createNewBranchAsync(repoInfo.slug, branchName, commitid)
return repoInfo.fullName + "#" + branchName
}
export function listRefsAsync(repopath: string, namespace = "tags", useProxy?: boolean, noCache?: boolean): Promise<string[]> {
return listRefsExtAsync(repopath, namespace, useProxy, noCache)
.then(res => Object.keys(res.refs))
}
export function listRefsExtAsync(repopath: string, namespace = "tags", useProxy?: boolean, noCache?: boolean): Promise<RefsResult> {
const parsed = parseRepoId(repopath);
const proxy = shouldUseProxy(useProxy);
let head: string = null
const fetch = !proxy ?
ghGetJsonAsync(`https://api.github.com/repos/${parsed.slug}/git/refs/${namespace}/?per_page=100`) :
// no CDN caching here, bust browser cace
U.httpGetJsonAsync(pxt.BrowserUtils.cacheBustingUrl(`${pxt.Cloud.apiRoot}gh/${parsed.slug}/refs${noCache ? "?nocache=1" : ""}`))
.then(r => {
let res = Object.keys(r.refs)
.filter(k => U.startsWith(k, "refs/" + namespace + "/"))
.map(k => ({ ref: k, object: { sha: r.refs[k] } }))
head = r.refs["HEAD"]
return res
})
let clean = (x: string) => x.replace(/^refs\/[^\/]+\//, "")
return fetch.then<RefsResult>((resp: GHRef[]) => {
resp.sort((a, b) => semver.strcmp(clean(a.ref), clean(b.ref)))
let r: pxt.Map<string> = {}
for (let obj of resp) {
r[clean(obj.ref)] = obj.object.sha
}
return { refs: r, head }
}, err => {
if (err.statusCode == 404)
return { refs: {} } as any
else
return Promise.reject(err)
})
}
function resolveRefAsync(r: GHRef): Promise<string> {
if (r.object.type == "commit")
return Promise.resolve(r.object.sha)
else if (r.object.type == "tag")
return ghGetJsonAsync(r.object.url)
.then((r: GHRef) =>
r.object.type == "commit" ? r.object.sha :
Promise.reject(new Error("Bad type (2nd order) " + r.object.type)))
else
return Promise.reject(new Error("Bad type " + r.object.type))
}
function tagToShaAsync(repopath: string, tag: string) {
// TODO support fetching a tag
if (/^[a-f0-9]{40}$/.test(tag))
return Promise.resolve(tag)
const parsed = parseRepoId(repopath)
return ghGetJsonAsync(`https://api.github.com/repos/${parsed.slug}/git/refs/tags/${tag}`)
.then(resolveRefAsync, e =>
ghGetJsonAsync(`https://api.github.com/repos/${parsed.slug}/git/refs/heads/${tag}`)
.then(resolveRefAsync))
}
export async function pkgConfigAsync(repopath: string, tag: string, config: pxt.PackagesConfig) {
if (!tag)
tag = await db.latestVersionAsync(repopath, config)
return await db.loadConfigAsync(repopath, tag)
}
export async function downloadPackageAsync(repoWithTag: string, config: pxt.PackagesConfig): Promise<CachedPackage> {
const p = parseRepoId(repoWithTag)
if (!p) {
pxt.log('Unknown GitHub syntax');
return undefined
}
if (isRepoBanned(p, config)) {
pxt.tickEvent("github.download.banned");
pxt.log('Github repo is banned');
return undefined;
}
// always try to upgrade unbound versions
if (!p.tag) {
p.tag = await db.latestVersionAsync(p.slug, config)
}
const cached = await db.loadPackageAsync(p.fullName, p.tag)
const dv = upgradedDisablesVariants(config, repoWithTag)
if (dv) {
const cfg = Package.parseAndValidConfig(cached.files[pxt.CONFIG_NAME])
if (cfg) {
pxt.log(`auto-disable ${dv.join(",")} due to targetconfig entry for ${repoWithTag}`)
cfg.disablesVariants = dv
cached.files[pxt.CONFIG_NAME] = Package.stringifyConfig(cfg)
}
}
return cached
}
export async function downloadLatestPackageAsync(repo: ParsedRepo, useProxy?: boolean, noCache?: boolean): Promise<{ version: string, config: pxt.PackageConfig }> {
const packageConfig = await pxt.packagesConfigAsync()
const tag = await pxt.github.latestVersionAsync(repo.slug, packageConfig, useProxy, noCache)
// download package into cache
const repoWithTag = `${repo.fullName}#${tag}`;
await pxt.github.downloadPackageAsync(repoWithTag, packageConfig)
// return config
const config = await pkgConfigAsync(repo.fullName, tag, packageConfig)
const version = `github:${repoWithTag}`
return { version, config };
}
export async function cacheProjectDependenciesAsync(cfg: pxt.PackageConfig): Promise<void> {
const ghExtensions = Object.keys(cfg.dependencies)
?.filter(dep => isGithubId(cfg.dependencies[dep]));
if (ghExtensions.length) {
const pkgConfig = await pxt.packagesConfigAsync();
// Make sure external packages load before installing header.
await Promise.all(
ghExtensions.map(
async ext => {
const extSrc = cfg.dependencies[ext];
const ghPkg = await downloadPackageAsync(extSrc, pkgConfig);
if (!ghPkg) {
throw new Error(lf("Cannot load extension {0} from {1}", ext, extSrc));
}
}
)
);
}
}
export interface User {
login: string; // "Microsoft",
id: number; // 6154722,
avatar_url: string; // "https://avatars.githubusercontent.com/u/6154722?v=3",
gravatar_id: string; // "",
html_url: string; // "https://github.com/microsoft",
type: string; // "Organization"
name: string;
company: string;
}
interface Repo {
id: number;
name: string; // "pxt-microbit-cppsample",
full_name: string; // "Microsoft/pxt-microbit-cppsample",
owner: User;
private: boolean;
html_url: string; // "https://github.com/microsoft/pxt-microbit-cppsample",
description: string; // "Sample C++ extension for PXT/microbit",
fork: boolean;
created_at: string; // "2016-05-05T11:18:12Z",
updated_at: string; // "2016-06-20T02:25:03Z",
pushed_at: string; // "2016-05-05T11:59:42Z",
homepage: string; // null,
size: number; // 4
stargazers_count: number;
watchers_count: number;
forks_count: number;
open_issues_count: number;
forks: number;
open_issues: number;
watchers: number;
default_branch: string; // "main", "master",
score: number; // 6.7371006
// non-github, added to track search request
tag?: string;
}
interface SearchResults {
total_count: number;
incomplete_results: boolean;
items: Repo[];
}
export interface ParsedRepo {
owner?: string;
project?: string;
// owner/project (aka slug)
slug: string;
fullName: string;
tag?: string;
fileName?: string;
}
export enum GitRepoStatus {
Unknown,
Approved,
Banned
}
export interface GitRepo extends ParsedRepo {
name: string;
description: string;
defaultBranch: string;
status?: GitRepoStatus;
updatedAt?: number;
private?: boolean;
fork?: boolean;
}
export function isDefaultBranch(branch: string, repo?: GitRepo) {
if (repo && repo.defaultBranch)
return branch === repo.defaultBranch;
return /^(main|master)$/.test(branch);
}
export function listUserReposAsync(): Promise<GitRepo[]> {
const q = `{
viewer {
repositories(first: 100, affiliations: [OWNER, COLLABORATOR], orderBy: {field: PUSHED_AT, direction: DESC}) {
nodes {
name
description
full_name: nameWithOwner
private: isPrivate
fork: isFork
updated_at: updatedAt
owner {
login
}
defaultBranchRef {
name
}
pxtjson: object(expression: "HEAD:pxt.json") {
... on Blob {
text
}
}
readme: object(expression: "HEAD:README.md") {
... on Blob {
text
}
}
}
}
}
}`
return ghGraphQLQueryAsync(q)
.then(res => (<any[]>res.data.viewer.repositories.nodes)
.filter((node: any) => node.pxtjson) // needs a pxt.json file
.filter((node: any) => {
node.default_branch = node.defaultBranchRef.name;
const pxtJson = pxt.Package.parseAndValidConfig(node.pxtjson && node.pxtjson.text);
const readme = node.readme && node.readme.text;
// needs to have a valid pxt.json file
if (!pxtJson) return false;
// new style of supported annontation
if (pxtJson.supportedTargets)
return pxtJson.supportedTargets.indexOf(pxt.appTarget.id) > -1;
// legacy readme.md annotations
return readme && readme.indexOf("PXT/" + pxt.appTarget.id) > -1;
})
.map((node: any) => mkRepo(node, { fullName: node.full_name }))
);
}
export function createRepoAsync(name: string, description: string, priv?: boolean) {
return ghPostAsync("https://api.github.com/user/repos", {
name,
description,
private: !!priv,
has_issues: true, // default
has_projects: false,
has_wiki: false,
allow_rebase_merge: false,
allow_merge_commit: true,
delete_branch_on_merge: false // keep branches for naming purposes
}).then(v => mkRepo(v))
}
export async function enablePagesAsync(repo: string) {
// https://developer.github.com/v3/repos/pages/#enable-a-pages-site
// try read status
const parsed = parseRepoId(repo);
let url: string = undefined;
try {
const status = await ghGetJsonAsync(`https://api.github.com/repos/${parsed.slug}/pages`) // try to get the pages
if (status)
url = status.html_url;
} catch (e) { }
// status failed, try enabling pages
if (!url) {
// enable pages
try {
const r = await ghPostAsync(`https://api.github.com/repos/${parsed.slug}/pages`, {
source: {
branch: "master",
path: "/"
}
}, {
"Accept": "application/vnd.github.switcheroo-preview+json"
});
url = r.html_url;
}
catch (e) {// this is still an experimental api subject to changes
pxt.tickEvent("github.pages.error");
pxt.reportException(e);
}
}
// we have a URL, update project
if (url) {
// check if the repo already has a web site
const rep = await ghGetJsonAsync(`https://api.github.com/repos/${repo}`);
if (rep && !rep.homepage) {
try {
await ghPostAsync(`https://api.github.com/repos/${repo}`, { "homepage": url }, undefined, "PATCH");
} catch (e) {
// just ignore if fail to update the homepage
pxt.tickEvent("github.homepage.error");
}
}
}
}
export function repoIconUrl(repo: GitRepo): string {
if (repo.status != GitRepoStatus.Approved) return undefined;
return mkRepoIconUrl(repo)
}
export function mkRepoIconUrl(repo: ParsedRepo): string {
return Cloud.cdnApiUrl(`gh/${repo.fullName}/icon`)
}
function mkRepo(r: Repo, options?: {
config?: pxt.PackagesConfig,
fullName?: string,
fileName?: string,
tag?: string
}): GitRepo {
if (!r) return undefined;
const rr: GitRepo = {
owner: r.owner.login.toLowerCase(),
slug: r.full_name.toLowerCase(),
fullName: (options?.fullName || r.full_name).toLowerCase(),
fileName: options?.fileName?.toLocaleLowerCase(),
name: r.name,
description: r.description,
defaultBranch: r.default_branch,
tag: options?.tag,
updatedAt: Math.round(new Date(r.updated_at).getTime() / 1000),
fork: r.fork,
private: r.private,
}
rr.status = repoStatus(rr, options?.config);
return rr;
}
export function repoStatus(rr: ParsedRepo, config: pxt.PackagesConfig): GitRepoStatus {
if (!rr) return GitRepoStatus.Unknown;
return isRepoBanned(rr, config) ? GitRepoStatus.Banned
: isRepoApproved(rr, config) ? GitRepoStatus.Approved
: GitRepoStatus.Unknown;
}
function isOrgBanned(repo: ParsedRepo, config: pxt.PackagesConfig): boolean {