-
Notifications
You must be signed in to change notification settings - Fork 0
/
tico
executable file
·471 lines (387 loc) · 18 KB
/
tico
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
#!/usr/bin/env python3
import os
import sys
import shutil
import hashlib
import json
import datetime
def print_help():
print("Tico - A Version Control System")
print("Usage:")
print(" tico init - Initialize a new Tico repository")
print(" tico add <file> - Add a file to the index")
print(" tico commit -m <message> - Commit changes with a message")
print(" tico rmadd <file> - remove a file from the index")
print(" tico rmcommit - remove last commit")
print(" tico log - Display commit log")
print(" tico checkout <commit> - Checkout a specific commit")
print(" tico help - to see this usage help")
print(" tico status - to see status")
print(" tico user show - to see present user (default username is naveen)")
print(" tico user set <username> - to change user")
print(" tico push <path> - to push your file to another folder")
print()
print("Created by - Naveen Pal")
print()
def main():
if len(sys.argv) < 2:
print_help()
sys.exit(1)
command = sys.argv[1]
if command == "init":
svc.init()
print(f"Initialized empty Tico repository in {os.getcwd()}")
elif command == "add":
if len(sys.argv) < 3:
print("Error: Please provide a file to add.")
sys.exit(1)
elif not os.path.exists(sys.argv[2]):
print(f"Error: Your filename({sys.argv[2]}) does not exist")
sys.exit(1)
file_to_add = sys.argv[2]
svc.add(file_to_add)
print(f"Added {file_to_add}, Successfully.")
elif command == "commit":
if "-m" not in sys.argv:
print("Error: Please provide a commit message using -m.")
sys.exit(1)
message_index = sys.argv.index("-m") + 1
message = sys.argv[message_index]
author = svc.current_user()
svc.commit(message, author )
print("Committed Successfully")
elif command == "rmadd":
if len(sys.argv) < 3:
print("Error: Please provide file to remove from add.")
sys.exit(1)
svc.rmadd(sys.argv[2])
print(f"{sys.argv[2]} removed successfully")
elif command == "rmcommit":
svc.rmcommit()
elif command == "log":
svc.log()
elif command == "checkout":
if len(sys.argv) < 3:
print("Error: Please provide a commit hash to checkout.")
sys.exit(1)
elif not os.path.exists(os.path.join(os.path.join(".tico","objects"),sys.argv[2])):
print("Error: Please recheck your Hash")
sys.exit(1)
ans=input("Are you sure to checkout this will replace your files? (y- to replace file, n- to cancel checkout): ")
if ans=='yes' or ans=="y":
commit_to_checkout = sys.argv[2]
svc.checkout(commit_to_checkout)
print(f"Checked out commit: {commit_to_checkout}")
elif ans=="no" or ans=="n":
sys.exit()
else:
print(f"Invalid arguement: {ans}")
sys.exit(1)
elif command == "status":
current_branch = "main" # Use 'main' instead of 'master'
head_commit = svc._get_head_commit(current_branch)
index_changes = svc.get_added_files()
working_directory_changes = svc.get_working_directory_changes()
print("On branch", current_branch)
if not svc.file_status("all"):
print("\nnothing to commit (create/copy files and use 'tico add' to track)")
if not index_changes=={}:
print("\nChanges to be committed:")
for file_path, obj_hash in index_changes.items():
print(f" {file_path}: {obj_hash}")
if not working_directory_changes["untracked"]==[]:
print("\nUntracked files:")
for file_path in working_directory_changes["untracked"]:
print(f" {file_path}")
if not working_directory_changes["modified"] == {}:
print("\nChanges not staged for commit:")
for file_path, obj_hash in working_directory_changes["modified"].items():
print(f" {file_path}: {obj_hash}")
print()
# print("\nNo changes added to commit (use 'tico add <file>' and 'tico commit')")
elif command == "help":
print_help()
elif command == "user":
if sys.argv[2] == "set":
svc._user_change(sys.argv[3])
print(f"\nYour username is {svc.current_user()}")
elif sys.argv[2] == "show":
print(f"\nYour username is {svc.current_user()}")
elif command == "push":
svc.push(sys.argv[2])
print(f"Successfully pushed all files to {sys.argv[2]}")
else:
print(f"Error: Unknown command '{command}'.")
print_help()
sys.exit(1)
class SimpleVersionControl:
def init(self, repo_path=".tico"):
self.repo_path = repo_path
self.index_file = os.path.join(repo_path, "index.json")
self.added_file = os.path.join(repo_path, "added.json")
self.modified_file = os.path.join(repo_path, "modified.json")
self.objects_path = os.path.join(repo_path, "objects")
self.branches_path = os.path.join(repo_path, "branches")
self.user_file = os.path.join(repo_path, "users.txt")
self._initialize_repo()
def _initialize_repo(self):
# Create the repository directory if it doesn't exist
if not os.path.exists(self.repo_path):
os.makedirs(self.repo_path)
# Create the objects directory for storing file content
if not os.path.exists(self.objects_path):
self.objects_path = os.path.join(".tico", "objects")
os.makedirs(self.objects_path)
# Create the branches directory
if not os.path.exists(self.branches_path):
os.makedirs(self.branches_path)
# Initialize a default branch
self._create_branch("main")
# Initialize the index, added and modified file
for file in [self.index_file,self.added_file,self.modified_file]:
if not os.path.exists(file):
with open(file, "w") as index:
json.dump({}, index)
# Initialize the user file
if not os.path.exists(self.user_file):
user_name = input("please set your username: ")
if user_name == "":
user_name = "Unknown"
date_time = (datetime.datetime.now()).strftime("%Y-%m-%d %H:%M:%S")
with open(self.user_file, "w") as user_data:
user_data.write(f"\n {date_time} {user_name}")
def _user_change(self, user_name):
self.user_file = os.path.join(".tico", "users.txt")
with open(self.user_file, "a") as user:
date_time = (datetime.datetime.now()).strftime("%Y-%m-%d %H:%M:%S")
userdata=date_time+" "+user_name
user.write("\n"+userdata)
def _create_branch(self, branch_name):
self.branches_path = os.path.join(".tico", "branches")
branch_path = os.path.join(self.branches_path, branch_name)
if not os.path.exists(branch_path):
os.makedirs(branch_path)
# Create a branch file to store the latest commit hash
branch_file = os.path.join(branch_path, "HEAD")
if not os.path.exists(branch_file):
with open(branch_file, "w") as head_file:
head_file.write("")
def _get_head_commit(self, branch_name):
self.branches_path = os.path.join(".tico", "branches")
branch_path = os.path.join(self.branches_path, branch_name)
branch_file = os.path.join(branch_path, "HEAD")
with open(branch_file, "r") as head_file:
return head_file.read().strip()
def _update_head_commit(self, branch_name, commit_hash):
self.branches_path = os.path.join(".tico", "branches")
branch_path = os.path.join(self.branches_path, branch_name)
branch_file = os.path.join(branch_path, "HEAD")
with open(branch_file, "a") as head_file:
head_file.write(commit_hash+"\n")
def _get_object_path(self, obj_hash):
self.objects_path = os.path.join(".tico", "objects")
return os.path.join(self.objects_path, obj_hash)
def _get_object_hash(self, content):
return hashlib.sha1(content.encode("utf-8")).hexdigest()
def _save_object(self, content):
obj_hash = self._get_object_hash(content)
obj_path = self._get_object_path(obj_hash)
if not os.path.exists(obj_path):
with open(obj_path, "w") as obj_file:
obj_file.write(content)
return obj_hash
def _read_object(self, obj_hash):
obj_path = self._get_object_path(obj_hash)
with open(obj_path, "r") as obj_file:
return obj_file.read()
def add(self, file_path):
with open(file_path, "r") as file:
content = file.read()
obj_hash = self._save_object(content)
files=["index.json","added.json"]
for file in files:
svc._update_json(file_path,obj_hash,file,"a")
def _update_json(self,file_path,obj_hash,json_file,m):
json_file = os.path.join(".tico", json_file)
if not m=="w":
with open(json_file, "r") as index_file:
index = json.load(index_file)
else:
index={}
index[file_path] = obj_hash
with open(json_file, "w") as index_file:
json.dump(index, index_file)
def commit(self, message, author):
self.index_file = os.path.join(".tico", "index.json")
self.added_file = os.path.join(".tico", "added.json")
with open(self.index_file, "r") as index_file:
index = json.load(index_file)
with open(self.added_file, "r") as added_file:
added = json.load(added_file)
if not added:
print("Nothing to commit.")
exit(1)
commit_data = {
"message": message,
"author": author,
"timestamp": str(datetime.datetime.now()),
"all": index,
"changes": added,
}
commit_content = json.dumps(commit_data, sort_keys=True)
commit_hash = self._save_object(commit_content)
with open(self.added_file, "w") as added_file:
added_file.write("{}")
current_branch = "main" # For simplicity, always commit to the main branch
head_commit = self._get_head_commit(current_branch)
# Update the branch's HEAD to point to the new commit
self._update_head_commit(current_branch, commit_hash)
print(f"Commit hash: {commit_hash}")
def rmadd(self,rm_file):
self.added_file = os.path.join(".tico", "added.json")
with open(self.added_file, "r") as file:
data =file.read().strip()
if sys.argv[2] not in data:
print("Error: Please recheck your filename")
data=json.loads(data)
file_hash=data[rm_file]
svc.remove_object_file(file_hash)
def rmcommit(self):
self.objects_path = os.path.join(".tico", "objects")
self.branches_path = os.path.join(".tico", "branches")
branch_path = os.path.join(self.branches_path, "main")
head_file_path = os.path.join(branch_path, "HEAD")
# Read the contents of the HEAD file
with open(head_file_path, "r") as head_file:
lines = head_file.readlines()
# Remove the last line
commit_hash=lines[-1]
commit_hash=commit_hash[:-1]
lines = lines[:-1]
# Write the modified content back to the HEAD file
with open(head_file_path, "w") as head_file:
head_file.writelines(lines)
commit_content = self._read_object(commit_hash).strip()
commit_data = json.loads(commit_content)
for file_path, obj_hash in commit_data["changes"].items():
svc.remove_object_file(obj_hash)
svc.remove_object_file(commit_hash)
print(f"Last Commit removed successfully (Removed Commit Hash:{commit_hash})")
def remove_object_file(self,file_name):
self.objects_path = os.path.join(".tico", "objects")
path=os.path.join(self.objects_path,file_name)
os.remove(path)
def log(self):
current_branch = "main" # For simplicity, always show log for the main branch
head_all = self._get_head_commit(current_branch).split("\n")
if head_all==[""]:
print("Nothing to show in log")
sys.exit()
for head_commit in head_all:
commit_content = self._read_object(head_commit).strip()
commit_data = json.loads(commit_content)
print(f"Commit: {head_commit}")
print(f"Author: {commit_data['author']}")
print(f"Timestamp: {commit_data['timestamp']}")
print(f"Message: {commit_data['message']}")
print("Added / Modifiled Files:")
for file_path, obj_hash in commit_data["changes"].items():
print(f" {file_path}: {obj_hash}")
print("All files:")
for file_path, obj_hash in commit_data["all"].items():
print(f" {file_path}: {obj_hash}")
print()
head_commit = commit_data.get("parent")
def checkout(self, commit_hash):
# For simplicity, checkout only works for the current branch (main)
current_branch = "main"
self._update_head_commit(current_branch, commit_hash)
# Restore files from the given commit
commit_content = self._read_object(commit_hash)
commit_data = json.loads(commit_content)
svc._update_json("","","index.json","w")
for file_path, obj_hash in commit_data["all"].items():
svc._update_json(file_path,obj_hash,"index.json","a")
obj_content = self._read_object(obj_hash)
with open(file_path, "w") as file:
file.write(obj_content)
def get_index_changes(self):
self.index_file = os.path.join(".tico", "index.json")
with open(self.index_file, "r") as index_file:
return json.load(index_file)
def get_added_files(self):
self.added_file = os.path.join(".tico", "added.json")
with open(self.added_file, "r") as added_file:
return json.load(added_file)
def get_working_directory_changes(self):
working_directory_changes = {"untracked": [], "modified": {}}
for file_path in os.listdir(".") :
if file_path != ".tico":
if file_path not in self.get_index_changes():
working_directory_changes["untracked"].append(file_path)
elif self.file_changed(file_path):
obj_hash = self._get_object_hash(open(file_path, "r").read())
working_directory_changes["modified"][file_path] = obj_hash
svc.add(file_path)
return working_directory_changes
def file_changed(self, file_path):
index_hash = self.get_index_changes().get(file_path)
with open(file_path, "r") as file:
current_hash = self._get_object_hash(file.read())
return index_hash != current_hash
def current_user(self):
self.user_file = os.path.join(".tico", "users.txt")
with open(self.user_file, "r") as user_data:
cuser=user_data.readlines()[-1].strip().split()[-1]
return cuser
def file_status(self,m):
current_branch = "main" # Use 'main' instead of 'master'
head_commit = svc._get_head_commit(current_branch)
index_changes = svc.get_added_files()
working_directory_changes = svc.get_working_directory_changes()
if m=="all":
return index_changes != {} or working_directory_changes["untracked"] != [] or working_directory_changes["modified"] != {}
elif m=="added":
return index_changes != {}
elif m=="untracked":
return working_directory_changes["untracked"] != []
elif m=="modified":
return working_directory_changes["modified"] != {}
def delete_files_except_svc(self):
# Get the current directory
current_directory = os.getcwd()
# List all files and folders in the current directory
files_and_folders = os.listdir(current_directory)
# Delete all files and folders except for .tico
for item in files_and_folders:
if item != ".tico":
item_path = os.path.join(current_directory, item)
if os.path.isfile(item_path):
# Delete file
os.remove(item_path)
elif os.path.isdir(item_path):
# Delete folder and its contents
shutil.rmtree(item_path)
def push(self,destination_directory):
# Get the current directory
current_directory = os.getcwd()
# Create the destination directory
os.makedirs(destination_directory, exist_ok=True)
# List all files and folders in the current directory
files_and_folders = os.listdir(current_directory)
# Copy all files except .tico to the destination directory
for item in files_and_folders:
if item != ".tico":
item_path = os.path.join(current_directory, item)
destination_item_path = os.path.join(destination_directory, item)
if os.path.isfile(item_path):
# Copy file
shutil.copy2(item_path, destination_item_path)
print(f"Copied file: {item} to {destination_directory}")
elif os.path.isdir(item_path):
# Copy folder and its contents
shutil.copytree(item_path, destination_item_path)
print(f"Copied folder: {item} to {destination_directory}")
if __name__ == "__main__":
svc = SimpleVersionControl()
main()