forked from isomorphic-git/isomorphic-git
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
14674 lines (13698 loc) · 427 KB
/
index.js
File metadata and controls
14674 lines (13698 loc) · 427 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
import AsyncLock from 'async-lock';
import Hash from 'sha.js/sha1.js';
import crc32 from 'crc-32';
import pako from 'pako';
import ignore from 'ignore';
import pify from 'pify';
import cleanGitRef from 'clean-git-ref';
import { readContract, selectWeightedPstHolder } from 'smartweave';
import axios from 'axios';
import diff3Merge from 'diff3';
/**
* @typedef {Object} GitProgressEvent
* @property {string} phase
* @property {number} loaded
* @property {number} total
*/
/**
* @callback ProgressCallback
* @param {GitProgressEvent} progress
* @returns {void | Promise<void>}
*/
/**
* @typedef {Object} GitHttpRequest
* @property {string} url - The URL to request
* @property {string} [method='GET'] - The HTTP method to use
* @property {Object<string, string>} [headers={}] - Headers to include in the HTTP request
* @property {AsyncIterableIterator<Uint8Array>} [body] - An async iterator of Uint8Arrays that make up the body of POST requests
* @property {ProgressCallback} [onProgress] - Reserved for future use (emitting `GitProgressEvent`s)
* @property {object} [signal] - Reserved for future use (canceling a request)
*/
/**
* @typedef {Object} GitHttpResponse
* @property {string} url - The final URL that was fetched after any redirects
* @property {string} [method] - The HTTP method that was used
* @property {Object<string, string>} [headers] - HTTP response headers
* @property {AsyncIterableIterator<Uint8Array>} [body] - An async iterator of Uint8Arrays that make up the body of the response
* @property {number} statusCode - The HTTP status code
* @property {string} statusMessage - The HTTP status message
*/
/**
* @callback HttpFetch
* @param {GitHttpRequest} request
* @returns {Promise<GitHttpResponse>}
*/
/**
* @typedef {Object} HttpClient
* @property {HttpFetch} request
*/
/**
* A git commit object.
*
* @typedef {Object} CommitObject
* @property {string} message Commit message
* @property {string} tree SHA-1 object id of corresponding file tree
* @property {string[]} parent an array of zero or more SHA-1 object ids
* @property {Object} author
* @property {string} author.name The author's name
* @property {string} author.email The author's email
* @property {number} author.timestamp UTC Unix timestamp in seconds
* @property {number} author.timezoneOffset Timezone difference from UTC in minutes
* @property {Object} committer
* @property {string} committer.name The committer's name
* @property {string} committer.email The committer's email
* @property {number} committer.timestamp UTC Unix timestamp in seconds
* @property {number} committer.timezoneOffset Timezone difference from UTC in minutes
* @property {string} [gpgsig] PGP signature (if present)
*/
/**
* An entry from a git tree object. Files are called 'blobs' and directories are called 'trees'.
*
* @typedef {Object} TreeEntry
* @property {string} mode the 6 digit hexadecimal mode
* @property {string} path the name of the file or directory
* @property {string} oid the SHA-1 object id of the blob or tree
* @property {'commit'|'blob'|'tree'} type the type of object
*/
/**
* A git tree object. Trees represent a directory snapshot.
*
* @typedef {TreeEntry[]} TreeObject
*/
/**
* A git annotated tag object.
*
* @typedef {Object} TagObject
* @property {string} object SHA-1 object id of object being tagged
* @property {'blob' | 'tree' | 'commit' | 'tag'} type the type of the object being tagged
* @property {string} tag the tag name
* @property {Object} tagger
* @property {string} tagger.name the tagger's name
* @property {string} tagger.email the tagger's email
* @property {number} tagger.timestamp UTC Unix timestamp in seconds
* @property {number} tagger.timezoneOffset timezone difference from UTC in minutes
* @property {string} message tag message
* @property {string} [gpgsig] PGP signature (if present)
*/
/**
* @typedef {Object} ReadCommitResult
* @property {string} oid - SHA-1 object id of this commit
* @property {CommitObject} commit - the parsed commit object
* @property {string} payload - PGP signing payload
*/
/**
* @typedef {Object} ServerRef - This object has the following schema:
* @property {string} ref - The name of the ref
* @property {string} oid - The SHA-1 object id the ref points to
* @property {string} [target] - The target ref pointed to by a symbolic ref
* @property {string} [peeled] - If the oid is the SHA-1 object id of an annotated tag, this is the SHA-1 object id that the annotated tag points to
*/
/**
* @typedef Walker
* @property {Symbol} Symbol('GitWalkerSymbol')
*/
/**
* Normalized subset of filesystem `stat` data:
*
* @typedef {Object} Stat
* @property {number} ctimeSeconds
* @property {number} ctimeNanoseconds
* @property {number} mtimeSeconds
* @property {number} mtimeNanoseconds
* @property {number} dev
* @property {number} ino
* @property {number} mode
* @property {number} uid
* @property {number} gid
* @property {number} size
*/
/**
* The `WalkerEntry` is an interface that abstracts computing many common tree / blob stats.
*
* @typedef {Object} WalkerEntry
* @property {function(): Promise<'tree'|'blob'|'special'|'commit'>} type
* @property {function(): Promise<number>} mode
* @property {function(): Promise<string>} oid
* @property {function(): Promise<Uint8Array|void>} content
* @property {function(): Promise<Stat>} stat
*/
/**
* @typedef {Object} CallbackFsClient
* @property {function} readFile - https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback
* @property {function} writeFile - https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback
* @property {function} unlink - https://nodejs.org/api/fs.html#fs_fs_unlink_path_callback
* @property {function} readdir - https://nodejs.org/api/fs.html#fs_fs_readdir_path_options_callback
* @property {function} mkdir - https://nodejs.org/api/fs.html#fs_fs_mkdir_path_mode_callback
* @property {function} rmdir - https://nodejs.org/api/fs.html#fs_fs_rmdir_path_callback
* @property {function} stat - https://nodejs.org/api/fs.html#fs_fs_stat_path_options_callback
* @property {function} lstat - https://nodejs.org/api/fs.html#fs_fs_lstat_path_options_callback
* @property {function} [readlink] - https://nodejs.org/api/fs.html#fs_fs_readlink_path_options_callback
* @property {function} [symlink] - https://nodejs.org/api/fs.html#fs_fs_symlink_target_path_type_callback
* @property {function} [chmod] - https://nodejs.org/api/fs.html#fs_fs_chmod_path_mode_callback
*/
/**
* @typedef {Object} PromiseFsClient
* @property {Object} promises
* @property {function} promises.readFile - https://nodejs.org/api/fs.html#fs_fspromises_readfile_path_options
* @property {function} promises.writeFile - https://nodejs.org/api/fs.html#fs_fspromises_writefile_file_data_options
* @property {function} promises.unlink - https://nodejs.org/api/fs.html#fs_fspromises_unlink_path
* @property {function} promises.readdir - https://nodejs.org/api/fs.html#fs_fspromises_readdir_path_options
* @property {function} promises.mkdir - https://nodejs.org/api/fs.html#fs_fspromises_mkdir_path_options
* @property {function} promises.rmdir - https://nodejs.org/api/fs.html#fs_fspromises_rmdir_path
* @property {function} promises.stat - https://nodejs.org/api/fs.html#fs_fspromises_stat_path_options
* @property {function} promises.lstat - https://nodejs.org/api/fs.html#fs_fspromises_lstat_path_options
* @property {function} [promises.readlink] - https://nodejs.org/api/fs.html#fs_fspromises_readlink_path_options
* @property {function} [promises.symlink] - https://nodejs.org/api/fs.html#fs_fspromises_symlink_target_path_type
* @property {function} [promises.chmod] - https://nodejs.org/api/fs.html#fs_fspromises_chmod_path_mode
*/
/**
* @typedef {CallbackFsClient | PromiseFsClient} FsClient
*/
/**
* @callback MessageCallback
* @param {string} message
* @returns {void | Promise<void>}
*/
/**
* @typedef {Object} GitAuth
* @property {string} [username]
* @property {string} [password]
* @property {Object<string, string>} [headers]
* @property {boolean} [cancel] Tells git to throw a `UserCanceledError` (instead of an `HttpError`).
*/
/**
* @callback AuthCallback
* @param {string} url
* @param {GitAuth} auth Might have some values if the URL itself originally contained a username or password.
* @returns {GitAuth | void | Promise<GitAuth | void>}
*/
/**
* @callback AuthFailureCallback
* @param {string} url
* @param {GitAuth} auth The credentials that failed
* @returns {GitAuth | void | Promise<GitAuth | void>}
*/
/**
* @callback AuthSuccessCallback
* @param {string} url
* @param {GitAuth} auth
* @returns {void | Promise<void>}
*/
/**
* @typedef {Object} SignParams
* @property {string} payload - a plaintext message
* @property {string} secretKey - an 'ASCII armor' encoded PGP key (technically can actually contain _multiple_ keys)
*/
/**
* @callback SignCallback
* @param {SignParams} args
* @return {{signature: string} | Promise<{signature: string}>} - an 'ASCII armor' encoded "detached" signature
*/
/**
* @callback WalkerMap
* @param {string} filename
* @param {WalkerEntry[]} entries
* @returns {Promise<any>}
*/
/**
* @callback WalkerReduce
* @param {any} parent
* @param {any[]} children
* @returns {Promise<any>}
*/
/**
* @callback WalkerIterateCallback
* @param {WalkerEntry[]} entries
* @returns {Promise<any[]>}
*/
/**
* @callback WalkerIterate
* @param {WalkerIterateCallback} walk
* @param {IterableIterator<WalkerEntry[]>} children
* @returns {Promise<any[]>}
*/
/**
* @typedef {Object} RefUpdateStatus
* @property {boolean} ok
* @property {string} error
*/
/**
* @typedef {Object} PushResult
* @property {boolean} ok
* @property {?string} error
* @property {Object<string, RefUpdateStatus>} refs
* @property {Object<string, string>} [headers]
*/
/**
* @typedef {0|1} HeadStatus
*/
/**
* @typedef {0|1|2} WorkdirStatus
*/
/**
* @typedef {0|1|2|3} StageStatus
*/
/**
* @typedef {[string, HeadStatus, WorkdirStatus, StageStatus]} StatusRow
*/
class BaseError extends Error {
constructor(message) {
super(message);
// Setting this here allows TS to infer that all git errors have a `caller` property and
// that its type is string.
this.caller = '';
}
toJSON() {
// Error objects aren't normally serializable. So we do something about that.
return {
code: this.code,
data: this.data,
caller: this.caller,
message: this.message,
stack: this.stack,
}
}
fromJSON(json) {
const e = new BaseError(json.message);
e.code = json.code;
e.data = json.data;
e.caller = json.caller;
e.stack = json.stack;
return e
}
get isIsomorphicGitError() {
return true
}
}
class InternalError extends BaseError {
/**
* @param {string} message
*/
constructor(message) {
super(
`An internal error caused this command to fail. Please file a bug report at https://github.com/isomorphic-git/isomorphic-git/issues with this error message: ${message}`
);
this.code = this.name = InternalError.code;
this.data = { message };
}
}
/** @type {'InternalError'} */
InternalError.code = 'InternalError';
// Modeled after https://github.com/tjfontaine/node-buffercursor
// but with the goal of being much lighter weight.
class BufferCursor {
constructor(buffer) {
this.buffer = buffer;
this._start = 0;
}
eof() {
return this._start >= this.buffer.length
}
tell() {
return this._start
}
seek(n) {
this._start = n;
}
slice(n) {
const r = this.buffer.slice(this._start, this._start + n);
this._start += n;
return r
}
toString(enc, length) {
const r = this.buffer.toString(enc, this._start, this._start + length);
this._start += length;
return r
}
write(value, length, enc) {
const r = this.buffer.write(value, this._start, length, enc);
this._start += length;
return r
}
copy(source, start, end) {
const r = source.copy(this.buffer, this._start, start, end);
this._start += r;
return r
}
readUInt8() {
const r = this.buffer.readUInt8(this._start);
this._start += 1;
return r
}
writeUInt8(value) {
const r = this.buffer.writeUInt8(value, this._start);
this._start += 1;
return r
}
readUInt16BE() {
const r = this.buffer.readUInt16BE(this._start);
this._start += 2;
return r
}
writeUInt16BE(value) {
const r = this.buffer.writeUInt16BE(value, this._start);
this._start += 2;
return r
}
readUInt32BE() {
const r = this.buffer.readUInt32BE(this._start);
this._start += 4;
return r
}
writeUInt32BE(value) {
const r = this.buffer.writeUInt32BE(value, this._start);
this._start += 4;
return r
}
}
function compareStrings(a, b) {
// https://stackoverflow.com/a/40355107/2168416
return -(a < b) || +(a > b)
}
function comparePath(a, b) {
// https://stackoverflow.com/a/40355107/2168416
return compareStrings(a.path, b.path)
}
/**
* From https://github.com/git/git/blob/master/Documentation/technical/index-format.txt
*
* 32-bit mode, split into (high to low bits)
*
* 4-bit object type
* valid values in binary are 1000 (regular file), 1010 (symbolic link)
* and 1110 (gitlink)
*
* 3-bit unused
*
* 9-bit unix permission. Only 0755 and 0644 are valid for regular files.
* Symbolic links and gitlinks have value 0 in this field.
*/
function normalizeMode(mode) {
// Note: BrowserFS will use -1 for "unknown"
// I need to make it non-negative for these bitshifts to work.
let type = mode > 0 ? mode >> 12 : 0;
// If it isn't valid, assume it as a "regular file"
// 0100 = directory
// 1000 = regular file
// 1010 = symlink
// 1110 = gitlink
if (
type !== 0b0100 &&
type !== 0b1000 &&
type !== 0b1010 &&
type !== 0b1110
) {
type = 0b1000;
}
let permissions = mode & 0o777;
// Is the file executable? then 755. Else 644.
if (permissions & 0b001001001) {
permissions = 0o755;
} else {
permissions = 0o644;
}
// If it's not a regular file, scrub all permissions
if (type !== 0b1000) permissions = 0;
return (type << 12) + permissions
}
const MAX_UINT32 = 2 ** 32;
function SecondsNanoseconds(
givenSeconds,
givenNanoseconds,
milliseconds,
date
) {
if (givenSeconds !== undefined && givenNanoseconds !== undefined) {
return [givenSeconds, givenNanoseconds]
}
if (milliseconds === undefined) {
milliseconds = date.valueOf();
}
const seconds = Math.floor(milliseconds / 1000);
const nanoseconds = (milliseconds - seconds * 1000) * 1000000;
return [seconds, nanoseconds]
}
function normalizeStats(e) {
const [ctimeSeconds, ctimeNanoseconds] = SecondsNanoseconds(
e.ctimeSeconds,
e.ctimeNanoseconds,
e.ctimeMs,
e.ctime
);
const [mtimeSeconds, mtimeNanoseconds] = SecondsNanoseconds(
e.mtimeSeconds,
e.mtimeNanoseconds,
e.mtimeMs,
e.mtime
);
return {
ctimeSeconds: ctimeSeconds % MAX_UINT32,
ctimeNanoseconds: ctimeNanoseconds % MAX_UINT32,
mtimeSeconds: mtimeSeconds % MAX_UINT32,
mtimeNanoseconds: mtimeNanoseconds % MAX_UINT32,
dev: e.dev % MAX_UINT32,
ino: e.ino % MAX_UINT32,
mode: normalizeMode(e.mode % MAX_UINT32),
uid: e.uid % MAX_UINT32,
gid: e.gid % MAX_UINT32,
// size of -1 happens over a BrowserFS HTTP Backend that doesn't serve Content-Length headers
// (like the Karma webserver) because BrowserFS HTTP Backend uses HTTP HEAD requests to do fs.stat
size: e.size > -1 ? e.size % MAX_UINT32 : 0,
}
}
function toHex(buffer) {
let hex = '';
for (const byte of new Uint8Array(buffer)) {
if (byte < 16) hex += '0';
hex += byte.toString(16);
}
return hex
}
/* eslint-env node, browser */
let supportsSubtleSHA1 = null;
async function shasum(buffer) {
if (supportsSubtleSHA1 === null) {
supportsSubtleSHA1 = await testSubtleSHA1();
}
return supportsSubtleSHA1 ? subtleSHA1(buffer) : shasumSync(buffer)
}
// This is modeled after @dominictarr's "shasum" module,
// but without the 'json-stable-stringify' dependency and
// extra type-casting features.
function shasumSync(buffer) {
return new Hash().update(buffer).digest('hex')
}
async function subtleSHA1(buffer) {
const hash = await crypto.subtle.digest('SHA-1', buffer);
return toHex(hash)
}
async function testSubtleSHA1() {
// I'm using a rather crude method of progressive enhancement, because
// some browsers that have crypto.subtle.digest don't actually implement SHA-1.
try {
const hash = await subtleSHA1(new Uint8Array([]));
if (hash === 'da39a3ee5e6b4b0d3255bfef95601890afd80709') return true
} catch (_) {
// no bother
}
return false
}
// Extract 1-bit assume-valid, 1-bit extended flag, 2-bit merge state flag, 12-bit path length flag
function parseCacheEntryFlags(bits) {
return {
assumeValid: Boolean(bits & 0b1000000000000000),
extended: Boolean(bits & 0b0100000000000000),
stage: (bits & 0b0011000000000000) >> 12,
nameLength: bits & 0b0000111111111111,
}
}
function renderCacheEntryFlags(entry) {
const flags = entry.flags;
// 1-bit extended flag (must be zero in version 2)
flags.extended = false;
// 12-bit name length if the length is less than 0xFFF; otherwise 0xFFF
// is stored in this field.
flags.nameLength = Math.min(Buffer.from(entry.path).length, 0xfff);
return (
(flags.assumeValid ? 0b1000000000000000 : 0) +
(flags.extended ? 0b0100000000000000 : 0) +
((flags.stage & 0b11) << 12) +
(flags.nameLength & 0b111111111111)
)
}
class GitIndex {
/*::
_entries: Map<string, CacheEntry>
_dirty: boolean // Used to determine if index needs to be saved to filesystem
*/
constructor(entries) {
this._dirty = false;
this._entries = entries || new Map();
}
static async from(buffer) {
if (Buffer.isBuffer(buffer)) {
return GitIndex.fromBuffer(buffer)
} else if (buffer === null) {
return new GitIndex(null)
} else {
throw new InternalError('invalid type passed to GitIndex.from')
}
}
static async fromBuffer(buffer) {
// Verify shasum
const shaComputed = await shasum(buffer.slice(0, -20));
const shaClaimed = buffer.slice(-20).toString('hex');
if (shaClaimed !== shaComputed) {
throw new InternalError(
`Invalid checksum in GitIndex buffer: expected ${shaClaimed} but saw ${shaComputed}`
)
}
const reader = new BufferCursor(buffer);
const _entries = new Map();
const magic = reader.toString('utf8', 4);
if (magic !== 'DIRC') {
throw new InternalError(`Inavlid dircache magic file number: ${magic}`)
}
const version = reader.readUInt32BE();
if (version !== 2) {
throw new InternalError(`Unsupported dircache version: ${version}`)
}
const numEntries = reader.readUInt32BE();
let i = 0;
while (!reader.eof() && i < numEntries) {
const entry = {};
entry.ctimeSeconds = reader.readUInt32BE();
entry.ctimeNanoseconds = reader.readUInt32BE();
entry.mtimeSeconds = reader.readUInt32BE();
entry.mtimeNanoseconds = reader.readUInt32BE();
entry.dev = reader.readUInt32BE();
entry.ino = reader.readUInt32BE();
entry.mode = reader.readUInt32BE();
entry.uid = reader.readUInt32BE();
entry.gid = reader.readUInt32BE();
entry.size = reader.readUInt32BE();
entry.oid = reader.slice(20).toString('hex');
const flags = reader.readUInt16BE();
entry.flags = parseCacheEntryFlags(flags);
// TODO: handle if (version === 3 && entry.flags.extended)
const pathlength = buffer.indexOf(0, reader.tell() + 1) - reader.tell();
if (pathlength < 1) {
throw new InternalError(`Got a path length of: ${pathlength}`)
}
// TODO: handle pathnames larger than 12 bits
entry.path = reader.toString('utf8', pathlength);
// The next bit is awkward. We expect 1 to 8 null characters
// such that the total size of the entry is a multiple of 8 bits.
// (Hence subtract 12 bytes for the header.)
let padding = 8 - ((reader.tell() - 12) % 8);
if (padding === 0) padding = 8;
while (padding--) {
const tmp = reader.readUInt8();
if (tmp !== 0) {
throw new InternalError(
`Expected 1-8 null characters but got '${tmp}' after ${entry.path}`
)
} else if (reader.eof()) {
throw new InternalError('Unexpected end of file')
}
}
// end of awkward part
_entries.set(entry.path, entry);
i++;
}
return new GitIndex(_entries)
}
get entries() {
return [...this._entries.values()].sort(comparePath)
}
get entriesMap() {
return this._entries
}
*[Symbol.iterator]() {
for (const entry of this.entries) {
yield entry;
}
}
insert({ filepath, stats, oid }) {
stats = normalizeStats(stats);
const bfilepath = Buffer.from(filepath);
const entry = {
ctimeSeconds: stats.ctimeSeconds,
ctimeNanoseconds: stats.ctimeNanoseconds,
mtimeSeconds: stats.mtimeSeconds,
mtimeNanoseconds: stats.mtimeNanoseconds,
dev: stats.dev,
ino: stats.ino,
// We provide a fallback value for `mode` here because not all fs
// implementations assign it, but we use it in GitTree.
// '100644' is for a "regular non-executable file"
mode: stats.mode || 0o100644,
uid: stats.uid,
gid: stats.gid,
size: stats.size,
path: filepath,
oid: oid,
flags: {
assumeValid: false,
extended: false,
stage: 0,
nameLength: bfilepath.length < 0xfff ? bfilepath.length : 0xfff,
},
};
this._entries.set(entry.path, entry);
this._dirty = true;
}
delete({ filepath }) {
if (this._entries.has(filepath)) {
this._entries.delete(filepath);
} else {
for (const key of this._entries.keys()) {
if (key.startsWith(filepath + '/')) {
this._entries.delete(key);
}
}
}
this._dirty = true;
}
clear() {
this._entries.clear();
this._dirty = true;
}
render() {
return this.entries
.map(entry => `${entry.mode.toString(8)} ${entry.oid} ${entry.path}`)
.join('\n')
}
async toObject() {
const header = Buffer.alloc(12);
const writer = new BufferCursor(header);
writer.write('DIRC', 4, 'utf8');
writer.writeUInt32BE(2);
writer.writeUInt32BE(this.entries.length);
const body = Buffer.concat(
this.entries.map(entry => {
const bpath = Buffer.from(entry.path);
// the fixed length + the filename + at least one null char => align by 8
const length = Math.ceil((62 + bpath.length + 1) / 8) * 8;
const written = Buffer.alloc(length);
const writer = new BufferCursor(written);
const stat = normalizeStats(entry);
writer.writeUInt32BE(stat.ctimeSeconds);
writer.writeUInt32BE(stat.ctimeNanoseconds);
writer.writeUInt32BE(stat.mtimeSeconds);
writer.writeUInt32BE(stat.mtimeNanoseconds);
writer.writeUInt32BE(stat.dev);
writer.writeUInt32BE(stat.ino);
writer.writeUInt32BE(stat.mode);
writer.writeUInt32BE(stat.uid);
writer.writeUInt32BE(stat.gid);
writer.writeUInt32BE(stat.size);
writer.write(entry.oid, 20, 'hex');
writer.writeUInt16BE(renderCacheEntryFlags(entry));
writer.write(entry.path, bpath.length, 'utf8');
return written
})
);
const main = Buffer.concat([header, body]);
const sum = await shasum(main);
return Buffer.concat([main, Buffer.from(sum, 'hex')])
}
}
function compareStats(entry, stats) {
// Comparison based on the description in Paragraph 4 of
// https://www.kernel.org/pub/software/scm/git/docs/technical/racy-git.txt
const e = normalizeStats(entry);
const s = normalizeStats(stats);
const staleness =
e.mode !== s.mode ||
e.mtimeSeconds !== s.mtimeSeconds ||
e.ctimeSeconds !== s.ctimeSeconds ||
e.uid !== s.uid ||
e.gid !== s.gid ||
e.ino !== s.ino ||
e.size !== s.size;
return staleness
}
// import LockManager from 'travix-lock-manager'
// import Lock from '../utils.js'
// const lm = new LockManager()
let lock = null;
function createCache() {
return {
map: new Map(),
stats: new Map(),
}
}
async function updateCachedIndexFile(fs, filepath, cache) {
const stat = await fs.lstat(filepath);
const rawIndexFile = await fs.read(filepath);
const index = await GitIndex.from(rawIndexFile);
// cache the GitIndex object so we don't need to re-read it every time.
cache.map.set(filepath, index);
// Save the stat data for the index so we know whether the cached file is stale (modified by an outside process).
cache.stats.set(filepath, stat);
}
// Determine whether our copy of the index file is stale
async function isIndexStale(fs, filepath, cache) {
const savedStats = cache.stats.get(filepath);
if (savedStats === undefined) return true
const currStats = await fs.lstat(filepath);
if (savedStats === null) return false
if (currStats === null) return false
return compareStats(savedStats, currStats)
}
class GitIndexManager {
/**
*
* @param {object} opts
* @param {import('../models/FileSystem.js').FileSystem} opts.fs
* @param {string} opts.gitdir
* @param {object} opts.cache
* @param {function(GitIndex): any} closure
*/
static async acquire({ fs, gitdir, cache }, closure) {
if (!cache.index) cache.index = createCache();
const filepath = `${gitdir}/index`;
if (lock === null) lock = new AsyncLock({ maxPending: Infinity });
let result;
await lock.acquire(filepath, async function() {
// Acquire a file lock while we're reading the index
// to make sure other processes aren't writing to it
// simultaneously, which could result in a corrupted index.
// const fileLock = await Lock(filepath)
if (await isIndexStale(fs, filepath, cache.index)) {
await updateCachedIndexFile(fs, filepath, cache.index);
}
const index = cache.index.map.get(filepath);
result = await closure(index);
if (index._dirty) {
// Acquire a file lock while we're writing the index file
// let fileLock = await Lock(filepath)
const buffer = await index.toObject();
await fs.write(filepath, buffer);
// Update cached stat value
cache.index.stats.set(filepath, await fs.lstat(filepath));
index._dirty = false;
}
});
return result
}
}
function basename(path) {
const last = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'));
if (last > -1) {
path = path.slice(last + 1);
}
return path
}
function dirname(path) {
const last = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'));
if (last === -1) return '.'
if (last === 0) return '/'
return path.slice(0, last)
}
/*::
type Node = {
type: string,
fullpath: string,
basename: string,
metadata: Object, // mode, oid
parent?: Node,
children: Array<Node>
}
*/
function flatFileListToDirectoryStructure(files) {
const inodes = new Map();
const mkdir = function(name) {
if (!inodes.has(name)) {
const dir = {
type: 'tree',
fullpath: name,
basename: basename(name),
metadata: {},
children: [],
};
inodes.set(name, dir);
// This recursively generates any missing parent folders.
// We do it after we've added the inode to the set so that
// we don't recurse infinitely trying to create the root '.' dirname.
dir.parent = mkdir(dirname(name));
if (dir.parent && dir.parent !== dir) dir.parent.children.push(dir);
}
return inodes.get(name)
};
const mkfile = function(name, metadata) {
if (!inodes.has(name)) {
const file = {
type: 'blob',
fullpath: name,
basename: basename(name),
metadata: metadata,
// This recursively generates any missing parent folders.
parent: mkdir(dirname(name)),
children: [],
};
if (file.parent) file.parent.children.push(file);
inodes.set(name, file);
}
return inodes.get(name)
};
mkdir('.');
for (const file of files) {
mkfile(file.path, file);
}
return inodes
}
/**
*
* @param {number} mode
*/
function mode2type(mode) {
// prettier-ignore
switch (mode) {
case 0o040000: return 'tree'
case 0o100644: return 'blob'
case 0o100755: return 'blob'
case 0o120000: return 'blob'
case 0o160000: return 'commit'
}
throw new InternalError(`Unexpected GitTree entry mode: ${mode.toString(8)}`)
}
class GitWalkerIndex {
constructor({ fs, gitdir, cache }) {
this.treePromise = GitIndexManager.acquire(
{ fs, gitdir, cache },
async function(index) {
return flatFileListToDirectoryStructure(index.entries)
}
);
const walker = this;
this.ConstructEntry = class StageEntry {
constructor(fullpath) {
this._fullpath = fullpath;
this._type = false;
this._mode = false;
this._stat = false;
this._oid = false;
}
async type() {
return walker.type(this)
}
async mode() {
return walker.mode(this)
}
async stat() {
return walker.stat(this)
}
async content() {
return walker.content(this)
}
async oid() {
return walker.oid(this)
}
};
}
async readdir(entry) {
const filepath = entry._fullpath;