Repository navigation
Expand file tree
/
Copy pathsync_app.py
More file actions
291 lines (243 loc) · 11 KB
/
Copy pathsync_app.py
File metadata and controls
291 lines (243 loc) · 11 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
import tkinter as tk
from tkinter import filedialog, messagebox, scrolledtext
import json
import os
import shutil
import time
from datetime import datetime
APP_DIR = os.path.dirname(os.path.abspath(__file__))
SETTINGS_FILE = os.path.join(APP_DIR, "settings.json")
SYNC_FILE = os.path.join(APP_DIR, "_sync.json")
class SyncApp:
def __init__(self, root):
self.root = root
self.root.title("Sync Tool")
self.root.geometry("700x550")
self.root.resizable(False, False)
# Load settings
self.settings = self.load_settings()
# --- Settings frame ---
frm_settings = tk.LabelFrame(root, text=" Catalog Settings ", padx=10, pady=10)
frm_settings.pack(fill="x", padx=15, pady=10)
tk.Label(frm_settings, text="Base catalog:").grid(row=0, column=0, sticky="w")
self.txt_base = tk.Entry(frm_settings, width=60)
self.txt_base.insert(0, self.settings.get("base_catalog", "D:\\base_catalog"))
self.txt_base.grid(row=1, column=0, columnspan=2, pady=5)
tk.Button(frm_settings, text="Browse...", command=self.browse_base).grid(row=1, column=2, padx=5)
tk.Label(frm_settings, text="Temp catalog:").grid(row=2, column=0, sticky="w")
self.txt_temp = tk.Entry(frm_settings, width=60)
self.txt_temp.insert(0, self.settings.get("temp_catalog", "D:\\temp_catalog"))
self.txt_temp.grid(row=3, column=0, columnspan=2, pady=5)
tk.Button(frm_settings, text="Browse...", command=self.browse_temp).grid(row=3, column=2, padx=5)
# --- Actions frame ---
frm_actions = tk.LabelFrame(root, text=" Actions ", padx=10, pady=10)
frm_actions.pack(fill="x", padx=15, pady=5)
self.btn_export = tk.Button(frm_actions, text="EXPORT (base -> temp)", bg="lightgreen",
command=self.do_export, width=22)
self.btn_export.pack(side="left", padx=5)
self.btn_import = tk.Button(frm_actions, text="IMPORT (temp -> base)", bg="lightblue",
command=self.do_import, width=22)
self.btn_import.pack(side="left", padx=5)
tk.Button(frm_actions, text="Save Settings", command=self.save_settings, width=22).pack(side="left", padx=5)
# --- Log frame ---
tk.Label(root, text="Log:").pack(anchor="w", padx=15)
self.log = scrolledtext.ScrolledText(root, height=18, font=("Consolas", 9))
self.log.pack(fill="both", padx=15, pady=5)
def log_msg(self, text):
ts = datetime.now().strftime("%H:%M:%S")
self.log.insert(tk.END, f"[{ts}] {text}\n")
self.log.see(tk.END)
self.root.update_idletasks()
def browse_base(self):
path = filedialog.askdirectory(title="Select base catalog")
if path:
self.txt_base.delete(0, tk.END)
self.txt_base.insert(0, path)
def browse_temp(self):
path = filedialog.askdirectory(title="Select temp catalog")
if path:
self.txt_temp.delete(0, tk.END)
self.txt_temp.insert(0, path)
def load_settings(self):
if os.path.exists(SETTINGS_FILE):
try:
with open(SETTINGS_FILE, "r", encoding="utf-8") as f:
return json.load(f)
except Exception:
pass
return {"base_catalog": "D:\\base_catalog", "temp_catalog": "D:\\temp_catalog"}
def save_settings(self):
self.settings = {
"base_catalog": self.txt_base.get().strip(),
"temp_catalog": self.txt_temp.get().strip()
}
with open(SETTINGS_FILE, "w", encoding="utf-8") as f:
json.dump(self.settings, f, indent=2)
self.log_msg("Settings saved.")
def save_json_utf8(self, path, data):
with open(path, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
def load_sync_data(self):
if os.path.exists(SYNC_FILE):
try:
with open(SYNC_FILE, "r", encoding="utf-8") as f:
return json.load(f)
except Exception:
pass
return {}
def get_file_info(self, filepath):
stat = os.stat(filepath)
return {
"mtime": stat.st_mtime,
"size": stat.st_size
}
def do_export(self):
base = self.txt_base.get().strip()
temp = self.txt_temp.get().strip()
if not os.path.isdir(base):
self.log_msg(f"ERROR: Base catalog not found: {base}")
return
if not os.path.isdir(temp):
os.makedirs(temp, exist_ok=True)
self.btn_export.config(state="disabled")
self.btn_import.config(state="disabled")
try:
sync_data = self.load_sync_data()
delete_list_file = os.path.join(temp, "_delete_list.json")
delete_list = []
if os.path.exists(delete_list_file):
try:
with open(delete_list_file, "r", encoding="utf-8") as f:
loaded = json.load(f)
if isinstance(loaded, list):
delete_list = loaded
except Exception:
pass
self.log_msg(f"Scanning: {base}")
current_paths = {}
copied = 0
for dirpath, _, filenames in os.walk(base):
for fname in filenames:
full = os.path.join(dirpath, fname)
rel = os.path.relpath(full, base)
current_paths[rel] = True
info = self.get_file_info(full)
is_modified = False
if rel not in sync_data:
is_modified = True
else:
cached = sync_data[rel]
if cached.get("mtime") != info["mtime"] or cached.get("size") != info["size"]:
is_modified = True
if is_modified:
dest = os.path.join(temp, rel)
os.makedirs(os.path.dirname(dest), exist_ok=True)
try:
shutil.copy2(full, dest)
sync_data[rel] = info
copied += 1
self.log_msg(f" Copied: {rel}")
except Exception as e:
self.log_msg(f" SKIPPED (locked): {rel} - {e}")
# Find deleted
to_delete = [k for k in sync_data if k not in current_paths]
for key in to_delete:
del sync_data[key]
if key not in delete_list:
delete_list.append(key)
temp_file = os.path.join(temp, key)
if os.path.exists(temp_file):
try:
os.remove(temp_file)
self.log_msg(f" Deleted from temp: {key}")
except Exception as e:
self.log_msg(f" NOT DELETED (locked): {key} - {e}")
self.save_json_utf8(SYNC_FILE, sync_data)
self.save_json_utf8(delete_list_file, delete_list)
self.log_msg(f"EXPORT COMPLETE. Files copied: {copied}")
finally:
self.btn_export.config(state="normal")
self.btn_import.config(state="normal")
def do_import(self):
base = self.txt_base.get().strip()
temp = self.txt_temp.get().strip()
if not os.path.isdir(temp):
self.log_msg(f"ERROR: Temp catalog not found: {temp}")
return
if not os.path.isdir(base):
os.makedirs(base, exist_ok=True)
self.btn_export.config(state="disabled")
self.btn_import.config(state="disabled")
try:
sync_data = self.load_sync_data()
delete_list_file = os.path.join(temp, "_delete_list.json")
delete_list = []
if os.path.exists(delete_list_file):
try:
with open(delete_list_file, "r", encoding="utf-8") as f:
loaded = json.load(f)
if isinstance(loaded, list):
delete_list = loaded
except Exception:
pass
self.log_msg(f"Scanning: {temp}")
copied = 0
for dirpath, _, filenames in os.walk(temp):
for fname in filenames:
if fname == "_delete_list.json":
continue
full = os.path.join(dirpath, fname)
rel = os.path.relpath(full, temp)
info = self.get_file_info(full)
is_modified = False
if rel not in sync_data:
is_modified = True
else:
cached = sync_data[rel]
if cached.get("mtime") != info["mtime"] or cached.get("size") != info["size"]:
is_modified = True
if is_modified:
dest = os.path.join(base, rel)
os.makedirs(os.path.dirname(dest), exist_ok=True)
try:
shutil.copy2(full, dest)
sync_data[rel] = info
copied += 1
self.log_msg(f" Copied: {rel}")
except Exception as e:
self.log_msg(f" SKIPPED (locked): {rel} - {e}")
# Delete files from base
deleted = 0
for key in delete_list:
filepath = os.path.join(base, key)
if os.path.exists(filepath):
try:
os.remove(filepath)
deleted += 1
self.log_msg(f" Deleted from base: {key}")
# Remove empty folders
d = os.path.dirname(filepath)
while d and d != base and len(d) > len(base):
try:
if not os.listdir(d):
os.rmdir(d)
d = os.path.dirname(d)
else:
break
except Exception:
break
except Exception as e:
self.log_msg(f" NOT DELETED (locked): {key} - {e}")
if key in sync_data:
del sync_data[key]
# Clear delete list
self.save_json_utf8(delete_list_file, [])
self.save_json_utf8(SYNC_FILE, sync_data)
self.log_msg(f"IMPORT COMPLETE. Copied: {copied}, deleted: {deleted}")
finally:
self.btn_export.config(state="normal")
self.btn_import.config(state="normal")
if __name__ == "__main__":
root = tk.Tk()
app = SyncApp(root)
root.mainloop()