-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscripts.py
266 lines (211 loc) · 8.49 KB
/
scripts.py
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
import json
import os
import sys
import time
from termcolor import colored
def setup_logs():
os.makedirs("logs", exist_ok=True)
os.makedirs("logs/states", exist_ok=True)
os.makedirs("logs/commits", exist_ok=True)
with open("logs/tracked_files.json", "w") as f:
json.dump({'files': []}, f)
print("Initialized empty GitOsLab repository ")
def detect_file_extensions_in_dir(base_path):
extensions = set()
for root, dirs, files in os.walk(base_path):
if 'logs' in dirs:
dirs.remove('logs')
for file_name in files:
_, ext = os.path.splitext(file_name)
if ext:
extensions.add(ext)
return list(extensions)
def process_file_type(file_extension, base_path):
log_file_name = f"logs/log_{file_extension[1:]}.txt"
with open('logs/tracked_files.json', "r") as f:
tracked_files = json.load(f)['files']
try:
with open(f'logs/states/{file_extension[1:]}.json', "r+") as states_file:
previous_state = json.load(states_file)
except FileNotFoundError:
previous_state = {'status': {}, 'new': {}, 'modified': {}}
with open(f'logs/states/{file_extension[1:]}.json', "w") as states_file:
json.dump(previous_state, states_file)
current_state = {}
file_count = 0
changes = []
new_files = []
modified_files = []
for root, dirs, files in os.walk(base_path):
if 'logs' in dirs:
dirs.remove('logs')
for file_name in files:
if file_name.endswith(file_extension):
file_path = os.path.join(root, file_name)
file_count += 1
last_modified = os.path.getmtime(file_path)
current_state[file_path] = last_modified
for file, mtime in current_state.items():
if file not in previous_state['status'] or previous_state['status'][file] != mtime:
if file not in previous_state['status']:
status = "New"
tracked_files.append(file)
print(file)
else:
status = "Modified"
new_files.append(file) if status == "New" else modified_files.append(file)
changes.append(f"{file} - {status}")
with open(log_file_name, 'a') as log_file:
message = f"[{time.ctime()}] {file_extension} files: {file_count}, Changes: {changes}\n"
log_file.write(message)
with open(f"logs/states/{file_extension[1:]}.json", 'w+') as stats_file:
json.dump({'status': current_state, 'new': new_files, 'modified': modified_files}, stats_file)
with open(f"logs/tracked_files.json", 'w') as f:
json.dump({'files': tracked_files}, f)
def add_files(base_path):
file_extensions = detect_file_extensions_in_dir(base_path)
for ext in file_extensions:
pid = os.fork()
if pid == 0:
print(f"Child Process PID: {os.getpid()} for extension {ext}")
process_file_type(ext, base_path)
os._exit(0)
else:
print(f"Parent Process PID: {os.getpid()} waiting for child {pid}")
os.wait()
print('Add files Successfully...')
def commit_changes(commit_message):
timestamp = time.time()
commit_file_path = f"logs/commits/{int(timestamp)}.json"
commit_data = {
'message': commit_message,
'timestamp': int(timestamp),
'changes': {
'added': {},
'modified': {},
}
}
for ext in os.listdir("logs/states/"):
if ext.endswith(".json"):
state_file_path = f"logs/states/{ext}"
with open(state_file_path, 'r') as state_file:
state = json.load(state_file)
for new_file in state['new']:
try:
with open(new_file, 'r') as f:
content = f.read()
commit_data['changes']['added'][new_file] = content
except (FileNotFoundError, PermissionError):
print(f"Could not read new file: {new_file}")
for modified_file in state['modified']:
try:
with open(modified_file, 'r') as f:
content = f.read()
commit_data['changes']['modified'][modified_file] = content
except (FileNotFoundError, PermissionError):
print(f"Could not read modified file: {modified_file}")
state['new'] = []
state['modified'] = []
with open(state_file_path, 'w') as state_file:
json.dump(state, state_file)
with open(commit_file_path, 'w') as commit_file:
json.dump(commit_data, commit_file, indent=4)
print(f"Committed changes with message: '{commit_message}'")
def revert_commit(commit_timestamp):
commit_file_path = f"logs/commits/{commit_timestamp}.json"
if not os.path.exists(commit_file_path):
print(f"Commit with timestamp {commit_timestamp} not found!")
return
with open(commit_file_path, 'r') as commit_file:
commit_data = json.load(commit_file)
for file_path, content in commit_data['changes']['added'].items():
try:
with open(file_path, 'w') as f:
f.write(content)
print(f"Restored added file: {file_path}")
except Exception as e:
print(f"Failed to restore added file {file_path}: {e}")
for file_path, content in commit_data['changes']['modified'].items():
try:
with open(file_path, 'w') as f:
f.write(content)
print(f"Restored modified file: {file_path}")
except Exception as e:
print(f"Failed to restore modified file {file_path}: {e}")
print(f"Reverted to commit {commit_timestamp}")
def monitor_process():
new_files = []
modified_files = []
untracked_files = []
for file_name in os.listdir("logs/states/"):
if file_name.endswith(".json"):
file_path = f"logs/states/{file_name}"
with open(file_path, 'r') as state_file:
state = json.load(state_file)
new_files.extend(state.get("new", []))
modified_files.extend(state.get("modified", []))
with open('logs/tracked_files.json', 'r') as f:
tracked_files = json.load(f)['files']
for root, dirs, files in os.walk('.'):
if 'logs' in dirs:
dirs.remove('logs')
for file in files:
file_path = os.path.join(root, file)
if file_path not in tracked_files:
untracked_files.append(file_path)
if new_files:
print(colored("New files:", "green", attrs=["bold"]))
for file in new_files:
print(colored(f" - {file}", "light_green"))
else:
print(colored("No new files detected.", "yellow"))
if modified_files:
print(colored("\nModified files:", "blue", attrs=["bold"]))
for file in modified_files:
print(colored(f" - {file}", "red"))
else:
print(colored("\nNo modified files detected.", "yellow"))
if untracked_files:
print(colored("\nUntracked files:", "yellow", attrs=["bold"]))
for file in untracked_files:
print(colored(f" - {file}", "light_red"))
else:
print(colored("\nNo untracked files detected.", "yellow"))
def status():
pipe_read, pipe_write = os.pipe()
pid_monitor = os.fork()
if pid_monitor == 0: # child
os.close(pipe_read)
print(f"Child Process PID: {os.getpid()} for monitoring status")
monitor_process()
os._exit(0)
else:
print(f"Parent Process PID: {os.getpid()} waiting for child {pid_monitor}")
os.wait()
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: gitoslab <command>")
sys.exit(1)
command = sys.argv[2]
if command == "init":
setup_logs()
elif command == "add":
if len(sys.argv) > 2:
base_path = sys.argv[3]
add_files(base_path)
else:
print("Usage: gitoslab add <path>")
elif command == "commit":
if len(sys.argv) == 5 and sys.argv[3] == "-m":
message = str(sys.argv[4])
commit_changes(message)
else:
print("Usage: gitoslab commit -m <message>")
elif command == "revert":
if len(sys.argv) == 4:
timestamp = int(sys.argv[3])
revert_commit(timestamp)
else:
print("Usage: gitoslab revert <timestamp>")
elif command == "status":
status()