forked from jaammees/lvllvl
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithubClient.js
More file actions
1224 lines (968 loc) · 32.2 KB
/
githubClient.js
File metadata and controls
1224 lines (968 loc) · 32.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
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
// github library: https://github.com/github-tools/github
var GitHubClient = function() {
var token = false;
var githubUser = null;
var githubProfile = null;
var gh = null;
var repo = null;
var filesToCommit = [];
var currentBranch = {};
var newCommit = {};
var repositoryOwner = '';
var repositoryName = '';
var repositoryFolder = '';//'data';
var repositoryFolderSHA = '';
var treeFiles = null;
var onLogin = false;
var onLogout = false;
var provider = null;
var scopes = [];
// this.repoUsername = 'jaammees';
// this.repoName = 'test-repo';
this.setRepositoryFolder = function(folder) {
repositoryFolder = folder;
},
this.isLoggedIn = function() {
return token !== false;
},
this.on = function(eventName, f) {
switch(eventName) {
case 'login':
onLogin = f;
break;
case 'logout':
onLogout = f;
break;
}
}
//https://level-3-editor.firebaseapp.com/__/auth/handler?code=60a4d9520ddf67c7d0c0&state=AMbdmDkfURiE2j_iPjz1kHjnT8ajrVnMVjDKXqURKXnjjshMuSTpb-wdjaEP9U1p1mqP_tnR9hkZRV-D6yPAY_yaJaHURljsJ92TS8VHzJ-a9A3Bwux1CW_ldRg2tbl3Y5ekw40T6-v2_9qYBrDFLlNEBmo8MwqygshD1rjyeGyUzQUTx3CIuFd8jgh6KVQ69XPHlro09SI263KTUIBUdSaey05HYew4wf4VXfT-5JwVgJ_-NhSOl0ZAGJqOp7SD1AOZE5LyWRUXyxJQElg1QAD8bI8wkJfrv8uZN2R9jXZw3Q7OBud6b-hpjRsXJeLqb-7OhMRYoeQbbiI
this.loginWithRedirect = function() {
provider = new firebase.auth.GithubAuthProvider();
provider.addScope('repo');
provider.addScope('gist');
firebase.auth().signInWithRedirect(provider);
},
this.getScopes = function() {
return scopes;
}
// if the current user doesn't have the scope, then request it
this.requestScope = function(scope, callback) {
if( (token === false || !this.hasScope(scope)) ) {
// user either is not logged in or doesn't have the scope
var requestScopes = [];
for(var i = 0; i < scopes.length; i++) {
requestScopes.push(scopes[i]);
}
requestScopes.push(scope);
this.login(callback, requestScopes);
} else {
callback();
}
}
this.hasScope = function(scope) {
for(var i = 0; i < scopes.length; i++) {
if(scopes[i] == scope) {
return true;
}
}
return false;
}
this.login = function(callback, scopesRequired) {
var _this = this;
// console.log('github login');
// console.log('scopes required: ' + scopesRequired);
provider = new firebase.auth.GithubAuthProvider();
if(typeof scopesRequired != 'undefined') {
for(var i = 0; i < scopesRequired.length; i++) {
provider.addScope(scopesRequired[i]);
}
} else {
provider.addScope('repo');
provider.addScope('gist');
}
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives you a GitHub Access Token. You can use it to access the GitHub API.
token = result.credential.accessToken;
var user = firebase.auth().currentUser;
firestoreDb.collection('users').doc(user.uid).set({ token: token }, { merge: true });
setToken(token, callback);
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
});
}
this.logout = function() {
g_app.fileManager.clearRepositoriesCache(function() {
firebase.auth().signOut();
token = false;
if(onLogout) {
onLogout();
}
});
}
function setToken(t, callback) {
token = t;
gh = new GitHub({ token: token });
githubUser = gh.getUser();
githubUser.getProfile().then(function(result) {
scopes = result.headers['x-oauth-scopes'].split(',');
for(var i = 0; i < scopes.length; i++) {
scopes[i] = scopes[i].trim();
}
githubProfile = result.data;
if(onLogin !== false) {
onLogin();
}
if(typeof callback != 'undefined') {
callback();
}
});
}
this.getLoginName = function() {
if(!token || !githubProfile) {
return '';
}
return githubProfile.login;
}
this.setUser = function(user, callback) {
if(user) {
var userDocRef = firestoreDb.collection("users").doc(user.uid);
userDocRef.get().then(function(userDoc) {
if(userDoc.exists) {
var data = userDoc.data();
setToken(data.token);
if(typeof callback != 'undefined') {
callback();
}
} else {
console.log("couldn't get user");
}
}).catch(function(error) {
console.log("Error getting document:", error);
console.log(error);
});
} else {
token = false;
githubUser = null;
githubProfile = null;
if(typeof callback != 'undefined') {
callback();
}
}
}
this.getRepoDetails = function(args, callback) {
var repo = gh.getRepo(githubProfile.login, args.repository);
repo.getDetails().then(function(response) {
callback(response);
}).catch((e) => {
callback({
status: 404,
statusText: "Repository Not Found"
});
});
}
this.getBranches = function(callback) {
if (!repo) {
throw 'Repository is not initialized';
}
repo.listBranches().then((branches) => {
callback(branches);
});
}
this.getCurrentBranchName = function(callback) {
this.getBranches(function(branches) {
var branchName = false;
var branchData = branches.data;
if(branchData && branchData.length > 0) {
branchName = branchData[0].name;
for(var i = 0; i < branchData.length; i++) {
if(branchData[i].name == 'master') {
branchName = 'master';
}
}
callback(branchName);
return;
}
callback('main');
});
}
this.createGist = function(args, callback) {
var gist = gh.getGist(); // not a gist yet
gist.create({
public: false,
description: 'Test',
files: args.files
}).then(function({data}) {
// Promises!
let createdGist = data;
return gist.read();
}).then(function(response) {
let retrievedGist = response.data;
callback(response);
// do interesting things
});
}
this.processTruncated = function(response, truncated, callback) {
if(truncated.length == 0) {
callback(response);
return;
}
var _this = this;
var key = truncated.pop();
var url = response.data.files[key].raw_url;
$.get(url, {}, function(data) {
response.data.files[key].content = data;
_this.processTruncated(response, truncated, callback);
});
},
this.getGist = function(args, callback) {
var id = args.id;
if(gh == null) {
gh = new GitHub({token: token });
}
var gist = gh.getGist(id); // not a gist yet
this.gistTruncated = [];
var _this = this;
gist.read().then(function(response) {
// need to check if truncated..
for(var key in response.data.files) {
if(response.data.files[key].truncated) {
_this.gistTruncated.push(key);
}
}
if(_this.gistTruncated.length > 0) {
_this.processTruncated(response, _this.gistTruncated, callback);
} else {
callback(response);
}
});
}
this.createRepo = function(args, callback) {
gh = new GitHub({ token: token });
var user = gh.getUser();
var repositoryType = args.repositoryType;
if(typeof repositoryType == 'undefined') {
repositoryType = 'private';
}
var options = {
"name": args.repository,
"private": repositoryType != 'public',
"auto_init": true
}
user.createRepo(options)
.then(function(response) {
if(callback) {
callback(response);
}
}).catch((e) => {
// uh oh, does the repo already exist?
var repo = gh.getRepo(githubProfile.login, args.repository);
repo.getDetails().then(function(response) {
if(response.status == 200) {
callback({
status: 500,
statusText: "Repository Already Exists"
});
}
}).catch(function(e) {
console.log('another exception...');
console.log(e);
});
});
}
// check if login is required, check if logged in, then called doLoad
this.load = function(args, callback) {
var _this = this;
var requireLogin = true;
if(typeof args.requireLogin != 'undefined') {
requireLogin = args.requireLogin;
}
if( (token === false || !this.hasScope('repo')) && requireLogin) {
this.login(function() {
_this.doLoad(args, callback);
}, ['repo']);
} else {
_this.doLoad(args, callback);
}
}
// first check if valid user logged in..
// then call do pull
this.pull = function(args, callback) {
var _this = this;
var requireLogin = true;
if(typeof args.requireLogin != 'undefined') {
requireLogin = args.requireLogin;
}
// if( (token === false || !this.hasScope('repo')) && requireLogin) {
if( requireLogin && token === false ) { //} (token === false || !this.hasScope('repo')) && requireLogin) {
// not logged in
this.login(function() {
_this.doPull(args, callback);
}, ['repo']);
} else if(requireLogin && !this.hasScope('repo')) {
// logged in, but doesn't have correct scope
var newScopes = this.getScopes();
newScopes.push('repo');
this.login(function() {
_this.doPull(args, callback);
}, newScopes);
} else {
_this.doPull(args, callback);
}
}
this.doPull = function(args, callback) {
gh = new GitHub({token: token });
var _this = this;
this.setRepo(args.owner, args.repository);
this.getCurrentBranchName(function(branchName) {
_this.setBranch(branchName)
.then( getCurrentCommitSHA )
.then( getCurrentTreeSHA )
.then( function() {
// get list of all the files in the repository
return repo.getTree(currentBranch.treeSHA + '?recursive=1');
})
.then( (response) => {
if(response !== false) {
// set all the files to get..
treeFiles = response.data.tree;
_this.pullFiles(treeFiles, args, callback);
} else {
// uh oh, something went wrong
callback({ success: false, message: "Couldn't get list of files in project" });
}
})
.catch(function(e) {
// uh oh
callback({ success: false, message: e.message });
});
});
}
this.pullFiles = async function(treeFiles, args, callback) {
var repositoryId = repositoryOwner + '/' + repositoryName;
// assuming doc is initialised
// or has current files in it
var doc = g_app.doc;
// count the number of blobs (not folders), blobs are files
// work out if there is a repository folder by looking for /screens, old way of storing things..
var fileCount = 0;
repositoryFolder = '';
for(var i = 0; i < treeFiles.length; i++) {
var path = treeFiles[i].path;
if(treeFiles[i].type == 'blob') {
fileCount++;
} else {
var pos = path.indexOf('/screens');
if(pos !== -1) {
repositoryFolder = path.substring(0, pos);
}
}
}
// keep track of files to pull/have been pulled
// mostly if want to prompt user to confirm
var filesToPull = [];
var fileListOnly = true;
if(typeof args.listFilesOnly) {
fileListOnly = args.listFilesOnly;
}
// load each of the files...
var fileLoadedCount = 0;
var filesToLoadCount = 0;
// count how many files need to pull
for(var i = 0; i < treeFiles.length; i++) {
if(treeFiles[i].type == 'blob') {
var sha = treeFiles[i].sha;
// path in the repository
var path = treeFiles[i].path;
// path in the doc, should be the same unless theres a repository folder
var docPath = path;
var slashPos = path.lastIndexOf('/');
var parentPath = path.substring(0, slashPos);
// remove the repository folder from the parent folder..
if(repositoryFolder.length > 0 && parentPath.indexOf(repositoryFolder) === 0) {
parentPath = parentPath.substring(repositoryFolder.length + 1);
docPath = docPath.substring(repositoryFolder.length + 1);
}
var dotPos = docPath.lastIndexOf('.');
var extension = '';
if(dotPos !== -1) {
extension = docPath.substring(dotPos + 1).toLowerCase();
}
// only config files can have .json extension?
// maybe should check if in folder that removes the json from path
if(extension == 'json' && docPath.indexOf('config/') == -1) {
docPath = docPath.substring(0, dotPos);
}
if(!doc.hasVersion(docPath, sha)) {
filesToLoadCount++;
}
}
}
for(var i = 0; i < treeFiles.length; i++) {
// only interested in blob, not tree
if(treeFiles[i].type == 'blob') {
var sha = treeFiles[i].sha;
// path in the repository
var path = treeFiles[i].path;
// path in the doc, should be the same unless theres a repository folder
var docPath = path;
var slashPos = path.lastIndexOf('/');
var parentPath = path.substring(0, slashPos);
// remove the repository folder from the parent folder..
if(repositoryFolder.length > 0 && parentPath.indexOf(repositoryFolder) === 0) {
parentPath = parentPath.substring(repositoryFolder.length + 1);
docPath = docPath.substring(repositoryFolder.length + 1);
}
var dotPos = docPath.lastIndexOf('.');
var extension = '';
if(dotPos !== -1) {
extension = docPath.substring(dotPos + 1).toLowerCase();
}
// only config files can have .json extension?
// maybe should check if in folder that removes the json from path
if(extension == 'json' && docPath.indexOf('config/') == -1) {
docPath = docPath.substring(0, dotPos);
}
// if the doc already has this version, dont reload it
if(!doc.hasVersion(docPath, sha)) {
filesToPull.push(docPath);
if(fileListOnly) {
} else {
var isBinaryFile = doc.isBinary(path);
if(typeof args.progress) {
args.progress({ message: 'Pulling ' + docPath + '...', progress: fileLoadedCount / filesToLoadCount })
}
// ok, fetch the file.
var file = null;
if(isBinaryFile) {
file = await repo.getBlobAsBase64(sha);
} else {
file = await repo.getBlob(sha);
}
var fileData = file.data;
if(isBinaryFile && typeof file.data.content !== 'undefined') {
encoding = file.data.encoding;
fileData = file.data.content;
}
doc.addRecord({
path: docPath,
content: fileData,
sha: sha
});
// if this is the current record being displayed,
// then refresh what is being displayed
if(docPath.length > 0 && docPath[0] != '/') {
docPath = '/' + docPath;
}
var currentDocPath = g_app.projectNavigator.getCurrentPath();
if(currentDocPath == docPath) {
g_app.projectNavigator.showDocRecord(currentDocPath, { forceReload: true });
}
}
fileLoadedCount++;
}
}
}
if(callback) {
callback({
filesToPull: filesToPull,
success: true,
status: 200
});
}
}
// get a list of all files in a repository, then call loadFiles
this.doLoad = function(args, callback) {
var _this = this;
gh = new GitHub({token: token });
this.setRepo(args.owner, args.repository);
this.getCurrentBranchName(function(branchName) {
_this.setBranch(branchName)
.then( getCurrentCommitSHA )
.then( getCurrentTreeSHA )
.then( function() {
return repo.getTree(currentBranch.treeSHA + '?recursive=1');
})
.then( (response) => {
if(response !== false) {
// set all the files to get..
treeFiles = response.data.tree;
_this.loadFiles(treeFiles, args, callback);
} else {
// uh oh, something went wrong
alert("Couldn't find containing folder");
}
// return treeFiles;
}).catch(function(e) {
console.log("EXCEPTION IN Load!!!");
console.log(e);
callback({ success: false, message: e.message });
}); ;
});
}
// treeFiles is from doLoad, contains all the files in the repository
this.loadFiles = async function(treeFiles, args, callback) {
g_app.doc = new Document();
g_app.doc.init(g_app);
var doc = g_app.doc;
var colorPaletteManager = g_app.textModeEditor.colorPaletteManager;
var tileSetManager = g_app.textModeEditor.tileSetManager;
var screenManager = g_app.textModeEditor.graphic;
g_app.createDocumentStructure(doc);
var colorPaletteId = '';
var tileSetId = '';
//g_app.textModeEditor.layers.load();
var folders = [
{ 'path': 'tile sets', 'type': 'tile set', 'extension': 'json' },
{ 'path': 'color palettes', 'type': 'color palette', 'extension': 'json' },
{ 'path': 'screens', 'type': 'screen', 'extension': 'json' },
{ 'path': 'sprites', 'type': 'sprite', 'extension': 'json' },
{ 'path': 'music', 'type': 'music', 'extension': 'json' },
{ 'path': 'asm', 'type': 'asm', 'extension': 'asm' },
{ 'path': 'scripts', 'type': 'script', 'extension': 'js' },
{ 'path': 'build', 'type': 'prg', 'extension': 'prg' }
];
// count the number of blobs (not folders), blobs are files
// work out if there is a repository folder by looking for /screens, old way of storing things..
var fileCount = 0;
repositoryFolder = '';
for(var i = 0; i < treeFiles.length; i++) {
var path = treeFiles[i].path;
if(treeFiles[i].type == 'blob') {
fileCount++;
} else {
var pos = path.indexOf('/screens');
if(pos !== -1) {
repositoryFolder = path.substring(0, pos);
}
}
}
var repositoryId = repositoryOwner + '/' + repositoryName;
var _this = this;
var binaryExtensions = [
'prg',
'bin',
'rom',
'nes'
];
// get local versions of the files in the repository, no longer used...
// g_app.fileManager.getRepositoryFiles(repositoryId, treeFiles, async function(localFiles) {
// load each of the files...
var fileLoadedCount = 0;
for(var i = 0; i < treeFiles.length; i++) {
if(treeFiles[i].type == 'blob') {
var sha = treeFiles[i].sha;
// path in the repository
var path = treeFiles[i].path;
// path in the doc, should be the same unless theres a repository folder
var docPath = path;
var slashPos = path.lastIndexOf('/');
var parentPath = path.substring(0, slashPos);
// remove the repository folder from the parent folder..
if(repositoryFolder.length > 0 && parentPath.indexOf(repositoryFolder) === 0) {
parentPath = parentPath.substring(repositoryFolder.length + 1);
docPath = docPath.substring(repositoryFolder.length + 1);
}
var name = path.substring(slashPos + 1);
var extension = '';
var dotPos = path.lastIndexOf('.');
if(dotPos !== -1) {
extension = path.substring(dotPos + 1).toLowerCase();
}
var isBinaryFile = false;
isBinaryFile = binaryExtensions.indexOf(extension.toLowerCase()) !== -1;
var file = null;
if(isBinaryFile) {
file = await repo.getBlobAsBase64(sha);
} else {
file = await repo.getBlob(sha);
}
if(typeof args.progress) {
args.progress({ message: 'Loading ' + name + '...', progress: fileLoadedCount / fileCount })
}
var fileData = file.data;
if(isBinaryFile && typeof file.data.content !== 'undefined') {
encoding = file.data.encoding;
fileData = file.data.content;
}
doc.addRecord({
path: docPath,
content: fileData,
sha: sha
});
fileLoadedCount++;
}
}
// console.log("DONE!!!!");
// return;
if(callback) {
callback({
success: true,
status: 200
});
}
// });
}
this.save = function(args, callback) {
var _this = this;
if(token === false) {
this.login(function() {
_this.doSave(args, callback);
});
} else {
_this.doSave(args, callback);
}
}
this.doSave = function(args, callback) {
var _this = this;
gh = new GitHub({token: token });
this.setRepo(args.owner, args.repository);
var commitMessage = 'commit...';
if(typeof args != 'undefined') {
if(typeof args.commitMessage != 'undefined') {
commitMessage = args.commitMessage;
}
}
var doc = g_app.doc;
files = doc.getFiles({
includeEmptyFolders: false,
doStringify: true
});
// return;
this.getCurrentBranchName(function(branchName) {
_this.setBranch(branchName)
.then( () => _this.pushFiles(commitMessage, files, args) )
.then(function(response) {
// now get the list of files and their sha's
}).then( getCurrentCommitSHA )
.then( getCurrentTreeSHA )
.then( function() {
// need to get the sha for the respository folder (data)
// so get the contents of root of tree
return repo.getContents(branchName, '');
}).then(function(response) {
var data = response.data;
repositoryFolderSHA = false;
if(repositoryFolder !== false && repositoryFolder != '') {
for(var i = 0; i < data.length; i++) {
if(data[i].path == repositoryFolder) {
// found the sha for the repository folder
repositoryFolderSHA = data[i].sha;
break;
}
}
return repo.getTree(repositoryFolderSHA + '?recursive=1');
} else {
return repo.getTree(currentBranch.treeSHA + '?recursive=1');
}
}).then(function(response) {
// set all the files to get..
treeFiles = response.data.tree;
_this.updateBrowserFiles(treeFiles, files, function() {
if(callback) {
callback(response);
}
});
}).catch(function(e) {
console.log("EXCEPTION IN SAVE!!!");
console.log(e.message);
if(callback) {
callback({ error: true, message: e.message });
}
});
});
}
this.updateBrowserFiles = function(treeFiles, files, callback) {
// need to update in memory doc files
var doc = g_app.doc;
for(var i = 0; i < treeFiles.length; i++) {
var path = treeFiles[i].path;
if(path.length > 0 && path[0] != '/') {
path = '/' + path;
}
var pathParts = path.split('/');
var extension = '';
var dotPos = path.lastIndexOf('.');
if(dotPos !== -1) {
extension = path.substring(dotPos + 1).trim().toLowerCase();
}
var parentPath = pathParts[1];
// if extension is json, remove it from the name
// only do this for color palette, screen, etc?
if(extension == 'json'
&& (
parentPath == 'color palettes'
|| parentPath == 'tile sets'
|| parentPath == 'screens'
|| parentPath == 'sprites'
|| parentPath == 'music'
|| parentPath == '3d scenes'
)
) {
path = path.substring(0, dotPos);
}
var sha = treeFiles[i].sha;
var record = doc.getDocRecord(path);
if(record) {
record.sha = sha;
} else {
console.error('couldnt find: ' + path);
}
}
// update browser saved files
var repositoryId = repositoryOwner + '/' + repositoryName;
g_app.fileManager.updateFileSHA(repositoryId, treeFiles, files, function() {
callback();
});
return;
}
/**
* Sets the current repository to make push to
* @public
* @param {string} userName Name of the user who owns the repository
* @param {string} repoName Name of the repository
* @return void
*/
this.setRepo = function(userName, repoName) {
repositoryOwner = userName;
repositoryName = repoName;
repo = gh.getRepo(userName, repoName);
}
/**
* Sets the current branch to make push to. If the branch doesn't exist yet,
* it will be created first
* @public
* @param {string} branchName The name of the branch
* @return {Promise}
*/
this.setBranch = function(branchName) {
if (!repo) {
throw 'Repository is not initialized';
}
return repo.listBranches().then((branches) => {
var branchExists = branches.data.find( branch => branch.name === branchName );
if (!branchExists) {
return repo.createBranch('main', branchName)
.then(() => {
currentBranch.name = branchName;
});
} else {
currentBranch.name = branchName;
}
});
}
this.getFileSHA = function(file) {
var fileSHA = '';
// get the sha
for(var i = 0; i < treeFiles.length; i++) {
if(treeFiles[i].path == file) {
fileSHA = treeFiles[i].sha;
break;
}
}
return fileSHA;
}