forked from CAU-OSS-project-practice/OSS-file-manager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfiles_new.py
1556 lines (1374 loc) · 56.7 KB
/
files_new.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
import os
import stat
from tkinter import font
import pygit2
import re
import sys
import platform
import subprocess
import string
import shutil
import configparser
import tkinter as tk
from tkinter import ttk, simpledialog,messagebox
from tkinter.messagebox import askyesno
from tkinter import filedialog
from pathlib import Path
from ftplib import FTP
from send2trash import send2trash
import history_graph
# git status dictionary
git_status_dict = {
-1: "NOT_GIT_REPOSITORY",
0: "UNMODIFIED",
1: "STAGED",
2: "STAGED",
4: "GIT_STATUS_INDEX_DELETED",
8: "GIT_STATUS_INDEX_RENAMED",
16: "GIT_STATUS_INDEX_TYPECHANGE",
128: "UNTRACKED",
132: "UNTRACKED",
256: "UNSTAGED",
257: "UNSTAGED-STAGED",
258: "UNSTAGED-STAGED",
512: "GIT_STATUS_WT_DELETED",
1024: "GIT_STATUS_WT_RENAMED",
2048: "GIT_STATUS_WT_TYPECHANGE",
4096: "GIT_STATUS_WT_UNREADABLE",
16384: "GIT_STATUS_IGNORED",
32768: "GIT_STATUS_CONFLICTED"
}
# icons for status [default, unstaged, staged, both]
icon_status_dict = {
-1: 0,
0: 0,
1: 2,
2: 2,
4: 0,
8: 0,
16: 0,
128: 1,
132: 1,
256: 1,
257: 3,
258: 3,
512: 0,
1024: 0,
2048: 0,
4096: 0,
16384: 0,
32768: 0
}
def open_git_branch_list():
global input_window
input_window = tk.Toplevel(window)
input_window.title('branch list for merge')
input_window.geometry("500x150")
input_window.geometry("+500+300")
if check_git_repo(last_path):
repository = pygit2.Repository(last_path) # 저장소 경로 설정
current_branch = repository.head.shorthand # 현재 브랜치 확인
branches_list = list(repository.branches.local)
branches_list.remove(current_branch)
global branch_combobox1
branch_combobox1 = ttk.Combobox(input_window, values=branches_list)
branch_combobox1.pack(fill=tk.BOTH)
branch_combobox1.set("choose branch to merge")
to_label = ttk.Label(input_window, text="to")
to_label.pack(pady=5)
branch_label2 = ttk.Label(input_window, text=current_branch)
branch_label2.pack(fill=tk.BOTH)
# Create a confirmation button
selected_branch = branch_combobox1.get()
confirm_button = ttk.Button(
input_window, text="Merge", command=merge_selected_branch)
confirm_button.pack(pady=10)
def destory_merge_window():
input_window.destroy()
succec_window.destroy()
def destroy_all_merge_window():
input_window.destroy()
succec_window.destroy()
abort_succec_window.destroy()
def git_abort():
repository = pygit2.Repository(last_path)
repository.reset(repository.head.target, pygit2.GIT_RESET_HARD)
global abort_succec_window
abort_succec_window = tk.Toplevel(window)
abort_succec_window.geometry("100x150")
abort_succec_window.geometry("+700+300")
confirm_button = tk.Button(
abort_succec_window, text="확인", command=destroy_all_merge_window)
try:
repository.reset(repository.head.target, pygit2.GIT_RESET_HARD)
tmp = "abort 성공"
except pygit2.GitError as e:
tmp = "Failed to abort merge:" + e
result_label = tk.Label(abort_succec_window, text=tmp, fg="green")
result_label.pack(side="top")
confirm_button.pack(side="bottom")
def merge_selected_branch():
global succec_window
succec_window = tk.Toplevel(window)
succec_window.geometry("300x150")
succec_window.geometry("+600+300")
# 성공 여부를 표시할 Label 생성
result_label = tk.Label(succec_window, text="앙", fg="green")
result_label.pack()
button_frame = tk.Frame(succec_window)
button_frame.pack(side=tk.BOTTOM)
confirm_button = tk.Button(
button_frame, text="확인", command=destory_merge_window)
confirm_button.pack(side=tk.LEFT)
# 현재 디렉토리를 기반으로 레포지토리 열기
repo = pygit2.Repository(last_path)
# 브랜치 이름
source_branch_name = branch_combobox1.get()
target_branch_name = repo.head.shorthand
# 브랜치 가져오기
source_branch = repo.branches.get(source_branch_name)
target_branch = repo.branches.get(target_branch_name)
# 소스 브랜치의 커밋 가져오기
source_commit = repo[source_branch.target]
# 마스터 브랜치의 커밋 가져오기
target_commit = repo[target_branch.target]
# Merge 분석
result, _ = repo.merge_analysis(source_commit.id)
if result & pygit2.GIT_MERGE_ANALYSIS_UP_TO_DATE:
result_label.config(text="Already up to date")
print("Already up to date")
elif result & pygit2.GIT_MERGE_ANALYSIS_FASTFORWARD:
# Fast-forward merge
target_branch.set_target(source_commit.id)
repo.reset(source_commit.id, pygit2.GIT_RESET_HARD)
result_label.config(text= "Fast-forward merged\n" + "commit id : " + str(source_commit.id)[:7])
print("Fast-forward merge")
else:
index = repo.merge_commits(target_commit.id, source_commit.id)
conflicts = index.conflicts
if conflicts:
abort_button = tk.Button(
button_frame, text="abort", command=git_abort)
abort_button.pack(side=tk.RIGHT)
repo.merge(source_commit.id)
result_label.config(text="Conflict 발생", fg="red")
for conflict in index.conflicts:
path = conflict[0] # Conflict file path
conflict_label = tk.Label(
succec_window, text="Conflict in file: {}".format(path.path), fg="red")
conflict_label.pack() # 충돌 라벨을 윈도우에 추가
print("Conflict in file:", path)
print("File:", path)
else:
# 머지 성공 시, 머지 커밋 생성
committer = pygit2.Signature('Your Name', '[email protected]')
merge_commit = repo.create_commit(
'HEAD',
committer,
committer,
'Merge branch {} into {}'.format(
source_branch_name, target_branch_name),
index.write_tree(repo),
[target_branch.target, source_branch.target]
)
result_label.config(text= "3-way Merge success\n" + "commit id : " + str(merge_commit)[:7])
#print('Merge commit created:', merge_commit)
repo.reset(merge_commit.hex, pygit2.GIT_RESET_HARD)
# Git branch Actions
# Interface
def git_restore():
if check_git_repo(last_path):
repo = pygit2.Repository(last_path)
head_commit = repo.head.peel(pygit2.Commit)
head_tree = head_commit.tree
relative_path = get_relative_repo_path(
last_path, repo) + g_current_item
tree_entry = head_tree[relative_path]
blob_oid = tree_entry.oid
blob = repo[blob_oid]
file_content = blob.data
tmp_path = last_path + "/" + g_current_item
with open(tmp_path, "wb") as f:
f.write(file_content)
update_files(last_path)
def git_restore_staged():
if check_git_repo(last_path):
repo = pygit2.Repository(last_path)
index = repo.index
index.read()
relative_path = get_relative_repo_path(
last_path, repo) + g_current_item
index.remove(relative_path)
try:
obj = repo.revparse_single(
'HEAD').tree[relative_path] # Get object from db
index.add(pygit2.IndexEntry(relative_path,
obj.id, obj.filemode)) # Add to inde
index.write()
except KeyError:
git_rm_cached()
update_files(last_path)
def git_rm_cached():
if check_git_repo(last_path):
try:
repo = pygit2.Repository(last_path)
repo.index.remove(get_relative_repo_path(
last_path, repo) + g_current_item)
repo.index.write()
except KeyError as e:
print("Failed to remove file: ", e)
update_files(last_path)
def git_rm():
if check_git_repo(last_path):
try:
repo = pygit2.Repository(last_path)
tmp_path = last_path + "/" + g_current_item
git_rm_cached()
os.remove(tmp_path)
repo.index.write()
except Exception as e:
print("Failed to remove file: ", e)
update_files(last_path)
def git_init():
# non-bare repository init
if not check_git_repo(last_path):
pygit2.init_repository(f'{last_path}/.git', False)
update_files(last_path)
def git_add():
if check_git_repo(last_path):
repository = pygit2.Repository(last_path)
index = repository.index
if g_current_item != None:
path = get_relative_repo_path(last_path, repository) + g_current_item
else:
path = None
if path != None:
index.add(path)
else:
index.add_all()
index.write()
update_files(last_path)
def git_commit(commit_message):
if check_git_repo(last_path):
repository = pygit2.Repository(last_path)
index = repository.index
config = repository.config
for name in config.get_multivar('user.name'):
user_name = name
for email in config.get_multivar('user.email'):
user_email = email
author = pygit2.Signature(user_name, user_email)
committer = pygit2.Signature(user_name, user_email)
tree = index.write_tree()
ref = repository.head.name
parents = [repository.head.target]
repository.create_commit(
ref,
author, committer, commit_message,
tree,
parents
)
update_files(last_path)
def git_mv(new_file_name):
if check_git_repo(last_path):
repository = pygit2.Repository(last_path)
index = repository.index
old_file_name = g_current_item
old_path = f'{last_path}/{old_file_name}'
new_path = f'{last_path}/{new_file_name}'
index.remove(old_file_name)
os.rename(old_path, new_path)
index.add(new_file_name)
index.write()
update_files(last_path)
def update_file_git_status(path, file_name):
if check_git_repo(path):
repository = pygit2.Repository(path)
status = repository.status_file(file_name)
else:
return 0
return status
# cur_directory_path 현재 접근한 디렉토리정보(아마 last_path), repo 객체를 넣으면 하위폴더에 대한
# 상대 경로를 반환함. 만약 .git 폴더가 있는 폴더면 반환값은 '' 이며 하위 폴더의 경우 상대경로 + '/'를 반환
# 전달 받은 relative_path와 파일명을 결합하여 사용
def get_relative_repo_path(cur_directory_path, repo):
repo_dir = cur_directory_path
repo_dir = repo_dir[(len(repo.path) - 5):]
if not repo_dir:
return ''
else:
return repo_dir + '/'
def check_git_repo(path):
try:
# 디렉토리가 Git 저장소인지 확인 레포가 만들어지면 init 불가능
repo = pygit2.Repository(path)
except pygit2.GitError:
return False
return True
def update_git_repo(path):
try:
# 디렉토리가 Git 저장소인지 확인 레포가 만들어지면 init 불가능
repo = pygit2.Repository(path)
except pygit2.GitError:
return False, pygit2.Repository()
return True, repo
def sort_name_reverse():
global sort
global reverse
sort = "name"
if reverse == False:
reverse = True
tree.heading("#0", text=" Name ↓")
elif reverse == True:
reverse = False
tree.heading("#0", text=" Name ↑")
tree.heading("#1", text="Size")
update_files(entry.get())
def sort_size_reverse():
global sort
global reverse
sort = "size"
if reverse == False:
reverse = True
tree.heading("#1", text="Size ↓")
elif reverse == True:
reverse = False
tree.heading("#1", text="Size ↑")
tree.heading("#0", text=" Name")
update_files(entry.get())
def move_up():
global last_lower_folder
up_path = entry.get().rsplit("/" if ftp != None else slash, 1)
last_lower_folder = up_path[1]
update_files(up_path[0])
def show_hide():
global hidden
if hidden_menu.get() == 1:
hidden = True
elif hidden_menu.get() == 0:
hidden = False
update_files(entry.get())
def open_right_menu(event):
try:
right_menu.tk_popup(event.x_root, event.y_root)
finally:
right_menu.grab_release()
def scan_disks_add_buttons():
if sys.platform == "win32":
letters = string.ascii_uppercase
letter_c = 0
column = 2
for _ in range(26):
disk = letters[letter_c]
if os.path.exists(f"{disk}:{slash}"):
tk.Button(frame_b, text=disk.lower(), font=("Arial", 14), relief="flat", bg="white", fg="black",
command=lambda disk=disk: update_files(f"{disk}:{slash}")).grid(column=column, row=1)
column += 1
letter_c += 1
if sys.platform == "linux":
column = 2
os_user = home_path.rsplit(slash, 1)[1]
if os.path.exists(f"/media/{os_user}/"):
for l_disk in os.listdir(f"/media/{os_user}/"):
tk.Button(frame_b, text=l_disk[0].lower(), font=("Arial", 14), relief="flat", bg="white", fg="black",
command=lambda l_disk=l_disk: update_files(f"/media/{os_user}/{l_disk}")).grid(column=column,
row=1)
column += 1
def up_down_focus():
"""Focus item on start"""
if tree.focus() == "":
try:
item = tree.get_children()[0]
tree.selection_set(item)
tree.focus(item)
tree.see(item)
except:
pass
def select():
global g_current_item
for x in buttons:
x.config(state="normal")
try:
select_row = tree.focus()
row_data = tree.item(select_row)
g_current_item = row_data["text"]
if not tree.selection():
g_current_item = ''
for x in buttons:
if check_git_repo(last_path):
if x == add_button:
continue
else:
x.config(state="disabled")
else:
if x == init_button or x == clone_button:
continue
else:
x.config(state="disabled")
current_git_status = row_data["values"][1]
folder_status = row_data["values"][0]
if check_git_repo(last_path):
if folder_status == 'dir':
for x in buttons:
if x != add_button:
x.config(state="disabled")
else:
try:
if current_git_status == "STAGED":
for x in buttons:
if x == commit_button or x == restore_staged_button or x == rm_cached_button or x == mv_button:
continue
else:
x.config(state="disabled")
elif current_git_status == "UNMODIFIED":
for x in buttons:
if x == rm_button or x == rm_cached_button or x == mv_button or x == commit_button:
continue
else:
x.config(state="disabled")
elif current_git_status == "UNSTAGED":
for x in buttons:
if x == add_button or x == rm_button or x == rm_cached_button or x == mv_button or x == restore_button or x == commit_button:
continue
else:
x.config(state="disabled")
elif current_git_status == "UNTRACKED":
for x in buttons:
if x == add_button:
continue
else:
x.config(state="disabled")
elif current_git_status == "UNSTAGED-STAGED":
init_button.config(state="disabled")
else:
print(None)
except:
print("Invalid Git status code:", current_git_status)
else:
for x in buttons:
if x == init_button:
continue
else:
x.config(state="disabled")
except IndexError:
g_current_item = None
"""Enable some menu items"""
if len(tree.selection()) > 0:
right_menu.entryconfig("Open", state="normal")
if ftp == None:
right_menu.entryconfig("Copy", state="normal")
right_menu.entryconfig("Rename", state="normal")
right_menu.entryconfig("Delete in trash", state="normal")
if ftp != None:
right_menu.entryconfig("Copy to folder", state="normal")
def remove_selection(menu_only=False):
"""Remove selection + Disable some menu items"""
if menu_only == False:
tree.selection_remove(tree.focus())
right_menu.entryconfig("Open", state="disabled")
right_menu.entryconfig("Copy", state="disabled")
right_menu.entryconfig("Rename", state="disabled")
right_menu.entryconfig("Delete in trash", state="disabled")
if ftp != None:
right_menu.entryconfig("Copy to folder", state="disabled")
def click():
stop = False
for i in tree.selection():
path = tree.item(i)["values"][2]
if tree.item(i)["values"][0] == "dir":
if stop == False:
update_files(path)
stop = True
else:
if ftp == None:
if sys.platform == "win32":
os.startfile(path)
else:
opener = "open" if sys.platform == "darwin" else "xdg-open"
subprocess.call([opener, path])
# Operations
def new(goal: str):
try:
test = False
cancel = False
if goal == "dir":
info_text = "Enter catalog name"
elif goal == "file":
info_text = "Enter file name"
while test == False and cancel == False:
name_dir = simpledialog.askstring(
title="Files", prompt=info_text, parent=tree_frame)
if name_dir is not None:
test = True
for f in os.listdir(last_path):
if f.lower() == name_dir.lower():
test = False
info_text = "Name is taken"
else:
cancel = True
if test == True:
path = os.path.join(last_path, name_dir)
if goal == "dir":
os.mkdir(path)
elif goal == "file":
Path(path).touch()
update_files(last_path)
except Exception as e:
tk.messagebox.showerror(title="Error", message=str(e))
def copy():
list_i = []
for i in tree.selection():
path = tree.item(i)["values"][1]
if "\\" in path:
path = path.replace("\\", "/")
list_i.append(f"'{path}'")
if len(list_i) > 1:
items = ",".join(list_i)
else:
items = list_i[0]
if sys.platform == "win32":
os.system(f"powershell.exe Set-Clipboard -path {items}")
right_menu.entryconfig("Paste", state="normal")
else:
global non_win_clipboard
non_win_clipboard = items
right_menu.entryconfig("Paste", state="normal")
def paste():
if sys.platform == "win32":
clipboard = window.selection_get(
selection="CLIPBOARD").replace("/", slash).split("\n")
else:
clipboard = non_win_clipboard.replace("'", "").split(",")
for source in clipboard:
edit = source.rsplit(slash, 1)
# Search copies, create destination path
file_copies = 1
for f in os.listdir(entry.get()):
if f.lower() == edit[1].lower():
file_copies += 1
if file_copies > 1:
while True:
for f in os.listdir(entry.get()):
if f.lower() == f"({file_copies}){edit[1]}".lower():
file_copies += 1
continue
break
destination = entry.get() + slash + f"({file_copies})" + edit[1]
else:
destination = entry.get() + slash + edit[1]
# Paste
if os.path.isdir(source):
shutil.copytree(source, destination)
else:
shutil.copy2(source, destination)
update_files(entry.get())
def delete():
try:
del_list = []
for i in tree.selection():
del_path = tree.item(i)["values"][1]
if os.path.exists(del_path):
del_list.append(del_path)
answer = askyesno(
title="Files", message=f"Delete {len(tree.selection())} objects in trash?")
if answer:
for di in del_list:
send2trash(di)
except:
pass
update_files(entry.get())
def rename():
for i in tree.selection():
r_path = tree.item(i)["values"][1]
e_path = r_path.rsplit(slash, 1)
if os.path.exists(r_path):
info_text = f"Rename '{e_path[1]}'"
test = False
while test == False:
test = True
new_name = simpledialog.askstring(
title="Files", prompt=info_text, parent=tree_frame, initialvalue=e_path[1])
if new_name is not None:
for f in os.listdir(entry.get()):
if f.lower() == new_name.lower() and new_name.lower() != e_path[1].lower():
test = False
info_text = "Name is taken"
if new_name is not None and new_name.lower() != e_path[1].lower():
n_path = e_path[0] + slash + new_name
os.rename(r_path, n_path)
update_files(entry.get())
def update_files(orig_dirname: str):
def convert_size(var) -> tuple:
if type(var) == type(1):
byte_size = var
else:
byte_size = os.stat(var).st_size
if byte_size >= 1000000000000:
size = str(round(byte_size / 1000000000000, 2)) + " TB"
elif byte_size >= 1000000000:
size = str(round(byte_size / 1000000000, 2)) + " GB"
elif byte_size >= 1000000:
size = str(round(byte_size / 1000000, 2)) + " MB"
elif byte_size >= 1000:
size = str(round(byte_size / 1000, 2)) + " KB"
elif byte_size < 1000:
size = str(byte_size) + " B"
return size, byte_size
try:
global last_path
global ftp
global url_ftp
dirname = orig_dirname
# FTP
if "ftp://" in dirname:
x = dirname.split("//", 1)
if "/" in x[1]:
dirname = "/" + x[1].split("/", 1)[1]
else:
dirname = "/"
#
if ftp == None:
ftp = FTP("")
try:
if ":" in x[1]:
ftp_split = x[1].split(":", 1)
ftp.connect(ftp_split[0], int(ftp_split[1]))
url_ftp = f"ftp://{ftp_split[0]}:{ftp_split[1]}"
else:
ftp.connect(x[1])
url_ftp = f"ftp://{x[1]}"
ftp.login()
#
right_menu.add_command(
label="Copy to folder", command=copy_from_ftp, state="disable")
right_menu.entryconfig(
"Show hidden files", state="disable")
right_menu.entryconfig("New file", state="disable")
right_menu.entryconfig("New catalog", state="disable")
except:
ftp = None
url_ftp = None
else:
if ftp != None:
ftp.quit()
ftp = None
url_ftp = None
#
right_menu.delete("Copy to folder")
right_menu.entryconfig("Show hidden files", state="normal")
right_menu.entryconfig("New file", state="normal")
right_menu.entryconfig("New catalog", state="normal")
# Check path
if ftp == None and op_slash in dirname:
dirname = dirname.replace(op_slash, slash)
elif ftp != None and "\\" in dirname:
dirname = dirname.replace("\\", "/")
if re.match(r".+\\$", dirname) or re.match(r".+/$", dirname):
dirname = dirname[0:-1]
if re.match(r"\w:$", dirname) or dirname == "":
if ftp == None:
dirname = dirname + slash
else:
dirname = "/"
# Scan
files_list, dirs_list = [], []
if ftp == None:
files = os.scandir(dirname)
is_repo_exist, git_repo = update_git_repo(dirname)
for f in files:
f_stat = f.stat()
size = convert_size(f_stat.st_size)
if f.is_dir():
# 오브젝트가 폴더이면 다음과 같은 정보들을 삽입
if is_repo_exist: # if true -> cant init
git_status = 0 # status 0 of file is current state
else: # if not exist -> can init, and flag is -1
git_status = -1
if hidden == False:
if sys.platform == "win32":
if not f.is_symlink() and not bool(f_stat.st_file_attributes & stat.FILE_ATTRIBUTE_HIDDEN):
dirs_list.append(
[f.name, "dir", f.path, folder_icon_list[icon_status_dict[git_status]], 0,
git_status_dict[git_status]])
else:
if not f.name.startswith("."):
dirs_list.append(
[f.name, "dir", f.path, folder_icon_list[icon_status_dict[git_status]], 0,
git_status_dict[git_status]])
else:
if sys.platform == "win32":
if bool(f_stat.st_file_attributes & stat.FILE_ATTRIBUTE_HIDDEN):
dirs_list.append(
[f.name, "dir", f.path, folder_hidden_icon, 0, git_status_dict[git_status]])
else:
if f.is_symlink():
dirs_list.append(
[f.name, "dir", f.path, folder_hidden_icon, 0, git_status_dict[git_status]])
else:
dirs_list.append(
[f.name, "dir", f.path, folder_icon_list[icon_status_dict[git_status]], 0,
git_status_dict[git_status]])
else:
if f.name.startswith("."):
dirs_list.append(
[f.name, "dir", f.path, folder_hidden_icon, 0, git_status_dict[git_status]])
else:
dirs_list.append(
[f.name, "dir", f.path, folder_icon_list[icon_status_dict[git_status]], 0,
git_status_dict[git_status]])
if f.is_file():
# 오브젝트가 파일이면 아래와 같은 정보들을 삽입
if is_repo_exist: # if true -> cant init
repo_dir = dirname
repo_dir = repo_dir[(len(git_repo.path) - 5):]
if not repo_dir:
git_status = git_repo.status_file(f.name)
else:
git_status = git_repo.status_file(
repo_dir + '/' + f.name)
else: # if not exist -> can init, and flag is
git_status = -1
if hidden == False:
if sys.platform == "win32":
if not bool(f_stat.st_file_attributes & stat.FILE_ATTRIBUTE_HIDDEN):
files_list.append(
[f.name, size[0], f.path, file_icon, size[1], git_status_dict[git_status]])
else:
if not f.name.startswith("."):
files_list.append(
[f.name, size[0], f.path, file_icon_list[icon_status_dict[git_status]], size[1],
git_status_dict[git_status]])
else:
if sys.platform == "win32":
if bool(f_stat.st_file_attributes & stat.FILE_ATTRIBUTE_HIDDEN):
files_list.append(
[f.name, size[0], f.path, file_hidden_icon, size[1], git_status_dict[git_status]])
else:
files_list.append(
[f.name, size[0], f.path, file_icon_list[icon_status_dict[git_status]], size[1],
git_status_dict[git_status]])
else:
if f.name.startswith("."):
files_list.append(
[f.name, size[0], f.path, file_hidden_icon, size[1], git_status_dict[git_status]])
else:
files_list.append(
[f.name, size[0], f.path, file_icon_list[icon_status_dict[git_status]], size[1],
git_status_dict[git_status]])
# FTP
else:
ftp.cwd(dirname)
try:
for f in ftp.mlsd():
if f[1]["type"] == "dir":
dirs_list.append(
[f[0], "dir", f"{orig_dirname}/{f[0]}", folder_icon])
elif f[1]["type"] == "file":
size = convert_size(int(f[1]["size"]))
files_list.append(
[f[0], size[0], f"{orig_dirname}/{f[0]}", file_icon, size[1]])
except:
ftp.voidcmd('TYPE I')
for f in ftp.nlst():
try:
if "." in f and not f.startswith("."):
size = convert_size(ftp.size(f))
files_list.append(
[f, size[0], f"{orig_dirname}/{f}", file_icon, size[1]])
else:
dirs_list.append(
[f, "dir", f"{orig_dirname}/{f}", folder_icon])
except:
dirs_list.append(
[f, "dir", f"{orig_dirname}/{f}", folder_icon])
# Sorting
if sort == "size":
if reverse == False:
dirs_list.sort(key=lambda s: s[0])
files_list.sort(key=lambda s: s[4])
if reverse == True:
dirs_list.sort(key=lambda s: s[0], reverse=True)
files_list.sort(key=lambda s: s[4], reverse=True)
elif sort == "name":
if reverse == False:
dirs_list.sort(key=lambda f: f[0])
files_list.sort(key=lambda f: f[0])
elif reverse == True:
dirs_list.sort(key=lambda f: f[0], reverse=True)
files_list.sort(key=lambda f: f[0], reverse=True)
# Clean old data
for item in tree.get_children():
tree.delete(item)
entry.delete(0, "end")
# Add new data
count = 0
# [f.name, "dir", f.path, folder_icon, git_status])
for i in dirs_list:
tree.insert("", tk.END, text=i[0], values=[
f"{i[1]}", i[5], i[2]], open=False, image=i[3])
count += 1
for i in files_list:
tree.insert("", tk.END, text=i[0], values=[
f"{i[1]}", i[5], i[2]], open=False, image=i[3])
count += 1
#
if ftp == None:
last_path = dirname
entry.insert("end", dirname)
else:
last_path = ftp.pwd()
entry.insert("end", f"{url_ftp}{ftp.pwd()}")
#
label["text"] = f" {str(count)} objects"
# Set title = folder name
if ftp == None:
if re.match(r"\w:\\$", dirname):
window.title(f"Disk ({dirname[0:2]})")
elif dirname == slash:
window.title("Files")
else:
window.title(dirname.rsplit(slash, 1)[1])
else:
window.title(url_ftp)
#
remove_selection(menu_only=True)
# If clipboard on windows has a path - change button
if sys.platform == "win32" and ftp == None:
try:
if re.match(r"\w:", window.selection_get(selection="CLIPBOARD")):
right_menu.entryconfig("Paste", state="normal")
else:
right_menu.entryconfig("Paste", state="disabled")
except:
right_menu.entryconfig("Paste", state="disabled")
# Focus on the folder from which you returned
if tree.focus() == "" and last_lower_folder != None:
for item in tree.get_children():
if tree.item(item)["text"] == last_lower_folder:
tree.selection_set(item)
tree.focus(item)
tree.see(item)
break
get_branch_list()
history_graph.draw_commit_history(graph_tree, graph_canvas, last_path)
except Exception as e:
tk.messagebox.showerror(title="Error", message=str(e))
def copy_from_ftp():
path = filedialog.askdirectory()
print(path)
for i in tree.selection():
text = tree.item(i)["text"]
with open(f"{path}/{text}", "wb") as file:
ftp.retrbinary(f"RETR {text}", file.write)
file.close()
# Fix graphic on Win 10
if sys.platform == "win32" and platform.release() == "10":
from ctypes import windll
windll.shcore.SetProcessDpiAwareness(1)
# Ini config home path, showing hidden files + other variables
config = configparser.ConfigParser()
config.read("files.ini")
home_path = str(Path.home(
)) if config["USER SETTINGS"]["home_path"] == "" else config["USER SETTINGS"]["home_path"]
hidden = True if config["USER SETTINGS"]["show_hidden_files"] == "True" else False
sort = "size" if config["USER SETTINGS"]["sort"] == "size" else "name"
reverse = False
last_lower_folder = None
last_path = None
non_win_clipboard = None
slash = "\\" if sys.platform == "win32" else "/"
op_slash = "/" if sys.platform == "win32" else "\\"
ftp = None
url_ftp = None
# Window
window = tk.Tk()
window.resizable(True, True)
window.iconphoto(True, tk.PhotoImage(file="data/icon.png"))
window.minsize(width=800, height=500)
frame_left = tk.Frame(window, border=1, bg="white")
frame_left.pack(fill="both", side="left", expand=True)
frame_right = tk.Frame(window, bg="white")
frame_right.pack(fill="both", side="right")
is_forget = True
frame_up = tk.Frame(frame_left, border=1, bg="white")
frame_up.pack(fill="x", side="top")