-
Notifications
You must be signed in to change notification settings - Fork 0
/
savemon.py
1433 lines (1173 loc) · 38.6 KB
/
savemon.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
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from os import (
makedirs
)
from os.path import (
dirname,
exists,
join,
expanduser,
isdir,
isfile
)
from shutil import (
copyfile,
move
)
from os import (
sep,
mkdir,
listdir,
remove
)
from pprint import (
PrettyPrinter
)
from threading import (
Lock,
Thread
)
from queue import (
Empty,
Queue
)
from traceback import (
print_exc,
format_exc
)
from time import (
time,
sleep
)
from re import (
compile
)
import sys
from subprocess import (
Popen
)
from datetime import (
datetime
)
try:
from wx import (
ITEM_CHECK,
ID_FILE,
ID_ANY,
PostEvent,
EVT_SCROLL,
EVT_ENTER_WINDOW,
ScrollBar,
SB_VERTICAL,
Control,
EVT_LEFT_UP,
EVT_LEFT_DOWN,
EVT_MOTION,
DEFAULT_DIALOG_STYLE,
RESIZE_BORDER,
EVT_MOUSEWHEEL,
EVT_SIZE,
EVT_PAINT,
AutoBufferedPaintDC, # is it cross-platform?
BG_STYLE_CUSTOM,
Dialog,
ID_NEW,
App,
Frame,
EVT_CLOSE,
StaticText,
TextCtrl,
BoxSizer,
HORIZONTAL,
VERTICAL,
EXPAND,
Button,
EVT_BUTTON,
DirDialog,
DD_DEFAULT_STYLE,
DD_DIR_MUST_EXIST,
ID_OK,
ID_CANCEL,
ID_YES,
MessageDialog,
YES_NO,
ID_NO,
MenuBar,
Menu,
ID_ABOUT,
CheckBox,
EVT_CHECKBOX,
EVT_MENU
)
from wx.lib.newevent import (
NewEvent
)
except ImportError:
print_exc()
print("try python -m pip install --upgrade wxPython")
exit(-1)
try:
from git import (
Repo,
InvalidGitRepositoryError
)
except ImportError:
print_exc()
print("try python -m pip install --upgrade gitpython")
exit(-1)
# Windows
#########
try:
from win32file import (
CreateFile,
FILE_SHARE_READ,
FILE_SHARE_WRITE,
OPEN_EXISTING,
OPEN_EXISTING,
ReadDirectoryChangesW,
CloseHandle
)
from win32con import (
FILE_NOTIFY_CHANGE_FILE_NAME,
FILE_NOTIFY_CHANGE_DIR_NAME,
FILE_NOTIFY_CHANGE_SIZE,
FILE_NOTIFY_CHANGE_LAST_WRITE,
FILE_FLAG_BACKUP_SEMANTICS
)
except ImportError:
print_exc()
print("try python -m pip install --upgrade pywin32")
exit(-1)
FILE_LIST_DIRECTORY = 0x0001
ACTIONS = {
1 : "Created",
2 : "Deleted",
3 : "Updated",
4 : "Renamed from something",
5 : "Renamed to something"
}
def open_directory_in_explorer(path):
Popen('explorer "%s"' % path)
# Generic
#########
class lazy(tuple):
def __new__(type, getter):
ret = tuple.__new__(type, (getter,))
return ret
def __get__(self, obj, type = None):
getter = self[0]
val = getter(obj)
obj.__dict__[getter.__name__] = val
return val
class NullStream(object):
write = lambda *_: None
flush = lambda *_: None
nullStream = NullStream()
logLock = Lock()
globalLogStream = nullStream
def cloneStream(stream):
class StreamClone(object):
def write(self, *a, **kw):
with logLock:
globalLogStream.write(*a, **kw)
stream.write(*a, **kw)
def flush(self):
globalLogStream.flush()
stream.flush()
return StreamClone()
sys.stderr = cloneStream(sys.stderr)
sys.stdout = cloneStream(sys.stdout)
# Domain specific
#################
re_system_name = compile("^.git$")
class Settings(object):
def __init__(self):
self.path = expanduser(join("~", "savemon.settings.py"))
self.saves = []
self.hidden = set()
self.logging = False
self.logFile = expanduser(join("~", "savemon.log"))
def __enter__(self, *_):
try:
with open(self.path, "r") as f:
code = f.read()
except:
pass
else:
glob = dict()
try:
exec(code, glob)
except:
print_exc()
else:
for k, v in glob.items():
setattr(self, k, v)
return self
def __exit__(self, *exc):
if exc[0]:
return
pp = PrettyPrinter(indent = 4)
code = "\n".join(
("%s = %s" % (a, pp.pformat(getattr(self, a)))) for a in [
"saves",
"hidden",
"logging",
]
)
try:
with open(self.path + ".tmp", "w") as f:
f.write(code)
except:
print_exc()
else:
move(self.path + ".tmp", self.path)
class MonitorThread(Thread):
def __init__(self, rootPath, onExit):
super(MonitorThread, self).__init__(name = "Directory Monitor Thread")
self.rootPath = rootPath
self.onExit = onExit
self._exit_request = False
self.trigger_file = join(rootPath, ".savemon.trigger")
self.changes = Queue()
def run(self):
root = self.rootPath
print("Start monitoring of '%s'" % root)
hDir = CreateFile(root, FILE_LIST_DIRECTORY,
FILE_SHARE_READ | FILE_SHARE_WRITE,
None,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS,
None
)
while not self._exit_request:
changes = ReadDirectoryChangesW(hDir, 1024, True,
FILE_NOTIFY_CHANGE_FILE_NAME |
FILE_NOTIFY_CHANGE_DIR_NAME |
FILE_NOTIFY_CHANGE_SIZE |
FILE_NOTIFY_CHANGE_LAST_WRITE,
None,
None
)
for action, file in changes:
changed = join(root, file)
if changed == self.trigger_file:
continue
self.changes.put((action, file))
print(changed,
ACTIONS.get(action, "[unknown 0x%X]" % action)
)
print("Stop monitoring of '%s'" % root)
CloseHandle(hDir)
self.onExit()
@property
def exit_request(self):
return self._exit_request
@exit_request.setter
def exit_request(self, val):
self._exit_request = val
if val:
self.trigger()
def trigger(self):
assert not exists(self.trigger_file)
with open(self.trigger_file, "w"): pass
remove(self.trigger_file)
class BackUpThread(Thread):
def __init__(self, saveDir, backupDir, changesQueue, filterOut = None):
super(BackUpThread, self).__init__(name = "Backing Up Thread")
self.saveDir = saveDir
self.backupDir = backupDir
self.qchanges = changesQueue
self.exit_request = False
self.filterOut = filterOut
self.doCommit = []
def commit(self, attempts = 5, period = 5):
try:
self._do_commit()
except:
print("Checking for index.lock")
lock = join(self.backupDir, ".git", "index.lock")
# XXX: If lock file exists then another Git process can operate.
# And removing of the lock is likely a very bad idea.
# However, if it still exists after some time then it likely
# has been forgotten (there is known bug).
# Also, user should not work with the repo while monitoring is
# active.
if exists(lock):
while attempts > 0:
print("Waiting for %d sec. (%d)" % (period, attempts))
sleep(period)
if not exists(lock):
break
attempts -= 1
else:
print("Removing " + lock)
remove(lock)
self._do_commit()
else:
# some other error
raise
def _do_commit(self):
repo, doCommit = self.repo, self.doCommit
if doCommit:
print("Committing changes")
for method, node in doCommit:
if method == "add":
repo.index.add([node])
elif method == "remove":
repo.index.remove([node], working_tree = True)
message = " ".join(
c[1] for c in doCommit[0 : min(5, len(doCommit))]
)
repo.index.commit(message)
del doCommit[:]
print("Committing finished")
def check(self, relN):
fullN = join(self.saveDir, relN)
fullBackN = join(self.backupDir, relN)
if isfile(fullN):
if exists(fullBackN):
with open(fullN, "rb") as f0:
with open(fullBackN, "rb") as f1:
doChanged = f0.read() != f1.read()
if doChanged:
print("Replacing %s with %s" % (fullBackN, fullN))
copyfile(fullN, fullBackN)
self.doCommit.append(("add", relN))
else:
fullBackNDir = dirname(fullBackN)
if not exists(fullBackNDir):
print("Creating directories '%s'" % fullBackNDir)
makedirs(fullBackNDir)
print("Copying '%s' to '%s'" % (fullN, fullBackN))
copyfile(fullN, fullBackN)
self.doCommit.append(("add", relN))
else:
if isfile(fullBackN):
print("Removing '%s'" % fullBackN)
self.doCommit.append(("remove", relN))
def run(self):
backupDir = self.backupDir
saveDir = self.saveDir
filterOut = self.filterOut
try:
self.repo = Repo(backupDir)
except InvalidGitRepositoryError:
print("Initializing Git repository in '%s'" % backupDir)
self.repo = Repo.init(backupDir)
print("Backing up current content of '%s'" % saveDir)
stack = [""]
while stack:
cur = stack.pop()
curSave = join(saveDir, cur)
curBackup = join(backupDir, cur)
toCheck = set(listdir(curSave))
if isdir(curBackup):
toCheck.update(listdir(curBackup))
for n in toCheck:
relN = join(cur, n)
if re_system_name.match(relN):
continue
if filterOut and filterOut.match(relN):
print("Ignoring '%s' (Filter Out)" % relN)
continue
fullN = join(saveDir, relN)
if isdir(fullN):
# Note, directories are created by `check` if needed
stack.append(relN)
else:
self.check(relN)
self.commit()
changes = set()
lastChange = time()
# Do not exit until detected changes are committed
while not self.exit_request or changes:
try:
change = self.qchanges.get(timeout = 0.1)
except Empty:
# give game a chance to made save data consistent
t = time()
if changes and t - lastChange > 5.0:
# ensure a directory are always precede its files
toCheck = sorted(changes, key = lambda c : len(c[1]))
print("Checking\n %s" % "\n ".join(
c[1] for c in toCheck)
)
for c in toCheck:
cur = c[1]
self.check(cur)
changes.clear()
self.commit()
continue
relN = change[1]
if re_system_name.match(relN):
continue
elif filterOut and filterOut.match(relN):
print("Ignoring '%s' (Filter Out)" % relN)
continue
else:
changes.add(change)
lastChange = time()
print("Stop backing up of '%s'" % saveDir)
class GitGraph(object):
def __init__(self):
self.cache = {}
self.roots = None
def __getitem__(self, gitpython_commit):
return self.cache[gitpython_commit]
def __setitem__(self, gitpython_commit, commit):
self.cache[gitpython_commit] = commit
def get(self, *a, **kw):
return self.cache.get(*a, **kw)
def iter_commits(self):
visited = set()
stack = list(self.roots)
while stack:
c = stack.pop(0)
if c in visited:
continue
visited.add(c)
yield c
stack.extend(c.children)
class Commit(object):
graph = GitGraph()
def __new__(type, backed, *a, **kw):
ret = type.graph.get(backed, None)
if ret is None:
ret = super().__new__(type)
ret.backed = backed
ret.children = []
type.graph[backed] = ret
return ret
@lazy
def parents(self):
ps = []
for p in self.backed.parents:
pc = Commit(p)
ps.append(pc)
pc.children.append(self)
return tuple(ps)
@lazy
def committed_time_str(self):
return commit_time_str(self.backed)
@lazy
def label(self):
return self.committed_time_str + " | " + self.backed.message
def commit_time_str(commit):
return commit.committed_datetime.strftime("%Y.%m.%d %H:%M:%S %z")
def build_commit_graph(*heads):
stack = list(heads)
roots = []
visited = set()
while stack:
c = stack.pop()
if c in visited:
continue
visited.add(c)
ps = c.parents
if not ps:
roots.append(c)
continue
for p in ps:
p.children.append(c)
stack.append(p)
Commit.graph.roots = tuple(roots)
backup_re = compile("backup_([0-9]+)")
class Strip(object):
def __init__(self, c):
self.commits = [c]
start_j = c._j
self.start_j = start_j
self.end_j = start_j
def bind(self, c):
self.commits.append(c)
self.end_j = max(c._j, self.end_j)
CommitSelectedEvent, EVT_COMMIT_SELECTED = NewEvent()
class GitSelector(Control):
def __init__(self, parent, repo_dir, **kw):
super(GitSelector, self).__init__(parent, **kw)
self._scrollbar = None
self.height = 300
self.repo_dir = repo_dir
self.scale, self.xshift, self.yshift = 4, 8, -8
self.half_step = 1 << (self.scale - 1)
self.text_offset_x = 8
self.read_repo()
self.Bind(EVT_MOTION, self._on_mouse_motion)
self._hl = None
self.Bind(EVT_LEFT_DOWN, self._on_lmb_down)
self.Bind(EVT_LEFT_UP, self._on_lmb_up)
self._lmb = None
self.Bind(EVT_SIZE, self._on_size)
self.SetBackgroundStyle(BG_STYLE_CUSTOM)
self.Bind(EVT_PAINT, self._on_paint)
self._scroll = 0
self.scroll = self.current._y - self.half_step
self.Bind(EVT_MOUSEWHEEL, self._on_mouse_wheel)
self.Bind(EVT_ENTER_WINDOW, self._on_enter_window)
def read_repo(self):
try:
repo = Repo(self.repo_dir)
except:
print("Cannot refresh backup")
print(format_exc())
return
self.repo = repo
heads = []
Commit.graph = graph = GitGraph()
for head in repo.heads:
c = Commit(head.commit)
if c in heads:
continue
heads.append(c)
build_commit_graph(*heads)
# layout commits
stripes = []
for j, c in enumerate(graph.iter_commits()):
c._j = j
parents = c.parents
for p in parents:
try:
s = p._s
except AttributeError:
# p's strip is already stolen by another child
continue
else:
del p._s
s.bind(c)
c._s = s
break
else:
# No free strip or c is root
c._s = s = Strip(c)
stripes.append(s)
for i, s in enumerate(stripes):
for c in s.commits:
c._i = i
# self.g_width = i + 1
# assign coordinates
self.index = index = {}
max_j = len(graph.cache)
scale, xshift, yshift = self.scale, self.xshift, self.yshift
self.lines = lines = []
for c in graph.iter_commits():
c._x = (c._i << scale) + xshift
# graph grows to the top
inv_j = max_j - c._j
index[inv_j] = c
c._y = (inv_j << scale) + yshift
for p in c.parents:
lines.append([p._x, p._y, c._x, c._y])
self.max_y = (max_j << scale) + yshift
self.current = graph[repo.active_branch.commit]
@property
def max_scroll(self):
return self.max_y - self.height + self.half_step
@property
def scroll(self):
return self._scroll
@scroll.setter
def scroll(self, v):
scroll = min(max(v, 0), self.max_scroll)
if scroll == self._scroll:
return
self._scroll = scroll
if self._scrollbar:
self._scrollbar.SetThumbPosition(scroll)
self.Refresh()
def _on_mouse_wheel(self, e):
self.scroll -= e.GetWheelRotation()
@property
def scrollbar(self):
return self._scrollbar
@scrollbar.setter
def scrollbar(self, sb):
prev = self._scrollbar
if sb is prev:
return
if prev is not None:
prev.Unbind(EVT_SCROLL, handler = self._on_scroll)
self._scrollbar = sb
if sb is None:
return
h = self.height
sb.SetScrollbar(self._scroll, h, self.max_scroll + h, h)
sb.Bind(EVT_SCROLL, self._on_scroll)
def _on_scroll(self, e):
self.scroll = e.GetPosition()
def _on_size(self, event):
event.Skip()
h = self.GetClientSize()[1]
self.height = h
# update scrolling
if self._scrollbar:
self._scrollbar.SetScrollbar(self._scroll, h, self.max_scroll + h,
h
)
self.scroll = self._scroll
self.Refresh()
def _on_mouse_motion(self, e):
if self._lmb is None:
x, y = e.GetPosition()
self._highlight(x, y)
def _highlight(self, x, y):
mid = self.half_step
# i = (x + mid - self.xshift) >> self.scale
# i = min(i, self.g_width - 1)
j = (y + mid + self.scroll - self.yshift) >> self.scale
try:
c = self.index[j] # (i, j)]
except KeyError:
self.highlighted = None
else:
self.highlighted = c
@property
def highlighted(self):
return self._hl
@highlighted.setter
def highlighted(self, v):
if v is self._hl:
return
self._hl = v
self.Refresh()
def _on_lmb_down(self, e):
self._lmb = e.GetPosition()
e.Skip()
def _on_lmb_up(self, e):
lmb = self._lmb
if lmb is None:
return
self._lmb = None
hl = self._hl
if hl is self.current:
return
x0, y0 = lmb
x, y = e.GetPosition()
self._highlight(x, y)
if hl is None:
return
if max(abs(x0 - x), abs(y0 - y)) > self.half_step:
return
PostEvent(self, CommitSelectedEvent(commit = hl))
def _on_paint(self, _e):
scroll = -self.scroll
text_offset_x = self.text_offset_x
dc = AutoBufferedPaintDC(self)
dc.Clear()
text_shift = -self.half_step
hl, cur = self._hl, self.current
for x1, y1, x2, y2 in self.lines:
dc.DrawLine(x1, y1 + scroll, x2, y2 + scroll)
br = dc.GetBackground()
prev_c = br.GetColour()
revert_color = False
for c in Commit.graph.iter_commits():
while True:
if c is cur:
br.SetColour((0, 255, 0, 255))
elif c is hl:
br.SetColour((255, 0, 0, 255))
else:
break
dc.SetBrush(br)
revert_color = True
break
x = c._x
y = c._y
dc.DrawCircle(x, y + scroll, 4)
dc.DrawText(c.label, x + text_offset_x, y + scroll + text_shift)
if revert_color:
br.SetColour(prev_c)
dc.SetBrush(br)
revert_color = False
def _on_enter_window(self, _):
self.SetFocus()
class BackupSelector(Dialog):
def __init__(self, parent, backupDir):
super(Dialog, self).__init__(parent,
style = DEFAULT_DIALOG_STYLE | RESIZE_BORDER
)
self.SetMinSize((300, 300))
sizer = BoxSizer(HORIZONTAL)
selector = GitSelector(self, backupDir, size = (700, 500))
sizer.Add(selector, 1, EXPAND)
scrollbar = ScrollBar(self, style = SB_VERTICAL)
selector.scrollbar = scrollbar
sizer.Add(scrollbar, 0, EXPAND)
sizer.SetSizeHints(self)
self.SetSizer(sizer)
selector.Bind(EVT_COMMIT_SELECTED, self._on_commit_selected)
def _on_commit_selected(self, e):
c = e.commit
dlg = MessageDialog(self,
"Do you want to switch to that version?\n\n" +
"SHA1: %s\n\n%s\n\n" % (c.backed.hexsha, c.label) +
"Files in both save and backup directories will be overwritten!",
"Confirmation is required",
YES_NO
)
switch = dlg.ShowModal() == ID_YES
dlg.Destroy()
if not switch:
return
self.target = c.backed
self.EndModal(ID_OK)
class SaveSettings(object):
def __init__(self, master, saveDirVal = None, backupDirVal = None):
self.master = master
saveDirSizer = BoxSizer(HORIZONTAL)
self.saveDir = TextCtrl(master,
size = (600, -1)
)
if saveDirVal:
self.saveDir.SetValue(saveDirVal)
saveDirSizer.Add(StaticText(master, label = "Save directory"), 0,
EXPAND
)
saveDirSizer.Add(self.saveDir, 1, EXPAND)
selectSaveDir = Button(master, -1, "Select")
saveDirSizer.Add(selectSaveDir, 0, EXPAND)
master.Bind(EVT_BUTTON, self._on_select_save_dir, selectSaveDir)
openSave = Button(master, label = "Open")
saveDirSizer.Add(openSave, 0, EXPAND)
master.Bind(EVT_BUTTON, self._on_open_save_dir, openSave)
hide = Button(master, label = "Hide")
saveDirSizer.Add(hide, 0, EXPAND)
master.Bind(EVT_BUTTON, self._on_hide, hide)
backupDirSizer = BoxSizer(HORIZONTAL)
self.backupDir = TextCtrl(master)
if backupDirVal:
self.backupDir.SetValue(backupDirVal)
backupDirSizer.Add(StaticText(master, label = "Backup directory"), 0,
EXPAND
)
backupDirSizer.Add(self.backupDir, 1, EXPAND)
switch = Button(master, label = "Switch")
master.Bind(EVT_BUTTON, self._on_switch, switch)
backupDirSizer.Add(switch, 0, EXPAND)
override = Button(master, label = "Overwrite")
master.Bind(EVT_BUTTON, self._on_overwrite, override)
backupDirSizer.Add(override, 0, EXPAND)
selectBackupDir = Button(master, -1, "Select")
master.Bind(EVT_BUTTON, self._on_select_backup_dir, selectBackupDir)
backupDirSizer.Add(selectBackupDir, 0, EXPAND)
openBackup = Button(master, label = "Open")
backupDirSizer.Add(openBackup, 0, EXPAND)
master.Bind(EVT_BUTTON, self._on_open_backup_dir, openBackup)
filterOutSizer = BoxSizer(HORIZONTAL)
filterOutSizer.Add(StaticText(master, label = "Filter Out"), 0, EXPAND)
self.filterOut = TextCtrl(master)
filterOutSizer.Add(self.filterOut, 1, EXPAND)
self.cbMonitor = CheckBox(master, label = "Monitor")
master.Bind(EVT_CHECKBOX, self._on_monitor, self.cbMonitor)
self.sizer = sizer = BoxSizer(VERTICAL)
sizer.Add(saveDirSizer, 0, EXPAND)
sizer.Add(backupDirSizer, 0, EXPAND)
sizer.Add(filterOutSizer, 0, EXPAND)
sizer.Add(self.cbMonitor, 0, EXPAND)
self.settingsWidgets = [
selectSaveDir,
self.saveDir,
self.backupDir,
switch,
selectBackupDir,
self.filterOut
]
def _on_overwrite(self, _):
self.ask_and_overwrite()
def ask_and_overwrite(self):
backupDir = self.backupDir.GetValue()
savePath = self.saveDir.GetValue()
if not (isdir(backupDir) and bool(savePath)):
with MessageDialog(self.master, "Set paths up!", "Error") as dlg:
dlg.ShowModal()
return False
repo = Repo(backupDir)
if repo.is_dirty():
with MessageDialog(self.master,
"Backup repository '%s' is dirty" % backupDir,
"Error") as dlg:
dlg.ShowModal()
return False
active_branch = repo.active_branch
try:
c = active_branch.commit
except Exception as e:
hint = ""
try:
if active_branch.name == "master":
hint = "Is backup empty?"
except:
pass
with MessageDialog(self.master,
str(e) + "\n" + hint,
"Error") as dlg:
dlg.ShowModal()
return False
label = commit_time_str(c) + " | " + c.message
dlg = MessageDialog(self.master,
"Do you want to overwrite save data with current version?\n\n" +
"SHA1: %s\n\n%s\n\n" % (c.hexsha, label) +
"Files in save directory will be overwritten!",
"Confirmation is required",
YES_NO
)
switch = dlg.ShowModal() == ID_YES
dlg.Destroy()
if not switch:
return False
self._switch_to(c)
return True