-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimple-git-editor.py
373 lines (311 loc) · 15.7 KB
/
simple-git-editor.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
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
import platform
import tkinter as tk
from tkinter import messagebox, ttk
import tkinter.filedialog as filedialog
import tkinter.messagebox as messagebox
import os
import subprocess
import customtkinter as ctk
from dotenv import load_dotenv
from git import Repo
import socket
import json
from jsonschema import validate, ValidationError
from pathlib import Path
load_dotenv()
git_access_token = os.getenv("git_access_token")
repo_url = os.getenv("repo")
app_name = os.getenv("app_name")
file_extensions = os.getenv("file_extensions")
search_folders = os.getenv("search_folders")
repo_path = './repo'
json_schema_path = "./json-schemas"
class GitGUIApp:
def __init__(self, root):
self.root = root
self.root.title(app_name)
self.json_schemas = self.load_json_schemas(json_schema_path)
# Frames
left_frame = ctk.CTkFrame(root)
left_frame.pack(side=tk.TOP, padx=10, pady=10, fill=tk.X)
#buttons
self.get_files_button = ctk.CTkButton(left_frame, text="📂 Get Files", command=self.get_files)
self.get_files_button.pack(side=tk.LEFT)
self.save_files_button = ctk.CTkButton(left_frame, text="💾 Save Files", command=self.save_files)
self.save_files_button.pack(side=tk.LEFT)
self.add_file_button = ctk.CTkButton(left_frame, text="➕ Add File", command=self.add_file)
self.add_file_button.pack(side=tk.RIGHT)
self.delete_file_button = ctk.CTkButton(left_frame, text="❌ Delete File", command=self.delete_file)
self.delete_file_button.pack(side=tk.RIGHT)
style.configure("Treeview", background=bg_color, foreground=text_color, fieldbackground=bg_color, borderwidth=0)
style.map('Treeview', background=[('selected', bg_color)], foreground=[('selected', selected_color)])
root.bind("<<TreeviewSelect>>", lambda event: root.focus_set())
self.file_list = ttk.Treeview(root)
self.file_list["columns"] = ("Changed", "Filename")
self.file_list.column("#0", width=0, stretch=tk.NO)
self.file_list.column("Changed", anchor=tk.CENTER, width=32, stretch=tk.NO)
self.file_list.column("Filename", anchor=tk.W, stretch=tk.YES)
self.file_list.heading("Changed", text="", anchor=tk.CENTER)
self.file_list.heading("Filename", text="Filename", anchor=tk.W)
self.file_list.bind("<Double-1>", self.on_file_click)
self.file_list.pack(fill=tk.BOTH, expand=True, side=tk.BOTTOM)
self.populate_list(repo_path)
self.check_for_changes()
def get_files(self):
if not repo_url or not git_access_token:
messagebox.showerror("Error", "Repository URL or Access Token not set in environment variables.")
return
if not os.path.exists(repo_path):
try:
Repo.clone_from(repo_url, repo_path, env={'GIT_ASKPASS': 'echo', 'GIT_USERNAME': git_access_token})
except Exception as e:
messagebox.showerror("Error", str(e))
return
else:
try:
repo = Repo(repo_path)
origin = repo.remote(name='origin')
origin.fetch()
default_branch = repo.active_branch.name if repo.active_branch else 'master'
repo.git.reset('--hard', f'origin/{default_branch}')
repo.git.pull()
except Exception as e:
messagebox.showerror("Error", str(e))
return
self.populate_list(repo_path)
def load_json_schemas(self, schema_dir):
schemas = {}
if not os.path.isdir(schema_dir):
return schemas
for file in os.listdir(schema_dir):
if file.endswith('.json'):
with open(os.path.join(schema_dir, file)) as schema_file:
schemas[file] = json.load(schema_file)
return schemas
def populate_list(self, repo_path):
extensions = os.environ.get('file_extensions', '')
valid_extensions = extensions.split(';')
search_folders = os.environ.get('search_folders', '')
if search_folders:
folders = search_folders.split(';')
else:
folders = ['']
self.file_list.delete(*self.file_list.get_children())
for folder in folders:
folder_path = os.path.join(repo_path, folder)
if os.path.isdir(folder_path):
for filename in os.listdir(folder_path):
if any(filename.endswith(ext) for ext in valid_extensions):
file_rel_path = os.path.join(folder, filename)
self.file_list.insert("", tk.END, values=("", file_rel_path), tags=('unchanged',))
# tag for modified files
# self.file_list.tag_configure('modified', background='light_yellow')
def check_for_changes(self):
if not os.path.isdir(repo_path): return
repo = Repo(repo_path)
changed_files = [item.a_path for item in repo.index.diff(None)] + repo.untracked_files
for filename in changed_files:
self.highlight_modified(filename)
# Schedule next check
self.root.after(5000, self.check_for_changes)
def highlight_modified(self, filename):
for item in self.file_list.get_children():
treeview_filelist_item = os.path.normpath(os.path.normpath(self.file_list.item(item, 'values')[1]))
filename_norm = os.path.normpath(filename)
if treeview_filelist_item == filename_norm:
self.file_list.item(item, values=("✏️", filename), tags=('modified',))
break
def on_file_click(self, event):
item = self.file_list.selection()[0]
filename = self.file_list.item(item, 'values')[1]
file_path = os.path.join(repo_path, filename)
if filename.endswith('.json'):
with open(file_path) as json_file:
json_data = json.load(json_file)
for _, schema in self.json_schemas.items():
try:
validate(instance=json_data, schema=schema)
self.show_json_dialog(json_data, schema, file_path)
return
except ValidationError:
pass
if os.path.isfile(file_path):
if platform.system() == "Windows":
os.startfile(file_path)
elif platform.system() == "Darwin":
subprocess.call(["open", file_path])
else: # Linux
subprocess.call(["xdg-open", file_path])
def show_json_dialog(self, json_data, schema, file_path):
dialog = ctk.CTkToplevel(self.root)
dialog.title(schema.get('title', 'JSON Data'))
self.widget_references = {}
if schema.get('type') == 'array':
# Handle array at root
self.create_array_ui(dialog, json_data, 'root', schema.get('items', {}))
else:
# Handle normal object with properties
self.process_properties(dialog, json_data, schema.get('properties', {}))
dialog.grid_rowconfigure(0, weight=1)
dialog.grid_columnconfigure(1, weight=1)
dialog.protocol("WM_DELETE_WINDOW", lambda: self.on_dialog_close(dialog, json_data, schema, file_path))
dialog.transient(self.root)
dialog.focus_set()
def process_properties(self, parent, data, properties, parent_key=''):
row = 0
for prop, details in properties.items():
label = ctk.CTkLabel(parent, text=prop)
label.grid(row=row, column=0, padx=10, pady=5)
value = data.get(prop, '')
widget_key = f"{parent_key}.{prop}" if parent_key else prop
if details.get('type') == 'object':
# Handle nested object
nested_frame = ctk.CTkFrame(parent)
nested_frame.grid(row=row, column=1, padx=10, pady=5, sticky='ew')
self.process_properties(nested_frame, value, details.get('properties', {}), widget_key)
elif details.get('type') == 'array':
# Handle array
array_frame = ctk.CTkFrame(parent)
array_frame.grid(row=row, column=1, padx=10, pady=2, sticky='ew')
self.create_array_ui(array_frame, value, widget_key, details.get('items', {}))
else:
# Handle simple types
text = ctk.CTkEntry(parent)
text.insert(0, str(value))
text.grid(row=row, column=1, padx=10, pady=5, sticky='ew')
self.widget_references[widget_key] = text
row += 1
def create_array_ui(self, parent, array_data, array_key, item_schema):
for i, item in enumerate(array_data):
if item_schema.get('type') == 'object':
# Handle array of objects
item_frame = ctk.CTkFrame(parent, border_color="grey", border_width=2)
item_frame.grid(row=i, column=0, padx=10, pady=2, sticky='ew')
self.process_properties(item_frame, item, item_schema.get('properties', {}), f"{array_key}[{i}]")
else:
# Handle array of simple types
entry = ctk.CTkEntry(parent)
entry.insert(0, str(item))
entry.grid(row=i, column=0, padx=10, pady=2, sticky='ew')
self.widget_references[f"{array_key}[{i}]"] = entry
def on_dialog_close(self, dialog, original_data, schema, file_path):
# Attempt to save the data when dialog is closed
if self.save_json_data(original_data, schema, file_path):
dialog.destroy() # Only close the dialog if save was successful
def save_json_data(self, original_data, schema, file_path):
def update_array_data(array_data, item_schema, parent_key):
updated_array = []
for i, item in enumerate(array_data):
if item_schema.get('type') == 'object':
# For each object in the array, update its properties
updated_object = {}
for prop in item_schema.get('properties', {}):
item_key = f"{parent_key}[{i}].{prop}"
if item_key in self.widget_references:
widget = self.widget_references[item_key]
prop_value = widget.get()
# Convert prop_value to the correct type as needed
updated_object[prop] = prop_value
updated_array.append(updated_object)
else:
# Handle simple types in the array
item_key = f"{parent_key}[{i}]"
if item_key in self.widget_references:
widget = self.widget_references[item_key]
updated_array.append(widget.get())
return updated_array
def update_data(data, schema_properties, parent_key=''):
for prop, details in schema_properties.items():
widget_key = f"{parent_key}.{prop}" if parent_key else prop
if details.get('type') == 'object':
nested_data = data.get(prop, {})
update_data(nested_data, details['properties'], widget_key)
data[prop] = nested_data
elif details.get('type') == 'array':
array_data = update_array_data(data[prop], details['items'], widget_key)
data[prop] = array_data
else:
if widget_key in self.widget_references:
widget = self.widget_references[widget_key]
input_value = widget.get()
if details.get('type') == 'number':
try:
data[prop] = float(input_value)
except ValueError:
messagebox.showerror("Validation Error", f"Value for '{prop}' should be a number.")
elif details.get('type') == 'integer':
try:
data[prop] = int(input_value)
except ValueError:
messagebox.showerror("Validation Error", f"Value for '{prop}' should be a integer.")
else:
data[prop] = input_value
# Check if the root of the schema is an array
if schema.get('type') == 'array':
updated_data = update_array_data(original_data, schema.get('items', {}), 'root')
else:
updated_data = original_data.copy()
update_data(updated_data, schema.get('properties', {}))
# Validate updated data
try:
validate(instance=updated_data, schema=schema)
with open(file_path, 'w') as json_file:
json.dump(updated_data, json_file, indent=4)
# messagebox.showinfo("Success", "Data saved successfully.")
return True
except ValidationError as e:
messagebox.showerror("Validation Error", str(e))
return False
def save_files(self):
if not os.path.exists(repo_path):
messagebox.showerror("Error", "Repository not cloned.")
return
try:
repo = Repo(repo_path)
repo.git.add(all=True)
changed_files = [item.a_path for item in repo.head.commit.diff(None)]
commit_message = f"Updated {', '.join(changed_files)} from {socket.gethostname()}"
repo.index.commit(commit_message)
repo.remote().push()
self.get_files()
except Exception as e:
messagebox.showerror("Error", str(e))
def delete_file(self):
selected_item = self.file_list.selection()
if selected_item:
filename = self.file_list.item(selected_item, 'values')[1]
file_path = os.path.join(repo_path, filename)
if os.path.exists(file_path):
os.remove(file_path)
self.file_list.delete(selected_item)
def add_file(self):
extensions = os.environ.get('file_extensions', '')
valid_extensions = extensions.split(';')
file_types = [('Allowed files', valid_extensions)]
# Open file save dialog
new_file_path = filedialog.asksaveasfilename(initialdir=repo_path, filetypes=file_types, defaultextension=valid_extensions[0])
if new_file_path:
with open(new_file_path, 'w') as new_file:
new_file.write('') # empty file
# Open the file
if platform.system() == "Windows":
os.startfile(new_file_path)
elif platform.system() == "Darwin": # macOS
subprocess.call(["open", new_file_path])
else: # Linux
subprocess.call(["xdg-open", new_file_path])
filename = os.path.basename(new_file_path)
# Add to Treeview
self.file_list.insert("", tk.END, values=("➕", filename), tags=('new_file',))
# Configure tag for new files
# self.file_list.tag_configure('new_file', background='lime green')
root = ctk.CTk()
root.geometry("1024x768")
###Treeview Customisation (theme colors are selected)
bg_color = root._apply_appearance_mode(ctk.ThemeManager.theme["CTkFrame"]["fg_color"])
text_color = root._apply_appearance_mode(ctk.ThemeManager.theme["CTkLabel"]["text_color"])
selected_color = root._apply_appearance_mode(ctk.ThemeManager.theme["CTkButton"]["fg_color"])
style = ttk.Style()
style.theme_use("default")
app = GitGUIApp(root)
root.mainloop()