-
Notifications
You must be signed in to change notification settings - Fork 0
/
git-util.js
342 lines (302 loc) · 10.4 KB
/
git-util.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
import * as isogit from 'isomorphic-git';
import fs from 'fs';
export async function gitReset({ dir, fs, ref, branch, hard = false }) {
const re = /^HEAD~([0-9]+)$/;
const m = ref.match(re);
if (m) {
const count = +m[1];
const commits = await isogit.log({ fs, dir, depth: count + 1 });
if (commits.length < count + 1) {
throw new Error('Not enough commits');
}
const commit = commits.pop().oid;
try {
await fs.promises.writeFile(
`${dir}/.git/refs/heads/${branch}`,
commit
);
if (hard) {
// clear the index (if any)
await fs.promises.unlink(`${dir}/.git/index`);
// checkout the branch into the working tree
await isogit.checkout({ dir, fs, ref: branch });
}
} catch (err) {
throw err;
}
} else {
throw new Error(`Wrong ref ${ref}`);
}
}
export function getTreeEntryType(mode) {
let type;
switch (mode) {
case 0o100644:
type = 'blob';
break;
case 0o040000:
type = 'tree';
break;
case 0o160000:
type = 'commit';
break;
default:
type = 'unknown';
}
return type;
}
export function parseIndexFile(path) {
const HEADER_SIZE = 12; // the size of the index file header in bytes
const ENTRY_SIZE = 62; // the size of each index file entry in bytes
const MODE = "100644"; // the mode for the blob objects
const NULL = "\0"; // the null character
const SPACE = " "; // the space character
const NEWLINE = "\n"; // the newline character
// read the index file as a buffer
const indexBuffer = fs.readFileSync(path);
// parse the header of the index file
const header = indexBuffer.subarray(0, HEADER_SIZE);
const signature = header.toString("utf8", 0, 4); // the signature should be "DIRC"
const version = header.readUInt32BE(4); // the version number
const entries = header.readUInt32BE(8); // the number of entries
// parse the entries of the index file
const entriesBuffer = indexBuffer.subarray(HEADER_SIZE, indexBuffer.byteLength);
const entryObjects = []; // an array to store the entry objects
let offset = 0;
while (offset + ENTRY_SIZE < entriesBuffer.byteLength) {
// get the ctime, mtime, dev, ino, mode, uid, gid, size, and sha1 fields
const ctime = entriesBuffer.readUInt32BE(offset);
const mtime = entriesBuffer.readUInt32BE(offset + 8);
const dev = entriesBuffer.readUInt32BE(offset + 16);
const ino = entriesBuffer.readUInt32BE(offset + 20);
const mode = entriesBuffer.readUInt32BE(offset + 24);
const uid = entriesBuffer.readUInt32BE(offset + 28);
const gid = entriesBuffer.readUInt32BE(offset + 32);
const size = entriesBuffer.readUInt32BE(offset + 36);
const sha1 = entriesBuffer.toString("hex", offset + 40, offset + 60);
// get the name
let nameEnd = offset + 62;
while (entriesBuffer[nameEnd] !== 0) {
nameEnd++;
}
const name = entriesBuffer.toString("utf8", offset + 62, nameEnd);
// create an entry object and push it to the array
const entryObject = { mode: mode.toString(8), path: name, oid: sha1, type: getTreeEntryType(mode) };
entryObjects.push(entryObject);
// calculate the next offset
offset = nameEnd + 1; // skip the null character
while (offset % 8 !== 0) { // skip the padding
offset++;
}
}
return entryObjects;
}
export function getTimezoneOffset() {
const offsetMinutes = new Date().getTimezoneOffset();
const offsetHours = Math.abs(Math.floor(offsetMinutes / 60));
const offsetMinutesFormatted = Math.abs(offsetMinutes % 60).toString().padStart(2, '0');
const sign = offsetMinutes > 0 ? '-' : '+';
return `${sign}${offsetHours.toString().padStart(2, '0')}${offsetMinutesFormatted}`;
}
export async function writeStashReflog(dir, stashCommit, message) {
const reflogPath = `${dir}/.git/logs/refs`;
await fs.promises.mkdir(reflogPath, { recursive: true });
const prevStashCommit = '0000000000000000000000000000000000000000';
const timestamp = Math.floor(Date.now() / 1000);
const timezoneOffset = getTimezoneOffset();
const reflogEntry = `${prevStashCommit} ${stashCommit} GliderStash <modesty@stash.com> ${timestamp} ${timezoneOffset}\t${message}\n`;
await fs.promises.appendFile(`${reflogPath}/stash`, reflogEntry);
}
export async function readAllReflogEntries(dir, ref) {
const reflogPath = `${dir}/.git/logs/refs/${ref}`;
const reflogEntries = [];
const reflogBuffer = await fs.promises.readFile(reflogPath);
const reflogString = reflogBuffer.toString('utf8');
const reflogLines = reflogString.split('\n');
for (const line of reflogLines) {
if (line) {
reflogEntries.push(line);
}
}
return reflogEntries;
}
async function writeBlobToFile(fs, dir, filepath, blobOid, addToStage = false) {
console.info(`Applying ${filepath} from ${blobOid} `);
if (!blobOid) {
return;
}
try {
const { blob } = await isogit.readBlob({ fs, dir, oid: blobOid })
const fileContent = Buffer.from(blob).toString('utf8');
await fs.promises.writeFile(`${dir}/${filepath}`, fileContent);
if (addToStage) {
await isogit.add({ fs, dir, filepath });
}
} catch (e) {
console.error(e);
}
}
export async function getAndApplyFileStateChanges(dir, commitHash1, commitHash2, addToStage = false) {
return isogit.walk({
fs,
dir,
trees: [isogit.TREE({ ref: commitHash1 }), isogit.TREE({ ref: commitHash2 })],
map: async function(filepath, [A, B]) {
// ignore directories
if (filepath === '.' || filepath.startsWith('.git')) {
return
}
if ((await A?.type()) === 'tree' || (await B?.type()) === 'tree') {
return
}
// generate ids
const Aoid = await A?.oid()
const Boid = await B?.oid()
// determine modification type
let type = 'equal'
if (Aoid !== Boid) {
type = 'modify'
}
if (Aoid === undefined) {
type = 'add'
}
if (Boid === undefined) {
type = 'remove'
}
if (Aoid === undefined && Boid === undefined) {
console.error('Something weird happened:', A, B);
}
if (type === 'equal') {
return
}
if (type === 'modify' || type === 'add') {
writeBlobToFile(fs, dir, filepath, Aoid, addToStage);
}
else if (type === 'remove') {
await fs.promises.unlink(`${dir}/${filepath}`);
if (addToStage) {
await isogit.remove({ fs, dir, filepath });
}
}
return {
path: filepath,
type,
oid: Aoid,
addToStage
}
},
})
}
export async function getTreeObjArrayStage(dir) {
let hasStagedChanges = false;
const indexTreeObj = await isogit.walk({
fs,
dir,
trees: [isogit.STAGE(), isogit.TREE({ ref: 'HEAD'})],
map: async function(filepath, [A, B]) {
// ignore directories
if (filepath === '.') {
return
}
const Atype = await A?.type();
const Btype = await B?.type();
if (Atype === 'special' || Btype === 'special') {
return
}
if (Atype === 'commit' || Btype === 'commit') {
return
}
// generate ids
let Aoid = await A?.oid()
let Boid = await B?.oid()
// determine modification type
let type = 'equal'
if (Aoid !== Boid) {
type = 'modify'
}
if (Aoid === undefined) {
type = 'add'
}
if (Boid === undefined) {
type = 'remove'
}
if (Aoid === undefined && Boid === undefined) {
console.error('Something weird happened:', A, B);
return;
}
if (Aoid === undefined || type === 'remove') {
return;
}
if (!hasStagedChanges && type !== 'equal') {
hasStagedChanges = true;
}
const mode = await A?.mode()
return {
mode: mode.toString(8),
path: filepath,
oid: Aoid,
type: Atype,
change: type
}
},
})
return hasStagedChanges ? indexTreeObj : [];
}
export async function getTreeObjArrayforWorkingDir(dir, workDirCompareBase) {
let hasWorkingChanges = false;
const workingTreeObjects = await isogit.walk({
fs,
dir,
trees: [isogit.WORKDIR(), workDirCompareBase],
map: async function(filepath, [A, B]) {
// ignore directories
if (filepath === '.' || filepath.startsWith('.git') ) {
return
}
const Atype = await A?.type();
const Btype = await B?.type();
if (Atype === 'special' || Btype === 'special') {
return
}
if (Atype === 'commit' || Btype === 'commit') {
return
}
// generate ids
let Aoid = await A?.oid()
let Boid = await B?.oid()
// determine modification type
let type = 'equal'
if (Aoid !== Boid) {
type = 'modify'
}
if (Aoid === undefined) {
type = 'add'
}
if (Boid === undefined) {
type = 'untracked'
}
if (Aoid === undefined && Boid === undefined) {
console.error('Something weird happened:', A, B);
return;
}
if (type === 'untracked') {
return;
}
if (type !== 'equal') { //needs to create the Blob object and add to the tree
const fileBuffer = await fs.promises.readFile(`${dir}/${filepath}`);
const uint8Blob = new Uint8Array(fileBuffer);
Aoid = await isogit.writeBlob({ fs, dir, blob: uint8Blob });
hasWorkingChanges = true;
}
const mode = await A?.mode()
return {
mode: mode.toString(8),
path: filepath,
oid: Aoid,
type: Atype,
change: type
}
},
})
return hasWorkingChanges ? workingTreeObjects : [];
}