-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgitLite.js
More file actions
executable file
·412 lines (334 loc) · 11.8 KB
/
gitLite.js
File metadata and controls
executable file
·412 lines (334 loc) · 11.8 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
#!/usr/bin/env node
const path = require("path");
const fs = require("fs/promises");
const crypto = require("crypto");
const { diffLines, diffChars } = require("diff");
const { Command } = require("commander");
const program = new Command();
class GitLite {
constructor() {
this.rootPath = ".";
this.repoPath = path.join(this.rootPath, ".gitLite");
this.objectFolderPath = path.join(this.repoPath, "objects");
this.indexPath = path.join(this.repoPath, "index");
this.headPath = path.join(this.repoPath, "HEAD");
this.ignorePatterns = [];
this.init();
}
async init() {
await fs.mkdir(this.objectFolderPath, { recursive: true });
try {
await fs.access(this.indexPath);
// console.log("GitLite already initialized");
} catch (err) {
await fs.writeFile(this.indexPath, JSON.stringify([]), { flag: "wx" });
await fs.writeFile(this.headPath, "", { flag: "wx" });
console.log("gitLite initialized");
}
}
async readIgnoreFile() {
const ignoreFilePath = path.join(this.rootPath, ".gitignore");
try {
const ignoreContent = await fs.readFile(ignoreFilePath, "utf8");
this.ignorePatterns = ignoreContent.split(/\r?\n/);
} catch (err) {
console.log(".gitignore file not found or error while reading");
}
}
isIgnored(filePath) {
if (!this.ignorePatterns.length) {
return false;
}
for (const pattern of this.ignorePatterns) {
if (pattern.trim() === "") {
continue;
}
const regex = new RegExp(pattern.replace(/\//g, path.sep));
if (regex.test(filePath)) {
return true;
}
}
return false;
}
// reads the index file and return the list of files in the staging area
async getStagedEntries() {
let stagedEntries = [];
try {
const indexContent = await fs.readFile(this.indexPath, "utf-8");
stagedEntries = JSON.parse(indexContent);
} catch (err) {
console.log("Failed to read index file. Assuming empty staging area.");
}
return stagedEntries;
}
hashIt(content) {
return crypto.createHash("sha1").update(content).digest("hex");
}
async getAllFiles(dirPath, arrayOfFiles) {
const files = await fs.readdir(dirPath);
arrayOfFiles = arrayOfFiles || [];
for (const file of files) {
if ((await fs.stat(path.join(dirPath, file))).isDirectory()) {
arrayOfFiles = await this.getAllFiles(
path.join(dirPath, file),
arrayOfFiles
);
} else {
arrayOfFiles.push(
path.relative(this.rootPath, path.join(dirPath, file))
);
}
}
return arrayOfFiles;
}
async add(files) {
console.log("Adding files to staging area...");
await this.readIgnoreFile();
let stagedEntries = await this.getStagedEntries();
if (files.includes(".")) {
files = await this.getAllFiles(this.rootPath);
}
for (const filePath of files) {
const fullPath = path.join(this.rootPath, filePath);
try {
await fs.access(fullPath, fs.constants.F_OK);
} catch {
console.log(`File not found: ${filePath}`);
continue;
}
if (this.isIgnored(filePath)) {
console.log(`Ignoring file: ${filePath} (listed in .gitignore)`);
continue;
}
const fileContent = await fs.readFile(fullPath);
const hash = this.hashIt(fileContent);
// Check if object with this hash already exists
const objectPath = path.join(this.objectFolderPath, hash);
try {
await fs.access(objectPath, fs.constants.F_OK);
console.log(`Object with hash ${hash} already exists.`);
continue;
} catch {
// Object does not exist, proceed with writing the file
}
await fs.writeFile(objectPath, fileContent);
stagedEntries.push({ path: filePath, hash });
console.log(`Added ${filePath} (hash: ${hash}) to staging area.`);
}
const indexContent = JSON.stringify(stagedEntries, null, 2);
await fs.writeFile(this.indexPath, indexContent);
console.log("Done adding files to staging area");
}
async getHead() {
try {
const headContent = await fs.readFile(this.headPath, "utf-8");
return headContent;
} catch (err) {
console.log("Failed to read HEAD file.");
return null;
}
}
async commit(message) {
console.log("Committing changes...");
const stagedEntries = await this.getStagedEntries();
const parentHash = await this.getHead();
if (stagedEntries.length === 0) {
console.log("No changes to commit.");
return;
}
const commitContent = {
message,
changes: stagedEntries,
parent: parentHash,
time: new Date().toISOString(),
};
const commitHash = this.hashIt(JSON.stringify(commitContent));
const commitPath = path.join(this.objectFolderPath, commitHash);
await fs.writeFile(commitPath, JSON.stringify(commitContent, null, 2));
console.log(`Commit hash: ${commitHash}`);
// Clear the staging area and updae HEAD
await fs.writeFile(this.indexPath, JSON.stringify([], null, 2));
await fs.writeFile(this.headPath, commitHash);
console.log("Done committing changes");
}
async log() {
console.log("Fetching commit history...");
let commitHash = await this.getHead();
if (!commitHash) {
console.log("No commits found!!");
return;
}
while (commitHash) {
const commitPath = path.join(this.objectFolderPath, commitHash);
const commitContent = await fs.readFile(commitPath, "utf-8");
const commit = JSON.parse(commitContent);
console.log(`\nCommit: ${commitHash}`);
console.log(`Date: ${commit.time}`);
console.log(`message: ${commit.message}`);
commit.changes.forEach((change) => {
console.log(`\n ${change.path} (${change.hash})`);
});
commitHash = commit.parent;
console.log("--------------------------------------------------- ");
}
console.log("Done fetching commit history");
}
async status() {
console.log("Checking status...");
const stagedEntries = await this.getStagedEntries();
if (stagedEntries.length === 0) {
console.log("No changes in staging area.");
} else {
console.log("Changes to be committed:");
stagedEntries.forEach((entry) => {
console.log(`\t${entry.path}`);
});
}
}
async getCommitHash(commitHash) {
const commitPath = path.join(this.objectFolderPath, commitHash);
const commitContent = await fs.readFile(commitPath, "utf-8");
const commit = JSON.parse(commitContent);
return commit;
}
async diff(commitId) {
const currentCommitData = await this.getCommitHash(commitId);
const currentParentHash = currentCommitData.parent;
if (!currentParentHash) {
console.log("No parent commit found");
return;
}
const parentCommitData = await this.getCommitHash(currentParentHash);
const parentChanges = parentCommitData.changes;
const currentChanges = currentCommitData.changes; // changes is the array of files changed
for (const change of currentChanges) {
const parentChange = parentChanges.find(
(parentChange) => parentChange.path === change.path
);
if (!parentChange) {
console.log(`\nNew file: ${change.path}`);
continue;
}
const parentObjectPath = path.join(
this.objectFolderPath,
parentChange.hash
);
const parentContent = await fs.readFile(parentObjectPath, "utf-8");
const currentObjectPath = path.join(this.objectFolderPath, change.hash);
const currentContent = await fs.readFile(currentObjectPath, "utf-8");
// Using diffLines for line-by-line comparison
const lineDiff = diffLines(
parentContent.toString(),
currentContent.toString()
);
console.log(`\nLine changes in: ${change.path}`);
await lineDiff.forEach(async (part) => {
if (part.added) {
process.stdout.write("\x1b[32m" + "++++++++++" + part.value);
} else if (part.removed) {
process.stdout.write("\x1b[31m" + "----------" + part.value);
} else {
process.stdout.write("\x1b[0m" + part.value);
}
});
// Using diffChars for character-by-character comparison
const charDiff = diffChars(
parentContent.toString(),
currentContent.toString()
);
console.log("\n");
console.log(`\nCharacter-by-character changes in: ${change.path}`);
charDiff.forEach((part) => {
if (part.added) {
process.stdout.write("\x1b[32m" + part.value);
} else if (part.removed) {
process.stdout.write("\x1b[31m" + part.value);
} else {
process.stdout.write("\x1b[0m" + part.value);
}
});
}
console.log("\n");
}
async push(branchName) {
console.log("Pushing to remote…");
// For simplicity, we’ll do a push by saving the current state to a remote repository folder in branchName folder
const remoteRepoPath = path.join(this.repoPath, "remote");
await fs.mkdir(remoteRepoPath, { recursive: true });
const remoteBranchPath = path.join(remoteRepoPath, branchName);
await fs.mkdir(remoteBranchPath, { recursive: true });
const headHash = await this.getHead();
if (!headHash) {
console.log("No commits to push.");
return;
}
// Save commit object to remote branch folder
const commitPath = path.join(this.objectFolderPath, headHash);
const commitContent = await fs.readFile(commitPath, "utf-8");
await fs.writeFile(path.join(remoteBranchPath, headHash), commitContent);
console.log(`Pushed commit ${headHash} to remote branch ${branchName}`);
console.log("Done pushing to remote");
}
async branch(newBranchName) {
console.log(`Creating new branch: ${newBranchName}`);
const headHash = await this.getHead();
if (!headHash) {
console.log("No commits to branch from.");
return;
}
const branchPath = path.join(this.repoPath, "branches");
await fs.mkdir(branchPath, { recursive: true });
const newBranchPath = path.join(branchPath, newBranchName);
await fs.writeFile(newBranchPath, headHash);
console.log(`Created branch ${newBranchName}`);
}
async checkout(branchName) {
console.log(`Switching to branch: ${branchName}`);
const branchPath = path.join(this.repoPath, "branches", branchName);
try {
const branchHead = await fs.readFile(branchPath, "utf-8");
await fs.writeFile(this.headPath, branchHead);
await fs.writeFile(this.branchPath, branchName);
console.log(`Switched to branch ${branchName}`);
} catch {
console.log(`Branch ${branchName} does not exist.`);
}
}
}
// Command line interface
program.command("init").action(async () => {
const gitLite = new GitLite();
});
program.command("add <files...>").action(async (files) => {
const gitLite = new GitLite();
await gitLite.add(files);
});
program.command("commit <message>").action(async (message) => {
const gitLite = new GitLite();
await gitLite.commit(message);
});
program.command("log").action(async () => {
const gitLite = new GitLite();
await gitLite.log();
});
program.command("status").action(async () => {
const gitLite = new GitLite();
await gitLite.status();
});
program.command("diff <commitId>").action(async (commitId) => {
const gitLite = new GitLite();
await gitLite.diff(commitId);
});
program.command("push").action(async (branchName) => {
const gitLite = new GitLite();
await gitLite.push(branchName);
});
program.command("branch").action(async (branchName) => {
const gitLite = new GitLite();
await gitLite.branch(branchName);
});
program.command("checkout").action(async (branchName) => {
const gitLite = new GitLite();
await gitLite.checkout(branchName);
});
program.parse(process.argv);