-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
1484 lines (1295 loc) · 38.5 KB
/
index.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
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
/**
* Server file
*/
// Import statements
const express = require('express');
const app = express();
const fs = require('fs')
require("dotenv").config();
// Server port number
const PORT = process.env.PORT;
// Example phenotypes taken from Phenoflow
const STATIC_PHENOTYPES = require('./test/phenotypes.json');
// Project variables
const OWNER = process.env.OWNER;
const AUTH_TOKEN = process.env.AUTH_TOKEN;
// README variables
const README_COMMIT_MESSAGE = 'Initial README.md';
const README_PATH = 'README.md';
const README_TEMPLATE_PATH = './README-Template.md';
// LICENSE variables
const LICENSE_COMMIT_MESSAGE = 'Initial LICENSE.md';
const LICENSE_PATH = 'LICENSE.md';
const LICENSE_FILE_PATH = './LICENSE.md';
// User variables
const USER_NAME = process.env.USER_NAME;
const USER_EMAIL = process.env.USER_EMAIL;
// Miscellaneous variables
const CWL_EXTENSION = `.cwl`;
const ERROR_MESSAGE = 'Sorry an error occurred';
// Necessary to parse JSON request bodies
app.use(express.json());
/**
* Octokit.js
* https://github.com/octokit/core.js#readme
*
* Taken from GitHub REST API Docs
* https://docs.github.com/en/rest/guides/getting-started-with-the-rest-api?apiVersion=2022-11-28
*/
const { Octokit } = require("octokit");
const { error } = require('console');
const octokit = new Octokit({
auth: AUTH_TOKEN
});
/**
* Get Hex string representation of string
* of different encoding
* @param {String} string String to be encoded
* @param {String} encoding 'hex', 'utf-8' or 'base64'
* @returns Hex string with 0s included
*/
function hexOf(string, encoding) {
// Encoding is utf-8 by default
const stringBuffer = Buffer.from(string, encoding);
let stringArray = [];
for(const value of stringBuffer.values()) {
let hexValue = value.toString(16);
// Puts inserts zero on values less than 0x10
if (hexValue.length == 1) {
hexValue = `0${hexValue}`
}
stringArray.push(hexValue);
}
return stringArray.join('');
}
/**
* Developer routes
*/
// Get GitHub API invokation quota information
app.get("/rate", async(request, response) => {
try {
const rate = await octokit.request('GET /rate_limit', {
headers: {
'X-GitHub-Api-Version': '2022-11-28'
}
});
return response.status(200).send(rate.data);
} catch (error) {
console.log(error);
return response.status(500).send(ERROR_MESSAGE);
}
});
// Check if server is running
app.get("/", async(request, response) => {
try {
return response.status(200).send('Server is running');
} catch (error) {
console.log(error);
return response.status(500).send(ERROR_MESSAGE);
}
});
/**
* Read routes
*/
/**
* Get the file or directory
* @param {String} repo Repository name
* @param {String} path File or Directory path [within repository]
* @returns File or Directory
*/
async function getFileOrDirectory(repo, path) {
try {
const file = await octokit.request('GET /repos/{owner}/{repo}/contents/{path}', {
owner: OWNER,
repo: repo,
path: path,
headers: {
'X-GitHub-Api-Version': '2022-11-28'
}
})
return file;
} catch (error) {
console.log(error);
throw error;
}
}
/**
* Get a phenotype in phenoflow
* @param {*} name Repository name
* @returns Phenotype
*/
async function getPhenotype(name) {
try {
const repo = await octokit.request('GET /repos/{owner}/{repo}', {
owner: OWNER,
repo: name,
headers: {
'X-GitHub-Api-Version': '2022-11-28'
}
}, { accept: 'application/vnd.github+json' });
return repo;
} catch (error) {
console.log(error);
throw error;
}
}
/**
* Get all phenotypes in GitHub
* @returns Array of phenotypes
*/
async function getAllPhenotypes() {
try {
const repos = await octokit.request('GET /orgs/{org}/repos', {
org: OWNER,
headers: {
'X-GitHub-Api-Version': '2022-11-28'
}
});
return repos;
} catch (error) {
console.log(error);
throw error;
}
}
/**
* Get path of step of phenotype
* @param {String} repo Repository name
* @param {String} path [Phenotype name].cwl file path
* @param {Number} number Step number
* @returns Step path string
*/
async function getStepPath(repo, path, number) {
try {
// The .cwl instantiation file of a phenotype
const file = await getFileOrDirectory(repo, path);
let contentBuffer = Buffer.from(file.data.content, 'base64');
let content = contentBuffer.toString('utf-8');
const contentHex = hexOf(content, 'utf-8');
/**
* Finds startIndex of the step path
* from within contentHex
*/
let searchString = `'${number}':\r\n run: `;
let searchHex = hexOf(searchString, 'utf-8');
const startIndex = contentHex.indexOf(searchHex) + (searchHex.length);
/**
* Finds endIndex of the step path
* from within contentHex
*/
searchString = CWL_EXTENSION;
searchHex = hexOf(searchString, 'utf-8');
const endIndex = contentHex.substring(startIndex).indexOf(searchHex) + startIndex + (searchHex.length);
/**
* Uses startIndex and endIndex to slice the step path
* out of contextHex
*/
const stepHex = contentHex.substring(startIndex, endIndex);
// Final buffer and string
const stepBuffer = Buffer.from(stepHex, 'hex');
const stepPath = stepBuffer.toString('utf-8');
return stepPath;
} catch (error) {
console.log(error);
throw error;
}
}
/**
* Get step of phenotype
* @param {String} repo Repository name
* @param {String} path [Phenotype name].cwl file path
* @param {Number} number Step number
* @returns Step
*/
async function getStep(repo, path, number) {
try {
const stepPath = await getStepPath(repo, path, number);
const body = await getFileOrDirectory(repo, stepPath);
return body;
} catch (error) {
console.log(error);
throw error;
}
}
/**
* Get description of step of phenotype
* @param {String} repo Repository name
* @param {String} path Step file path
* @param {Nubmer} number Step number
* @returns Step description string
*/
async function getStepDescription(repo, path, number) {
try {
// The .cwl step file of a phenotype
const step = await getStep(repo, path, number);
const contentBuffer = Buffer.from(step.data.content, 'base64');
const content = contentBuffer.toString('utf-8');
const contentHex = hexOf(content, 'utf-8');
/**
* Finds startIndex of the step description
* from within contentHex
*/
let searchString = `doc: `;
let searchHex = hexOf(searchString, 'utf-8');
const startIndex = contentHex.indexOf(searchHex) + (searchHex.length);
/**
* Finds endIndex of the step description
* from within contentHex
*/
searchString = '\nid: ';
searchHex = hexOf(searchString, 'utf-8');
const endIndex = contentHex.substring(startIndex).indexOf(searchHex) + startIndex;
/**
* Uses startIndex and endIndex to slice the step path
* out of contentHex
*/
const descriptionHex = contentHex.substring(startIndex, endIndex);
// Final buffer and string
const descriptionBuffer = Buffer.from(descriptionHex, 'hex');
const description = descriptionBuffer.toString('utf-8');
return description;
} catch (error) {
console.log(error);
throw error;
}
}
/**
* Get JavaScript and/ or Python implementation of step of phenotype
* @param {String} repo Repository name
* @param {String} path [Phenotype name].cwl file path
* @param {Number} number Step number
* @returns Array of Step implementation files
*/
async function getStepImplmentations(repo, path, number) {
try {
const phenotype = await octokit.request('GET /repos/{owner}/{repo}/contents', {
owner: OWNER,
repo: repo,
headers: {
'X-GitHub-Api-Version': '2022-11-28'
}
}, { accept: 'application/vnd.github+json' });
const contents = await getAllContents(phenotype.data, [], repo);
/**
* Searches for all JS and Python implementation
* step files in the phenotype repository
*/
let pathDict = {};
let extensionDict = {'.js': false, '.py': false};
contents.forEach(file => {
for (const extension of Object.keys(extensionDict)) {
/**
* If extension (.js or .py) is in the file name
* add file path to dictionary of files
* and mark as present
*/
if (file.name.indexOf(extension) != -1) {
extensionDict[extension] = true;
pathDict[file.name] = file.path;
}}
});
// List of implemenation files
let implementations = [];
let stepPath = await getStepPath(repo, path, number);
for (const [extension, value] of Object.entries(extensionDict)) {
/**
* If a step implmentation of type extension exists
* add implementation file to implementations list
*/
if (value) {
// Ammeds discrepency in name of first step of phenotypes
// created with the default connector
if (stepPath == 'read-potential-cases-disc.cwl') {
stepPath = 'read-potential-cases.cwl';
}
/**
* Formulates implmentation file path
* by replacing .cwl extension with extension
*/
const implementationPath = stepPath.replace(CWL_EXTENSION, extension);
const body = await getFileOrDirectory(repo, pathDict[implementationPath]);
implementations.push(body.data);
}
}
return implementations;
} catch (error) {
console.log(error);
throw error;
}
}
/**
* Recursive function to get all files and folders within repo
* @param {Array} data Current File and Directories to be searched
* @param {Array} contents Files and Directories already searched
* @param {String} repo Repository name
* @returns Array of Files and Directories
*/
async function getAllContents(data, contents, repo) {
let directories = []
for (const datum of data) {
/**
* If path is of a folder (not a file)
* adds folder to directories array.
* (files contain a '.', folders do not)
*/
if (datum.name.indexOf('.') == -1) {
directories.push(datum);
}
}
if (contents.length == 0) { contents = data }
/**
* Base case
*
* If no folders were found,
* return all data
*/
if (directories.length == 0) {
return contents.concat(data);
}
/**
* Recursive case
*
* If one or more folders are found,
* recall function
*/
else {
for (const directory of directories) {
const folders = await getFileOrDirectory(repo, directory.path);
return await getAllContents(folders.data, contents, repo);
}
}
}
// Get all phenotypes
// Get all phenotypes created by an author
// Get all phenotypes with a particular substring in the name
app.get("/phenotypes", async(request, response) => {
const author = request.query.author;
const name = request.query.name;
try {
const repos = await getAllPhenotypes();
let phenotypes = repos.data;
let output = [];
/**
* If author and name are queried,
* finds phenotypes matching a substring of name
* and created by author
*/
if (typeof(author) != 'undefined' && typeof(name) != 'undefined') {
/**
* Searches for all phenotypes that have name
* as a substring of their name
*/
for(const phenotype of phenotypes){
if(phenotype.name.includes(name)) {
// GETS the commit history of the repository
const commits = await octokit.request('GET /repos/{owner}/{repo}/commits', {
owner: OWNER,
repo: phenotype.name,
headers: {
'X-GitHub-Api-Version': '2022-11-28'
}
});
/**
* Searches for the author of the
* initial/ initialise README.md commit
*/
let isAuthorFound = false;
for(const commit of commits.data) {
/** If the author matches, pushes
the phenotype to output */
if (commit.commit.message == README_COMMIT_MESSAGE &&
commit.commit.author.name == author){
isAuthorFound = true;
output.push(phenotype);
}
}
if (!isAuthorFound) {
throw error;
}
}
}
}
/**
* If only author is queried,
* finds phenotypes created by author
*/
else if (typeof(author) != 'undefined') {
// Searches through all phenotypes
for(const phenotype of phenotypes){
// GETS the commit history of the repository
const commits = await octokit.request('GET /repos/{owner}/{repo}/commits', {
owner: OWNER,
repo: phenotype.name,
headers: {
'X-GitHub-Api-Version': '2022-11-28'
}
});
/**
* Searches for the author of the
* initial/ initialise README.md commit
*/
let isAuthorFound = false;
for(const commit of commits.data) {
/**
* If the author matches, pushes
* the phenotype to output
*/
if (commit.commit.message == README_COMMIT_MESSAGE &&
commit.commit.author.name == author){
isAuthorFound = true;
output.push(phenotype);
}
}
if (!isAuthorFound) {
throw error;
}
}
}
/**
* If only name is queried,
* finds phenotypes matching a substring of name
*/
else if (typeof(name) != 'undefined') {
let isPhenotypeFound = false;
for(const phenotype of phenotypes){
/**
* If name is a substring, pushes
* the phenotype to output
*/
if(phenotype.name.includes(name)) {
isPhenotypeFound = true;
output.push(phenotype);
}
}
if (!isPhenotypeFound) {
throw error;
}
}
/**
* If no author or name was specified,
* finds all phenotypes
*/
else {
output = phenotypes;
}
// Returns curated array of phenotypes
return response.status(200).send(output);
} catch (error) {
console.log(error);
return response.status(500).send(ERROR_MESSAGE);
}
});
// Get a single phenotype, by name
app.get("/phenotype/:name", async(request, response) => {
const name = request.params.name;
try {
const repo = await getPhenotype(name);
return response.status(200).send(repo.data);
} catch (error) {
console.log(error);
return response.status(500).send(ERROR_MESSAGE);
}
});
// Get a single phenotype contents
app.get("/phenotype/:name/contents", async(request, response) => {
const name = request.params.name;
try {
const repo = await octokit.request('GET /repos/{owner}/{repo}/contents', {
owner: OWNER,
repo: name,
headers: {
'X-GitHub-Api-Version': '2022-11-28'
}
}, { accept: 'application/vnd.github+json' });
const contents = await getAllContents(repo.data, [], name);
return response.status(200).send(contents);
} catch (error) {
console.log(error);
return response.status(500).send(ERROR_MESSAGE);
}
});
// Get description of a single phenotype, by name
app.get("/phenotype/:name/description", async(request, response) => {
const name = request.params.name;
try {
const readme = await octokit.request('GET /repos/{owner}/{repo}/readme', {
owner: OWNER,
repo: name,
headers: {
'X-GitHub-Api-Version': '2022-11-28'
}
}, { accept: 'application/vnd.github.raw' });
let readmeHex = hexOf(readme.data.content, 'base64');
/**
* Finds startIndex of the phenotype description
* within readmeHex
*/
let searchString = '- ';
let searchHex = hexOf(searchString);
const startIndex = readmeHex.indexOf(searchHex) + (searchString.length * 2);
/**
* Finds endIndex of the phenotype description
* within readmeHex
*/
searchString = '##';
searchHex = hexOf(searchString);
const endIndex = readmeHex.indexOf(searchHex) - (searchString.length * 2);
/**
* Uses startIndex and endIndex to slice the description
* out of readmeHex
*/
const descriptionHex = readmeHex.slice(startIndex, endIndex);
// Final buffer
const outputBuffer = Buffer.from(descriptionHex, 'hex');
return response.status(200).send(outputBuffer.toString('utf-8'));
} catch (error) {
console.log(error);
return response.status(500).send(ERROR_MESSAGE);
}
});
// Get a single step of phenotype, by phenotype and step number
app.get("/step/:step", async(request, response) => {
const repo = request.body.repo;
const path = `${repo}${CWL_EXTENSION}`;
try {
const step = await getStep(repo, path, request.params.step);
return response.status(200).send(step.data);
} catch (error) {
console.log(error);
return response.status(500).send(ERROR_MESSAGE);
}
});
// Get a single step of phenotype contents, by phenotype and step number
app.get("/step/:step/contents", async(request, response) => {
const repo = request.body.repo;
const path = `${request.body.repo}${CWL_EXTENSION}`;
try {
const step = await getStep(repo, path, request.params.step);
const contentBuffer = Buffer.from(step.data.content, 'base64');
const content = contentBuffer.toString('utf-8');
return response.status(200).send(content);
} catch (error) {
console.log(error);
return response.status(500).send(ERROR_MESSAGE);
}
});
// Get description of a single step of phenotype, by phenotype and step number
app.get("/step/:step/description", async(request, response) => {
const repo = request.body.repo;
const path = `${request.body.repo}${CWL_EXTENSION}`;
const step = request.params.step;
try {
const description = await getStepDescription(repo, path, step);
return response.status(200).send(description);
} catch (error) {
console.log(error);
return response.status(500).send(ERROR_MESSAGE);
}
});
// Get a single step of phenotype contents, by phenotype and step number
app.get("/step/:step/implementation", async(request, response) => {
const repo = request.body.repo;
const path = `${request.body.repo}${CWL_EXTENSION}`;
const step = request.params.step;
try {
const implementations = await getStepImplmentations(repo, path, step);
return response.status(200).send(implementations);
} catch (error) {
console.log(error);
return response.status(500).send(ERROR_MESSAGE);
}
});
/**
* Method signature is here for completeness
*
* Similar functionality is implmented in
* 'GET' /step/:step/description
*/
app.get("/step/:step/input/description", async(request, response) => {
pass;
});
/**
* Method signature is here for completeness
*
* Similar functionality is implmented in
* 'GET' /step/:step/description
*/
app.get("/step/:step/output/description", async(request, response) => {
pass;
});
// Get single file or directory, by path
app.get("/file", async(request, response) => {
const repo = request.body.repo;
const path = request.body.path;
try {
const file = await getFileOrDirectory(repo, path);
return response.status(200).send(file.data);
} catch (error) {
console.log(error);
return response.status(500).send(ERROR_MESSAGE);
}
});
// Get contents of a single file or directory, by path
app.get("/file/contents", async(request, response) => {
const repo = request.body.repo;
const path = request.body.path;
try {
const file = await getFileOrDirectory(repo, path);
let output = file;
// If path is a file, get string content of the file
if (typeof(file.data.content) != 'undefined') {
const contentBuffer = Buffer.from(file.data.content, 'base64');
const content = contentBuffer.toString('utf-8');
output = content
}
return response.status(200).send(output);
} catch (error) {
console.log(error);
return response.status(500).send(ERROR_MESSAGE);
}
});
/**
* Create routes
*/
/**
* Creates standard LICENSE.md file for a phenotype,
* from ./LICENSE.md
* @param {String} name Repository name
* @returns 1 if successful, else error
*/
async function createLICENSE(name) {
const repo = name;
// Parses template LICENSE.md file
const license = fs.readFileSync(LICENSE_FILE_PATH).toString();
const licenseHex = hexOf(license, 'utf-8');
// Final buffer
const outputBuffer = Buffer.from(licenseHex, 'hex');
try {
await octokit.request('PUT /repos/{owner}/{repo}/contents/{path}', {
owner: OWNER,
repo: repo,
path: LICENSE_PATH,
message: LICENSE_COMMIT_MESSAGE,
committer: {
name: USER_NAME,
email: USER_EMAIL
},
// GitHub REST API requires content in base-64
content: outputBuffer.toString('base64'),
headers: {
'X-GitHub-Api-Version': '2022-11-28'
}
});
console.log(`Created ${repo}/${LICENSE_PATH} file`);
return 1;
} catch (error) {
console.log(error);
throw error;
}
};
/**
* Creates standard README.md file for a phenotype,
* from ./README-Template.md
* @param {String} name Repository name
* @param {String} about <Phenotype ID> - <Phenotype description>
* @returns 1 if successful, else error
*/
async function initialiseREADME(name, about) {
const repo = name;
// Parses template README.md file
const template = fs.readFileSync(README_TEMPLATE_PATH).toString();
let templateHex = hexOf(template, 'utf-8');
// Dummy name variable
let searchString = hexOf('<Name>', 'utf-8');
// Searches for all apperances of searchString
const nameHex = hexOf(repo, 'utf-8');
// Replaces all occurances of searchString with true name
while(templateHex.indexOf(searchString) != -1) {
templateHex = templateHex.replace(searchString, nameHex);
}
// Dummy description variable
searchString = hexOf('<ID> - <Description>', 'utf-8');
// Searches for apperance of searchString
const descriptionHex = hexOf(about, 'utf-8');
// Replaces all occurance of searchString with true description
templateHex = templateHex.replace(searchString, descriptionHex);
// Final buffer
const outputBuffer = Buffer.from(templateHex, 'hex');
try {
await octokit.request('PUT /repos/{owner}/{repo}/contents/{path}', {
owner: OWNER,
repo: repo,
path: README_PATH,
message: README_COMMIT_MESSAGE,
committer: {
name: USER_NAME,
email: USER_EMAIL
},
// GitHub REST API requires content in base-64
content: outputBuffer.toString('base64'),
headers: {
'X-GitHub-Api-Version': '2022-11-28'
}
});
console.log(`Initialised ${repo}/${README_PATH} file`);
return 1;
} catch (error) {
console.log(error);
throw error;
}
};
/**
* Creates a phenotype repo
* @param {String} name Repository name
* @returns 1 if successful, else error
*/
async function createPhenotype(name) {
try {
await octokit.request('POST /orgs/{org}/repos', {
org: OWNER,
name: name,
description: `${name} phenotype. Created by ${USER_NAME}.`,
'private': false,
has_issues: true,
has_projects: true,
has_wiki: true,
headers: {
'X-GitHub-Api-Version': '2022-11-28'
}
});
console.log(`Created ${name} phenotype`);
return 1;
} catch (error) {
console.log(error);
throw error;
}
};
/**
* Creates a repo file
* @param {String} repo Repository name
* @param {String} path File path [within repository]
* @param {String} content File content [Base64]
* @returns 1 if successful, else error
*/
async function createFile(repo, path, content) {
try {
await octokit.request('PUT /repos/{owner}/{repo}/contents/{path}', {
owner: OWNER,
repo: repo,
path: path,
message: `Created ${path}`,
committer: {
name: USER_NAME,
email: USER_EMAIL
},
content: content,
headers: {
'X-GitHub-Api-Version': '2022-11-28'
}
});
console.log(`Created ${repo}/${path} file`);
return 1;
} catch (error) {
console.log(error);
throw error;
}
};
/**
* Implemented for development and testing purposes
*
* Create empty phenotypes from ./phenotypes-reduced.json
*/
app.post("/initialise", async (request, response) => {
try {
const remotePhenotypes = await octokit.request('GET /orgs/{org}/repos', {
org: OWNER,
headers: {
'X-GitHub-Api-Version': '2022-11-28'
}
});
// List of existing phenotypes in GitHub
let remoteNames = [];
// Populate remoteNames
remotePhenotypes.data.forEach(phenotype => {
remoteNames.push(phenotype.name.toLowerCase())
});
for(const phenotype of STATIC_PHENOTYPES) {
const name = phenotype.name.toLowerCase()
/**
* If static phenotype does not exist in GitHub,
* create phenotype, intialise README.md and
* create LICENSE.md
*/
if (!remoteNames.includes(name)) {
await createPhenotype(phenotype.name);
await initialiseREADME(phenotype.name, phenotype.about);
await createLICENSE(phenotype.name);
// Populate phenotype repository with its files
const files = phenotype.files;
for(const file of files){
await createFile(phenotype.name, file.path, file.content);
}
}
}
response.status(200).send();
} catch (error) {
console.log(error);
response.status(500).send(ERROR_MESSAGE);
}
});
// Create empty phenotype with name
app.post("/phenotype", async(request, response) => {
const name = request.body.name;
const about = request.body.about;
const files = request.body.files;
try {
await createPhenotype(name);
await initialiseREADME(name, about);
await createLICENSE(name);
/**
* If files were also sent,
* populate phenotype repository with its files
*/
if(typeof(files) != 'undefined' && files.length != 0) {
for(const file of files){
await createFile(name, file.path, file.content);
}
}
return response.status(200).send();
} catch (error) {
console.log(error);
return response.status(500).send(ERROR_MESSAGE);
}
});
// Create file within a phenotype by path
app.post("/file", async(request, response) => {
const repo = request.body.repo;
const path = request.body.path;
const content = request.body.content;
try {