Repository navigation
Expand file tree
/
Copy pathIndex.py
More file actions
250 lines (195 loc) · 7.92 KB
/
Copy pathIndex.py
File metadata and controls
250 lines (195 loc) · 7.92 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
import struct
import hashlib
import os, pwd, time, datetime
import configparser
from IndexEntry import IndexEntry
from myGit import createblob
from pathlib import Path
from test import tree_to_dictionary_recursive, flat_to_tree, createTreefromDict
ENTRY_FORMAT = "!4sII"
# Meaning of "!4sII":
# ! = Network byte order (Big-Endian)
# 4s = 4-character byte string for the signature string(4 bytes)
# I = Unsigned 32-bit integer for the version number(4 bytes)
# I = Unsigned 32-bit integer for the number of entries(4 bytes)
# Total size = 12 bytes
def createShaBytes(file_name):
with open(file_name, "rb") as f:
content = f.read()
content_size = len(content)
header = f"blob {content_size}\x00".encode("utf-8")
combinedata = header + content
result = hashlib.sha1(combinedata).digest()
return result
class Index:
def __init__(self, index_path="./mgit/index"):
self.index_path = index_path
self.entries = {}
self.commitable = False
if not os.path.exists(index_path):
with open(index_path, "wb") as f:
pass
print(f"Successfully created: {index_path}")
def write(self):
index_file_data = bytearray()
header = struct.pack(ENTRY_FORMAT, b"DIRC", 2, len(self.entries))
index_file_data.extend(header)
for path in sorted(self.entries.keys()):
entry = self.entries[path]
index_file_data.extend(entry.to_bytes())
sha1_checksum = hashlib.sha1(index_file_data).digest()
index_file_data.extend(sha1_checksum)
with open(self.index_path, "wb") as f:
f.write(index_file_data)
def read(self):
if not os.path.exists(self.index_path):
self.entries = {}
print("Index file not existing.")
return
with open(self.index_path, "rb") as f:
data = f.read()
content, checksum = data[:-20], data[-20:]
if content != b"":
assert (
hashlib.sha1(content).digest() == checksum
), "Index file is corrupted. Checksum mismatch."
signature_string, version_number, num_of_entries = struct.unpack(
ENTRY_FORMAT, content[:12]
)
entries_bytes = content
assert signature_string == b"DIRC" # DirCache
assert version_number == 2, "Mygit works on version 2"
offset = 12
for _ in range(num_of_entries):
entry, offset = IndexEntry.from_bytes(entries_bytes, offset)
self.entries[entry.path] = entry
# print(self.entries)
def rm(self, *filenames):
self.read()
for filename in filenames:
if filename in self.entries:
del self.entries[filename]
os.remove(filename)
else:
print(f"fatal: pathspec '{filename}' did not match any files")
self.write()
def add(self, *file_paths):
self.read()
if "." not in file_paths:
for file_path in file_paths:
try:
createblob(file_path)
file_metadata = os.stat(file_path)
ctime = int(file_metadata.st_ctime)
mtime = int(file_metadata.st_mtime)
dev = file_metadata.st_dev
ino = file_metadata.st_ino
mode = file_metadata.st_mode
uid = file_metadata.st_uid
gid = file_metadata.st_gid
file_size = file_metadata.st_size
sha1 = createShaBytes(file_path)
entry = IndexEntry(
ctime,
mtime,
dev,
ino,
mode,
uid,
gid,
file_size,
sha1,
file_path,
)
self.entries[file_path] = entry
except FileNotFoundError:
print(f"The file {file_path} can't be found")
else:
all_files = tree_to_dictionary_recursive()
for file_path, _ in all_files.items():
try:
createblob(file_path)
file_metadata = os.stat(file_path)
ctime = int(file_metadata.st_ctime)
mtime = int(file_metadata.st_mtime)
dev = file_metadata.st_dev
ino = file_metadata.st_ino
mode = file_metadata.st_mode
uid = file_metadata.st_uid
gid = file_metadata.st_gid
file_size = file_metadata.st_size
sha1 = createShaBytes(file_path)
entry = IndexEntry(
ctime,
mtime,
dev,
ino,
mode,
uid,
gid,
file_size,
sha1,
file_path,
)
self.entries[file_path] = entry
except FileNotFoundError:
print(f"The file {file_path} can't be found")
self.commitable = True
self.write()
def status(self):
working_dir_files = tree_to_dictionary_recursive()
untracked = []
unstaged = []
print("status")
for key, value in working_dir_files.items():
if key not in self.entries:
untracked.append(key)
continue
else:
if self.entries[key] != value:
unstaged.append(key)
"""On branch main
Your branch is ahead of 'origin/main' by X commits.
(use "git push" to publish your local commits)
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: Index.py
Untracked files:
(use "git add <file>..." to include in what will be committed).
"""
def commit(self, message):
if not self.commitable:
self.status()
return
else:
self.read()
nested_tree = flat_to_tree(self.entries)
main_tree = createTreefromDict(nested_tree) #just blob sha the results from this algorithm
uid = os.getuid()
user_entry = pwd.getpwuid(uid)
username = user_entry.pw_name
config = configparser.ConfigParser()
config.read('.mgit/config')
username = config['user']['name']
email = config['user']['email']
exact_timestamp = time.time()
unix_timestamp = int(exact_timestamp)
local_time = datetime.now().astimezone()
offset = local_time.strftime("%z")
line1 = f"tree {main_tree} \n"
line2 = f"parent 1a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p7q8r9s0t \n"
line3 = f"author {username} <{email}> {unix_timestamp} {offset} \n"
line4 = f"committer {username} <{email}> {unix_timestamp} {offset} \n"
result = "{} {} {} {} {}".format(line1, line2, line3, line4, message)
print(result)
#print(nested_tree)
# 1. convert entries into to a nested tree
# 2. turn the nested tree into the commit
#print(self.entries)
self.commitable = False
index = Index(".test")
index.write()
index.add(".")
#index.commit()
index.read()