-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
356 lines (293 loc) · 15.1 KB
/
Copy pathProgram.cs
File metadata and controls
356 lines (293 loc) · 15.1 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
using System;
using System.IO;
using System.Text;
using GitInternals.Utils;
using GitInternals.Objects;
using System.Collections.Generic;
namespace GitInternals
{
class Program
{
//Path to your git repository
static string GitRepoPath = @"\\wsl.localhost\Ubuntu-22.04\home\dev\workspace\github.com\lain-the-coder\git-internals-deep-dive\.git";
static void Main(string[] args)
{
if (args.Length == 0)
{
showUsage();
return;
}
string command = args[0];
switch (command)
{
case "read-blob":
ReadBlob(args);
break;
case "hash-object":
HashObject(args);
break;
case "read-tree":
ReadTree(args);
break;
case "read-commit":
ReadCommit(args);
break;
case "log":
Log(args);
break;
default:
Console.WriteLine($"Unknown command: {command}");
showUsage();
break;
}
static void showUsage()
{
Console.WriteLine("GitInternals - A Git object reader");
Console.WriteLine();
Console.WriteLine("Commands:");
Console.WriteLine(" read-blob <hash> Read and display a blob object");
Console.WriteLine(" hash-object <file> Calculate SHA-1 hash of a file");
Console.WriteLine(" read-tree <hash> Read and display a tree object");
Console.WriteLine(" read-commit <hash> Read and display a commit object");
Console.WriteLine(" log <branch> Walk commit history");
Console.WriteLine($"Git Repository: {GitRepoPath}");
}
static void ReadBlob(string[] args)
{
if (args.Length < 2)
{
Console.WriteLine("Usage: read-blob <hash>");
return;
}
string hash = args[1];
Console.WriteLine($"Reading blob: {hash}");
//Building file path from Hash
string folder = hash.Substring(0, 2);
string fileName = hash.Substring(2);
string objectPath = Path.Combine(GitRepoPath, "objects", folder, fileName);
Console.WriteLine($"Object path: {objectPath}");
//Read file from path into byte array
byte[] compressedData = File.ReadAllBytes(objectPath);
//Decompress data
byte[] decompressedData = ZlibHelper.Decompress(compressedData);
//Convert bytes to string
string fullContent = Encoding.UTF8.GetString(decompressedData);
//Parse header and content(split at null byte \0)
int nullByteSeparatorIndex = fullContent.IndexOf('\0');
string header = fullContent.Substring(0, nullByteSeparatorIndex);
string content = fullContent.Substring(nullByteSeparatorIndex + 1);
//Parse/split header details by splitting blob and size
string[] headerDetails = header.Split(' ');
string type = headerDetails[0];
int size = int.Parse(headerDetails[1]);
//Display object details and content
Console.WriteLine();
Console.WriteLine($"Object Type: {type}");
Console.WriteLine($"Size: {size} bytes");
Console.WriteLine();
Console.WriteLine("Content:");
Console.WriteLine("─────────────────────────────────────────");
Console.WriteLine(content);
Console.WriteLine("─────────────────────────────────────────");
}
static void HashObject(string[] args)
{
if (args.Length < 2)
{
Console.WriteLine("Usage: hash-object <file>");
return;
}
//Get file path
string filePath = args[1];
//Read file into byte array
byte[] contentBytes = File.ReadAllBytes(filePath);
//Create Git blob header
string header = $"blob {contentBytes.Length}\0";
//Convert header to bytes
byte[] headerBytes = Encoding.UTF8.GetBytes(header);
//Combine header and content bytes
//Allocate new byte array to hold header and content
byte[] data = new byte[headerBytes.Length + contentBytes.Length];
//Copy header bytes to new array
Array.Copy(headerBytes, 0, data, 0, headerBytes.Length);
//Copy content bytes to new array after header
Array.Copy(contentBytes, 0, data, headerBytes.Length, contentBytes.Length);
//Calculate SHA-1 hash of combined data
string hash = HashHelper.ComputeSHA1(data);
// Display result
Console.WriteLine($"File: {filePath}");
Console.WriteLine($"SHA1: {hash}");
}
static void ReadTree(string[] args)
{
if (args.Length < 2)
{
Console.WriteLine("Usage: read-tree <hash>");
return;
}
string hash = args[1];
Console.WriteLine($"Reading tree: {hash}");
//Building file path from Hash
string folder = hash.Substring(0, 2);
string fileName = hash.Substring(2);
string objectPath = Path.Combine(GitRepoPath, "objects", folder, fileName);
Console.WriteLine($"Object path: {objectPath}");
//Read and decompress data
byte[] compressedData = File.ReadAllBytes(objectPath);
byte[] decompressedData = ZlibHelper.Decompress(compressedData);
Console.WriteLine("Decompressed successfully.");
//Skip header - tree <size>\0
int position = 0;
while (decompressedData[position] != 0)
{
position++;
}
position++; // Move past null byte
Console.WriteLine($"Header skipped. Starting at position: {position}");
//Empty List to store entries
var entries = new List<TreeEntry>();
Console.WriteLine("Total Decompressed bytes: " + decompressedData.Length);
Console.WriteLine($"Total bytes to parse(actual data entry without header): {decompressedData.Length - position}");
//Loop through decompressed data until we reach the end, parsing each entry
while (position < decompressedData.Length)
{
//Read Mode
int modestart = position; //modestart = 9
while (decompressedData[position] != ' ')
{
position++; // Move to next byte until we find a space, stops at null byte; since 1 0 0 6 4 4 a p p . j s ; space between mode and filename
}
string mode = Encoding.UTF8.GetString(decompressedData, modestart, position - modestart); //Gets the 6 bytes [49, 48, 48, 48, 48, 48]; converts to string "100000" which is the mode(blob)
position++; // Move past space
//Read Filename
int namestart = position; //namestart = 16
while (decompressedData[position] != 0)
{
position++; // Move to next byte until we find a null byte since filename ends with null byte; since app.js\0
}
string name = Encoding.UTF8.GetString(decompressedData, namestart, position - namestart); //Gets the 6 bytes [97, 112, 112, 46, 106, 115]; converts to string "app.js" which is the filename
position++; // Move past null byte
//Read Hash
byte[] hashBytes = new byte[20]; //SHA-1 hash is 20 bytes in binary not hex; this will copy 20 bytes starting from position 23 to hashBytes array
Array.Copy(decompressedData, position, hashBytes, 0, 20);
position += 20; // Move position past the hash bytes
string hexHash = BitConverter.ToString(hashBytes).Replace("-", "").ToLower(); //Convert hashBytes to hex string
//Determine type of object
string type = mode == "040000" ? "tree" : "blob"; //040000 is tree, 100644 is blob
//Create TreeEntry object
entries.Add(new TreeEntry
{
Mode = mode,
Name = name,
Hash = hexHash,
Type = type
});
}
Console.WriteLine($"Parsed {entries.Count} entries!");
Console.WriteLine();
Console.WriteLine("Entries:");
Console.WriteLine("─────────────────────────────────────────────────────────────────────────────");
foreach (var entry in entries)
{
Console.WriteLine($"{entry.Mode} {entry.Type,-4} {entry.Hash} {entry.Name}");
}
Console.WriteLine("─────────────────────────────────────────────────────────────────────────────");
}
static void ReadCommit(string[] args)
{
//Same as ReadBlob
if (args.Length < 2)
{
Console.WriteLine("Usage: read-commit <hash>");
return;
}
string hash = args[1];
string folder = hash.Substring(0, 2);
string filename = hash.Substring(2);
string filepath = Path.Combine(GitRepoPath, "objects", folder, filename);
Console.WriteLine($"Commit path: {filepath}");
byte[] commitByte = File.ReadAllBytes(filepath);
byte[] commitDecompressed = ZlibHelper.Decompress(commitByte);
string fullContent = Encoding.UTF8.GetString(commitDecompressed);
int nullIndex = fullContent.IndexOf('\0');
string header = fullContent.Substring(0, nullIndex);
string content = fullContent.Substring(nullIndex + 1);
string[] headers = header.Split(' ');
string type = headers[0];
string size = headers[1];
//Display object details and content
Console.WriteLine();
Console.WriteLine($"Object Type: {type}");
Console.WriteLine($"Size: {size} bytes");
Console.WriteLine();
Console.WriteLine("Content:");
Console.WriteLine("─────────────────────────────────────────");
Console.WriteLine(content);
Console.WriteLine("─────────────────────────────────────────");
}
static void Log(string[] args)
{
if (args.Length < 2)
{
Console.WriteLine("Usage: log <branch>");
return;
}
string branchName = args[1];
//Build path to branch file
string branchPath = Path.Combine(GitRepoPath, "refs", "heads", branchName);
//Check if branch file exists
if (!File.Exists(branchPath))
{
Console.WriteLine($"Branch '{branchName}' not found at path: {branchPath}");
return;
}
//Read the latest commit hash from the branch file
string? latestCommitHash = File.ReadAllText(branchPath).Trim();
Console.WriteLine($"Branch: {branchName}");
Console.WriteLine($"Latest commit: {latestCommitHash}");
Console.WriteLine();
int commitCount = 0;
while (latestCommitHash != null)
{
commitCount++;
//Build path to commit object
string folder = latestCommitHash.Substring(0, 2);
string filename = latestCommitHash.Substring(2);
string commitPath = Path.Combine(GitRepoPath, "objects", folder, filename);
//Read and decompress commit object
byte[] commitBytes = File.ReadAllBytes(commitPath);
byte[] commitDecompressed = ZlibHelper.Decompress(commitBytes);
//Convert to string
string fullContent = Encoding.UTF8.GetString(commitDecompressed);
//Skip Header
int nullIndex = fullContent.IndexOf('\0');
string content = fullContent.Substring(nullIndex + 1);
string[] lines = content.Split('\n');
string message = "";
string? parentHash = null;
//Find Parent and Message
for (int i = 1; i < lines.Length; i++)
{
if (lines[i].StartsWith("parent "))
{
parentHash = lines[i].Replace("parent ", "");
}
else if (lines[i] == "")
{
//Empty line indicates start of commit message
message = string.Join("\n", lines, i + 1, lines.Length - (i + 1));
break;
}
}
// Display commit
Console.WriteLine($"commit {latestCommitHash}");
Console.WriteLine($" {message}");
Console.WriteLine();
// Move to parent (walk backwards!)
latestCommitHash = parentHash;
}
Console.WriteLine($"Total commits: {commitCount}");
}
}
}
}