-
Notifications
You must be signed in to change notification settings - Fork 35
/
workingIndex.js
110 lines (88 loc) · 2.45 KB
/
workingIndex.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
var Immutable = require('immutable');
var Concentrate = require('concentrate');
var IndexEntry = require('./indexEntry');
var SIGNATURE = 'DIRC';
var WorkingIndex = Immutable.Record({
version: Number(),
entries: Immutable.OrderedMap()
});
WorkingIndex.prototype.getEntries = function() {
return this.get('entries');
};
WorkingIndex.prototype.getVersion = function() {
return this.get('version');
};
/**
* Output as a buffer
* @return {Buffer}
*/
WorkingIndex.prototype.toBuffer = function() {
var entries = this.getEntries();
var version = this.getVersion();
var output = Concentrate()
.string(SIGNATURE)
.uint32be(version)
.uint32be(entries.size);
entries.each(function(entry) {
output.buffer(entry.toBuffer(version));
});
return output.result;
};
/**
* Parse a working inex from a Buffer
*
* @param {Buffer} content
* @return {WorkingIndex}
*/
WorkingIndex.createFromBuffer = function(content) {
var version, nEntries;
var entriesBuf;
var entries = Immutable.OrderedMap();
var header = content.slice(0, 12);
// Validate header signature
var signature = header.slice(0, 4);
if (signature.toString() !== SIGNATURE) {
throw new Error('Invalid working index header');
}
// Read the version
version = header.readInt32BE(4);
// Read the number of entries
nEntries = header.readInt32BE(8);
entriesBuf = content.slice(12);
for (var i = 0; i < (nEntries - 1); i++) {
var result = IndexEntry.createFromBuffer(entriesBuf, version);
entriesBuf = result.buffer;
entries = entries.set(
result.entry.getPath(),
result.entry
);
}
return new WorkingIndex({
version: version,
entries: entries
});
};
/**
* Read a WorkingIndex from a repository using its filename
*
* @param {Repository} repo
* @paran {String} refPath
* @return {Promise<WorkingIndex>}
*/
WorkingIndex.readFromRepo = function(repo, fileName) {
fileName = fileName || 'index';
return repo.readGitFile(fileName)
.then(WorkingIndex.createFromBuffer);
};
/**
* Write a working index in a repository.
*
* @param {Repository} repo
* @param {WorkingIndex} obj
* @return {Promise}
*/
WorkingIndex.writeToRepo = function(repo, workingIndex, fileName) {
fileName = fileName || 'index';
return repo.writeGitFile(fileName, workingIndex.toBuffer());
};
module.exports = WorkingIndex;