-
Notifications
You must be signed in to change notification settings - Fork 8
/
gitbackend.service.ts
970 lines (886 loc) · 36.4 KB
/
gitbackend.service.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
import { Injectable, OnDestroy } from '@angular/core';
import { AsyncSubject , Observable , BehaviorSubject , of , from as fromPromise , throwError } from 'rxjs';
import { FileBrowserService } from '../filebrowser.service';
import { FileInfo } from '../filebrowser.service';
import { mergeMap, map, tap, take, last } from 'rxjs/operators';
import { HttpHeaders, HttpClient, HttpEventType, HttpEvent, HttpRequest } from '@angular/common/http';
import { ConflictPick, hasConflicts, getConflictVersion, getJSONConflictVersion } from './resolveconflict';
/*
* These are used in the worker - but we declare them here so that typescript doesn't complain
*/
declare var importScripts;
declare var Module;
declare var FS;
declare var IDBFS;
declare var self;
export enum GIT_MERGE_FILE_FAVOR {
GIT_MERGE_FILE_FAVOR_NORMAL,
GIT_MERGE_FILE_FAVOR_OURS,
GIT_MERGE_FILE_FAVOR_THEIRS,
GIT_MERGE_FILE_FAVOR_UNION
};
function hex(buffer) {
const hexCodes = [];
const view = new DataView(buffer);
for (let i = 0; i < view.byteLength; i += 4) {
// Using getUint32 reduces the number of iterations needed (we process 4 bytes each time)
const value = view.getUint32(i);
// toString(16) will give the hex representation of the number without padding
const stringValue = value.toString(16);
// We use concatenation and slice for padding
const padding = '00000000';
const paddedValue = (padding + stringValue).slice(-padding.length);
hexCodes.push(paddedValue);
}
// Join all the hex strings into one
return hexCodes.join('');
}
function formatBytes(a, b?): string {
if (0 === a) {
return '0 B';
}
const c = 1e3,
d = b || 0,
e = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
f = Math.floor(Math.log(a) / Math.log(c));
return parseFloat((a / Math.pow(c, f)).toFixed(d)) + ' ' + e[f];
}
class LFSDownloadInfo {
href: string;
headers: HttpHeaders;
}
@Injectable()
export class GitBackendService extends FileBrowserService implements OnDestroy {
workerReady: AsyncSubject<boolean> = new AsyncSubject();
worker: Worker;
syncInProgress = false;
repositoryOpen = false;
mountdir: string;
workermessageid = 1;
resolvemap: {[id: number]: Function} = {};
dirlisteners: {[dir: string]: BehaviorSubject<FileInfo[]>} = {};
convertUploadsToLFSPointer = false;
gitLFSEndpoint = '/fintechneo/browsergittestdata.git/info';
gitLFSAuthorizationHeaderValue = 'Basic ' + btoa('username:password');
proxyHost: string;
currentStatus: BehaviorSubject<string> = new BehaviorSubject(null);
/**
* Set to true to disable syncing filesystem with indexedDB
*/
syncLocalFSDisabled = false;
constructor(
private http: HttpClient
) {
super();
}
mount(dir: string): Observable<any> {
if (this.mountdir) {
throwError('Mount already called');
}
this.currentStatus.next('Mounting local filesystem');
this.mountdir = dir;
// The "stupid" worker is simply evaluating scripts that we pass on to it
this.worker = new Worker('assets/stupid_worker.js');
this.worker.onmessage = (msg) => {
if (msg.data.id) {
if (msg.data.error) {
this.resolvemap[msg.data.id]({error: msg.data.error});
} else {
this.resolvemap[msg.data.id](msg.data.response);
}
delete this.resolvemap[msg.data.id];
} else if (msg.data.progressmessage) {
this.currentStatus.next(msg.data.progressmessage);
}
};
// Set up emscripten with libgit2 (inside worker)
return fromPromise(this.callWorker((params) => {
return new Promise((resolve, reject) => {
importScripts('libgit2.js');
Module['onRuntimeInitialized'] = () => {
self.workdir = '/' + params.workdir;
FS.mkdir(self.workdir, '0777');
FS.mount(IDBFS, {}, self.workdir);
FS.chdir(self.workdir);
self.fromGitPath = (path) => {
const currentdir: string[] = FS.cwd().split('/');
const gitroot = self.workdir;
return gitroot + '/' + path;
};
self.toGitPath = (filename) => {
const currentdir: string[] = FS.cwd().substring(`${self.workdir}/`.length).split('/');
return currentdir.join('/') + '/' + filename;
};
self.jsgitprogresscallback = (msg) => {
console.log(msg);
self.postMessage({
progressmessage: msg
});
};
self.jsgitinit();
resolve();
};
});
}, {workdir: dir})
).pipe(
mergeMap(() => this.syncLocalFS(true)),
mergeMap(() => this.readdir() as Observable<FileInfo[]>),
mergeMap((ret) => {
const hasGitRepo = ret.find(file => file.name === '.git');
if (hasGitRepo) {
return fromPromise(
this.callWorker(() => {
console.log('Open repository');
self.jsgitopenrepo();
self.jsgitsetuser(self.gituserfullname, self.gituseremail);
self.jsgitstatus();
})
).pipe(
tap(() => this.repositoryOpen = true),
mergeMap(() => this.readdir())
);
} else {
return of(null);
}
}),
tap(() => {
this.workerReady.next(true);
this.workerReady.complete();
this.currentStatus.next(null);
})
);
}
/**
* Convert function to string source code and send it to the worker for evaluation
* @param func the function to send
* @param params an object that will be JSON stringified and passed to the function
* @returns a promise that with the result of the operation
*/
callWorker(func, params?: any): Promise<any> {
return new Promise((resolve, reject) => {
const workermessageid = this.workermessageid++;
this.resolvemap[workermessageid] = (result) => {
if (result && result.error) {
reject(result.error);
} else {
resolve(result);
}
};
this.worker.postMessage({
func: func.toString(),
params: params,
id: workermessageid
});
});
}
/**
*
* @param func the function to send to the worker
* @param params params for the function to execute
* @returns an Observable with the results (completes when done)
*/
callWorker2(func, params?: any): Observable<any> {
return new Observable((observer) => {
const workermessageid = this.workermessageid++;
this.resolvemap[workermessageid] = (result) => {
if (result && result.error) {
observer.error(result.error);
} else {
observer.next(result);
}
observer.complete();
};
this.worker.postMessage({
func: func.toString(),
params: params,
id: workermessageid
});
});
}
initRepository(): Observable<any> {
return this.callWorker2(() => {
self.jsgitinitrepo();
});
}
clone(url: string): Observable<any> {
this.currentStatus.next('Cloning remote repository');
return this.workerReady
.pipe(
mergeMap(() =>
this.callWorker2((params) => {
self.jsgitclone(params.url, self.workdir);
if(!self.jsgitgetlasterror()) {
self.jsgitstatusresult = [];
FS.chdir(self.workdir);
self.jsgitsetuser(self.gituserfullname, self.gituseremail);
self.jsgitgetlasterror();
}
return self.jsgitlasterrorresult;
}, {url: url})
),
map(err => {
if(err && err.klass) {
throw err;
}
}),
mergeMap(() => this.syncLocalFS(false)),
tap(() => this.repositoryOpen = true),
tap(() => this.updateAllDirListeners()),
tap(() => this.currentStatus.next(null))
);
}
/**
* @param path if not given, will read current directory and update listeners,
* otherwise return a string array with the filenames of the given path.
* @returns Observable with either string array of filenames if path is specified, or array of FileInfo if no path is specified
*/
readdir(path?: string): Observable<string[]> | Observable<FileInfo[]> {
if (!path) {
return this.readCurrentDirAndUpdateListeners();
}
return this._readdirString(path);
}
/*
* simple readdir list the files names in the path and return as string array
*/
private _readdirString(path: string): Observable<string[]> {
return this.callWorker2((params) =>
FS.readdir(params.path), { path: path });
}
/*
* Read contents from current directory and notify the fileList subject and single dir listeners
*/
readCurrentDirAndUpdateListeners(): Observable<FileInfo[]> {
return this.callWorker2(() =>
FS.readdir('.')
.map(name => Object.assign({
name: name,
fullpath: FS.cwd() + '/' + name
}, FS.stat(name))
)
.map(fileinfo =>
Object.assign(fileinfo,
{ isDir: FS.isDir(fileinfo.mode) }
)
)
)
.pipe(
mergeMap((files: FileInfo[]) =>
this.repositoryOpen ?
this.listConflicts().pipe(
map(cf => files.map(f =>
Object.assign(f, {
conflict: cf.findIndex(c =>
f.fullpath.substring(('/' + this.mountdir + '/').length) === c) > -1
}))
)
) :
of(files)
),
tap((ret: FileInfo[]) =>
this.fileList.next(ret)
),
tap(() =>
this.currentpath.pipe(
take(1),
tap(p => this.updateDirListener(p.join('/')))
)
)
);
}
changedir(name: string): Observable<any> {
return fromPromise(this.callWorker((params) => FS.chdir(params.name), {name: name})
).pipe(
mergeMap(() => this.readdir()),
mergeMap(() => fromPromise(this.callWorker(() =>
self.toGitPath('').split(/\//).filter(p => p.length > 0)
))),
map((cwd) => this.currentpath.next(cwd))
);
}
unlink(filename: string): Observable<any> {
return fromPromise(
this.callWorker((params) => {
FS.unlink(params.filename);
console.log('Deleted local file', self.toGitPath(params.filename));
}, {filename: filename})
).pipe(
mergeMap(() => this.readdir()),
mergeMap(() => this.syncLocalFS(false))
);
}
listConflicts(): Observable<string[]> {
return this.callWorker2(() => {
return self.jsgitstatusresult.filter(r => r.status === 'conflict')
.map(c => c.our);
});
}
listTextFileConflicts(): Observable<string[]> {
return this.callWorker2(() => {
return self.jsgitstatusresult.filter(r =>
r.status === 'conflict' &&
r.binary === 0)
.map(c => c.our);
});
}
quickResolveConflict(fileName, chooseConflictSide: ConflictPick): Observable<any> {
return this.getTextFileContentsResolveConflicts(fileName, chooseConflictSide)
.pipe(
mergeMap(resolvedContents =>
this.saveTextFile(fileName, resolvedContents)
)
);
}
markConflictsResolved(): Observable<any> {
return this.callWorker2(() => {
const conflictstatusresults = self.jsgitstatusresult.filter(c => c.status === 'conflict');
conflictstatusresults.forEach(c => self.jsgitadd(c.our));
self.jsgitresolvemergecommit();
});
}
commitChanges(commitmessage?: string): Observable<any> {
return fromPromise(this.callWorker((params) => {
self.jsgitstatus();
const noconflictstatusresults = self.jsgitstatusresult.filter(c => c.status !== 'conflict');
const conflictstatusresults = self.jsgitstatusresult.filter(c => c.status === 'conflict');
if (conflictstatusresults.length > 0) {
console.log('Resolve conflicts before commiting changes.');
return;
}
if (self.jsgitworkdirnumberofdeltas() > 0
|| noconflictstatusresults.length > 0) {
noconflictstatusresults.forEach(p => {
if (p.status === 'deleted') {
self.jsgitremove(p.path);
} else {
if ((p.path as string).endsWith('/')) {
FS.readdir(self.fromGitPath(p.path))
.filter((f: string) => f.charAt(0) !== '.')
.forEach(f =>
self.jsgitadd(p.path + f)
);
}
self.jsgitadd(p.path);
}
});
self.jsgitaddfileswithchanges();
let commitmessage = params.commitmessage;
if(!commitmessage) {
const statusCount = {};
noconflictstatusresults.forEach(r => {
if(!statusCount[r.status]) {
statusCount[r.status] = [];
}
statusCount[r.status].push(r.path);
});
commitmessage = Object.keys(statusCount)
.map(statusName => `${statusName} ${statusCount[statusName].length} ` +
`(${statusCount[statusName].join(',')})`)
.join(', ');
}
self.jsgitcommit(
commitmessage
);
console.log('Changes committed');
} else {
console.log('No changes');
}
},{commitmessage: commitmessage})).pipe(
mergeMap(() => this.syncLocalFS(false))
);
}
getDownloadObjectUrl(filename: string): Observable<string> {
return this.callWorker2(params => {
const contents: Uint8Array = FS.readFile(params.filename);
const lfsheader = `version https://git-lfs.github.com/spec/v1`;
const isLFSPointer = String.fromCharCode.apply(null, contents.subarray(0, lfsheader.length)) === lfsheader;
if (isLFSPointer) {
return FS.readFile(params.filename, {encoding: 'utf8'});
} else {
return URL.createObjectURL(new Blob([contents], { type: 'application/octet-stream' }));
}
}, {filename: filename}
).pipe(
mergeMap((url: string) => {
if (url.indexOf('version ') === 0) {
const lfsPointerLines = url.split('\n');
const filesize = parseInt(lfsPointerLines[2].substring('size '.length), 10);
return this.getLFSDownloadInfo(url)
.pipe(
mergeMap((downloadobj) => {
const downloadurl = this.replaceWithProxyHost(downloadobj.href);
const req = new HttpRequest(
'GET',
downloadurl,
{
headers: downloadobj.headers,
responseType: 'blob', reportProgress: true
}
);
return this.http.request(req)
.pipe(
map((event: HttpEvent<any>) => {
if (event.type === HttpEventType.DownloadProgress) {
const percentDone = Math.round(100 * event.loaded / filesize);
this.currentStatus.next(
`Downloading ${formatBytes(event.loaded, 2)} ( ${percentDone} %)`
);
} else if (event.type === HttpEventType.Response) {
return event.body;
}
return event;
}),
last(),
map(blob =>
URL.createObjectURL(blob)
),
tap(() => this.currentStatus.next(null))
);
})
);
} else {
return of(url);
}
})
);
}
getTextFileContentsResolveConflicts(filename: string, chosenConclictSide: ConflictPick): Observable<string> {
return this.getTextFileContents(filename)
.pipe(
mergeMap(contents => {
if (hasConflicts(contents)) {
const resolved = filename.endsWith('.json') ?
getJSONConflictVersion(contents, chosenConclictSide) :
getConflictVersion(contents, chosenConclictSide);
return this.saveTextFile(filename, resolved)
.pipe(map(() => resolved));
} else {
return of(contents);
}
})
);
}
getTextFileContents(filename: string): Observable<string> {
return fromPromise(this.callWorker(params => {
return FS.readFile(params.filename, {encoding: 'utf8'});
}, {filename: filename}
));
}
saveTextFile(filename: string, content: string): Observable<any> {
return fromPromise(this.callWorker(params => {
return FS.writeFile(params.filename, params.content);
}, {filename: filename, content: content}
)).pipe(
mergeMap(() => this.syncLocalFS(false))
);
}
uploadFile(file: File): Observable<any> {
if (this.convertUploadsToLFSPointer) {
let filecontents: Uint8Array;
return new Observable<string>(observer => {
this.currentStatus.next('Calculating checksum for ' + file.name);
const filereader = new FileReader();
filereader.readAsArrayBuffer(file);
filereader.onload = async () => {
filecontents = new Uint8Array(filereader.result as ArrayBuffer);
const hashbuf = await window.crypto.subtle.digest('SHA-256',
filecontents
);
const lfsPointerText = `version https://git-lfs.github.com/spec/v1\n` +
`oid sha256:${hex(hashbuf)}\n` +
`size ${filecontents.length}\n`;
this.currentStatus.next(`Uploading ${file.name} to LFS storage`);
observer.next(lfsPointerText);
};
}).pipe(
mergeMap((lfsPointerText) =>
this.uploadToLFSStorage(lfsPointerText, file).pipe(
mergeMap(() => this.saveTextFile(file.name, lfsPointerText))
)
),
tap(() => this.gitLFSTrack(file.name)),
tap(() => this.currentStatus.next(null))
);
} else {
return new Observable(observer => {
this.callWorker((params) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', params.url, false);
xhr.responseType = 'arraybuffer';
xhr.send();
console.log(xhr.response);
FS.writeFile(params.name, new Uint8Array(xhr.response), {encoding: 'binary'});
const gitpath = self.toGitPath(params.name);
console.log('Written file locally', gitpath);
}, {url: URL.createObjectURL(file), name: file.name})
.then(() => {
observer.next(file.name);
});
}).pipe(
mergeMap(() => this.syncLocalFS(false))
);
}
}
mkdir(dirname: string): Observable<any> {
return fromPromise(
this.callWorker(params => {
FS.mkdir(params.dirname);
}, {dirname: dirname}
)
).pipe(
mergeMap(() => this.readdir()),
mergeMap(() => this.syncLocalFS(false))
);
}
rmdir(dirname: string): Observable<any> {
return this.callWorker2((params) => {
const dirnameparts: string[] = params.dirname.split('/');
if (dirnameparts.length > 1) {
FS.chdir('/' + dirnameparts.slice(0, dirnameparts.length - 1).join('/'));
console.log('cwd', FS.cwd());
}
const recursedir = (path) =>
FS.readdir(path)
.filter((f: string) => !(f=== '.' || f === '..' ))
.forEach((f: string) => {
const deletepath = path + '/' + f;
console.log('Deleting', deletepath);
if (FS.isDir(FS.stat(deletepath).mode)) {
recursedir(deletepath);
FS.rmdir(deletepath);
} else {
FS.unlink(deletepath);
}
});
recursedir(params.dirname);
FS.rmdir(params.dirname);
console.log('Removed directory', params.dirname);
}, {dirname: dirname}).pipe(
mergeMap(() => this.readdir()),
mergeMap(() => this.syncLocalFS(false))
);
}
rename(oldpath: string, newpath: string): Observable<any> {
return fromPromise(
this.callWorker(params => {
FS.rename(params.oldpath, params.newpath);
}, {oldpath: oldpath, newpath: newpath}
)
).pipe(
mergeMap(() => this.readdir()),
mergeMap(() => this.syncLocalFS(false))
);
}
push() {
this.currentStatus.next('Pushing local changes to server');
return this.callWorker2(() => {
self.jsgitpush();
self.jsgitgetlasterror();
return self.jsgitlasterrorresult;
}, {}
).pipe(
map(err => {
if(err && err.klass) {
throw err;
}
}),
tap(() => this.currentStatus.next(null))
);
}
pull(git_merge_file_favor: number = GIT_MERGE_FILE_FAVOR.GIT_MERGE_FILE_FAVOR_NORMAL) {
this.currentStatus.next('Pulling recent changes from server');
return this.callWorker2((params) => {
self.jsgitpull(params.git_merge_file_favor);
self.jsgitgetlasterror();
// Update status after pull
self.jsgitstatus();
return self.jsgitlasterrorresult;
}, {git_merge_file_favor: git_merge_file_favor}
).pipe(
map(err => {
if(err && err.klass) {
throw err;
}
}),
tap(() => this.currentStatus.next(null)),
mergeMap(() => this.readdir()),
mergeMap(() => this.syncLocalFS(false)),
tap(() => this.updateAllDirListeners())
);
}
listendir(dir: string): Observable<FileInfo[]> {
if (!this.dirlisteners[dir]) {
this.dirlisteners[dir] = new BehaviorSubject([]);
this.updateDirListener(dir);
}
return this.dirlisteners[dir];
}
updateAllDirListeners() {
Object.keys(this.dirlisteners).forEach(dir => this.updateDirListener(dir));
}
updateDirListener(dir: string) {
if (!this.dirlisteners[dir]) {
return;
}
setTimeout(() =>
this.workerReady.subscribe(() => {
this.callWorker((params) => {
const fulldirpath = self.fromGitPath(params.dir);
let exists = false;
try {
FS.stat(fulldirpath);
exists = true;
} catch (e) {
}
if (exists) {
console.log('update dir listener', fulldirpath, params.dir);
return FS.readdir(fulldirpath).map(name => Object.assign({
name: name,
fullpath: self.fromGitPath(`${params.dir}/${name}`)
}, FS.stat(self.fromGitPath(`${params.dir}/${name}`)))
)
.map(fileinfo =>
Object.assign(fileinfo,
{ isDir: FS.isDir(fileinfo.mode) }
)
).filter(fileinfo => !fileinfo.isDir);
} else {
return [];
}
},
{dir: dir}
).then((files: FileInfo[]) => {
console.log(dir, files);
this.dirlisteners[dir].next(files);
});
}),
0);
}
/**
*
* @param direction false = write, true = read
*/
syncLocalFS(direction: boolean): Observable<any> {
console.log('synclocalfs called', direction, this.syncInProgress);
if (this.syncLocalFSDisabled) {
console.log('synclocalfs is disabled');
return of(false);
}
if (this.syncInProgress) {
return of(true);
} else {
this.syncInProgress = true;
return new Observable(observer => {
this.callWorker((params) =>
new Promise<any>((resolve, reject) =>
FS.syncfs(params.direction, () => {
console.log(params.direction ? 'reload persisted' : 'persisted');
resolve();
})
),
{direction: direction}
).then(() => {
this.syncInProgress = false;
observer.next();
});
});
}
}
unmount() {
if (this.worker) {
this.worker.terminate();
this.worker = null;
console.log('Git backend service terminated');
this.mountdir = null;
this.repositoryOpen = false;
}
}
/**
* jsgit doesn't read the host name and protocol from the url so need to set it from here
* @param host e.g. https://github.com
*/
setHost(host: string) {
this.callWorker2((params) =>
Module.jsgithost = params.host,
{host: host}
).subscribe();
}
/**
* Set name and email to be used for commit
* @param name
* @param email
*/
setUser(name: string, email: string) {
this.callWorker2((params) => {
self.gituserfullname = params.name;
self.gituseremail = params.email;
self.jsgitsetuser(self.gituserfullname, self.gituseremail);
},
{name: name, email: email}
).subscribe();
}
/**
* Additional headers to send with http request, e.g. authorization tokens
* @param headers
*/
setHeaders(headers: HttpHeaders) {
this.callWorker2((params) =>
Module.jsgitheaders = params.headers,
{
headers: headers.keys().map(key =>
({name: key, value: headers.get(key)}))
}
).subscribe();
}
history(): Observable<any> {
return this.callWorker2(() => {
self.jsgithistory();
return self.jsgithistoryresult;
});
}
replaceWithProxyHost(url) {
if (this.proxyHost) {
url = url.substring('https://'.length);
url = this.proxyHost + url.substring(url.indexOf('/'));
}
return url;
}
/**
* Similar to e.g.: git lfs track "*.psd"
*
* Will update .gitattributes
* @param pattern
*/
public gitLFSTrack(filenameorpattern: string) {
this.callWorker2((params) => {
console.log('gitLFStrac', params);
const pattern = params.pattern.replace(/\s/g, '[[:space:]]');
let hasPattern = false;
let gitattributeslines = [];
try {
gitattributeslines = FS.readFile('.gitattributes', {encoding: 'utf8'}).split('\n');
} catch (e) {}
const patternparts = pattern.split(/\./);
const extension = patternparts[patternparts.length - 1];
hasPattern = gitattributeslines.find(line => {
const linepattern = line.split(' ')[0];
const lineextension = linepattern.split('.')[1];
return line.indexOf('filter=lfs') > 0 &&
line.indexOf(`${pattern} `) === 0 ||
(line.charAt(0) === '*' && lineextension === extension);
}) ? true : false;
if (!hasPattern) {
gitattributeslines.push(`${pattern} filter=lfs diff=lfs merge=lfs -text`);
FS.writeFile('.gitattributes', gitattributeslines.join('\n'));
}
console.log(gitattributeslines);
}, {pattern: filenameorpattern}).subscribe();
}
private uploadToLFSStorage(lfsPointer: string, contents: Blob): Observable<any> {
const lfsPointerLines = lfsPointer.split('\n');
const sha256sum = lfsPointerLines[1].substring('oid sha256:'.length);
const size = parseInt(lfsPointerLines[2].substring('size '.length), 10);
return this.http
.post(this.gitLFSEndpoint + '/lfs/objects/batch',
{
'operation': 'upload',
'transfers': [ 'basic' ],
// 'ref': { 'name': 'refs/heads/master' },
'objects': [
{
'oid': sha256sum,
'size': size,
}
]
},
{
headers: {
'Authorization': this.gitLFSAuthorizationHeaderValue,
'Accept': 'application/vnd.git-lfs+json',
'Content-Type': 'application/vnd.git-lfs+json'
}
}
).pipe(
tap(ret => console.log(ret)),
mergeMap(
(ret: any) => {
if (!ret.objects[0].actions || ret.objects[0].actions.download) {
console.log('Already uploaded', sha256sum);
return of(true);
}
const uploadobj = ret.objects[0].actions.upload;
const verifyobj = ret.objects[0].actions.verify;
let headers = new HttpHeaders(uploadobj.header);
headers = headers.append('ngsw-bypass', 'true');
let url = uploadobj.href;
url = this.replaceWithProxyHost(url);
return this.http.request(
new HttpRequest<any>('PUT', url, contents, {headers: headers, reportProgress: true})
)
.pipe(
tap((event: HttpEvent<any>) => {
if (event.type === HttpEventType.UploadProgress) {
const percentDone = Math.round(100 * event.loaded / event.total);
this.currentStatus.next(`Uploading ${formatBytes(event.loaded, 2)} ( ${percentDone} % )`);
} else if (event.type === HttpEventType.Response) {
return event.body;
}
return event;
}),
last(),
mergeMap(() => verifyobj ?
this.http.post(
this.replaceWithProxyHost(verifyobj.href), {
oid: sha256sum,
size: size
}, {headers: verifyobj.header})
: of(true)
)
);
}
)
);
}
getLFSDownloadInfo(lfsPointer: string): Observable<LFSDownloadInfo> {
const lfsPointerLines = lfsPointer.split('\n');
const sha256sum = lfsPointerLines[1].substring('oid sha256:'.length);
const size = parseInt(lfsPointerLines[2].substring('size '.length), 10);
return this.http
.post(this.gitLFSEndpoint + '/lfs/objects/batch',
{
'operation': 'download',
'transfers': [ 'basic' ],
// 'ref': { 'name': 'refs/heads/master' },
'objects': [
{
'oid': sha256sum,
'size': size,
}
]
},
{
headers: {
'Authorization': this.gitLFSAuthorizationHeaderValue,
'Accept': 'application/vnd.git-lfs+json',
'Content-Type': 'application/vnd.git-lfs+json'
}
}
).pipe(map(
(ret: any) => {
const downloadobj = ret.objects[0].actions.download;
const url = downloadobj.href;
let headers = null;
if(downloadobj.header) {
headers = new HttpHeaders(downloadobj.header);
}
return {
href: url,
headers: headers
};
}
));
}
ngOnDestroy() {
this.unmount();
}
}