-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
updatingdata.py
2049 lines (1880 loc) · 87.4 KB
/
updatingdata.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 copy
import json
import logging
import os.path
import datetime
from dataclasses import dataclass
from time import sleep
import github
import requests
import yaml
from github import Github, Repository, Branch
from termcolor import colored, cprint
@dataclass
class Git:
g: Github
repo: Repository
branch: Branch
@dataclass
class atrt:
br_access_token: str
at_creation_time: datetime.datetime
br_refresh_token: str
rt_creation_time: datetime.datetime
atexp = datetime.timedelta(minutes=10)
rtexp = datetime.timedelta(hours=168)
@dataclass
class Cred:
git_user: str
git_token: str
br_token: str
br_email: str
br_psw: str
ats: atrt
class Dir:
repo = "scambi.org"
url_r = "scambifestival/" + repo
dbranch = "main"
cbranch = "main"
data_folder = "data/{}" # ready to be formatted
config_folder = ".pino/{}" # ready to be formatted
config_raw_url = "https://raw.githubusercontent.com/scambifestival/" + repo + "/" + cbranch + "/" + config_folder
checking_outcome = True
first_run = True
cred = Cred
arrow = colored(">>> ", "light_cyan", attrs=["bold"])
igreen = colored("ⓘ ", "green", attrs=["bold"])
ired = colored("ⓘ ", "red", attrs=["bold"])
iyallow = colored("ⓘ ", "yellow", attrs=["bold"])
icyan = colored("ⓘ ", "cyan", attrs=["bold"])
dirs = Dir
# noinspection SpellCheckingInspection
def main():
global cred
sleep(1)
cprint("\nPLEASE CHECK THE README FILE IN THE GITHUB REPO BEFORE USING THIS TOOL.\n", "red")
sleep(1)
print(icyan + "'updatingdata.py' working dirs:\n")
sleep(0.4)
print("\tRepository:\t\t" + dirs.repo)
sleep(0.4)
print("\tData Branch:\t\t" + dirs.dbranch + "\n\tData folder:\t\t" + dirs.data_folder.removesuffix("{}"))
sleep(0.4)
print("\tControl Branch:\t\t" + dirs.cbranch + "\n\tControl folder:\t\t" + dirs.config_folder.removesuffix("{}") +
"\n")
sleep(0.7)
print("----------------------------------------------------------------------------\n")
print("Hi! This is a small tool to update JSON/CSV files in the " + dirs.url_r + " repository!")
sleep(0.4)
cred = credential_gatherer()
git = github_log(user=cred.git_user, psw=cred.git_token)
tables_infos = config_getter(git, "tablesInfos.yml", None)
auto_update(tables_infos, config_getter(git, "toUpdate.yml", tables_infos), git)
print("\nProcess done. Bye!")
# noinspection PyUnboundLocalVariable
def credential_gatherer():
global first_run
print("\n" + icyan + "Gathering credentials from file...")
if os.path.isfile("gb_tokens.txt") is False:
sleep(0.5)
cprint("\nCredentials file not found. I need to create it.", "yellow")
sleep(0.5)
cprint("\n! Please note that none of those details will be shared anywhere.\n", "green")
sleep(0.5)
print("➔ What's your GitHub username?")
sleep(0.2)
user = input("\nGITHUB USERNAME " + arrow)
while True:
sleep(0.2)
ans = input("\nIs '" + user + "' correct?\n\t- Press ENTER to confirm or\n\t- Type your username again\n\n"
+ arrow)
if ans == "":
break
user = ans
sleep(0.3)
print("\nOK!\n\n➔ What's your GitHub private access token?\nNOTE:\tIt should start with 'ghp_'.\n")
sleep(0.2)
git_token = input("GITHUB TOKEN " + arrow)
sleep(0.3)
print("\nOK!\n\n➔ What's your Pino access token?\n\t- Send 'help' to see how to create a Pino token.\n")
sleep(0.2)
br_token = input("PINO TOKEN " + arrow)
if br_token.lower() == "help":
sleep(0.2)
print("\nThose are the steps to create a Pino Token:\n")
sleep(0.2)
print("\t1. Login to pino.scambi.org")
sleep(0.2)
print("\t2. Click on your name at the top left of the web page")
sleep(0.2)
print("\t3. Go to 'Token API' section")
sleep(0.2)
print("\t4. Click 'Create token +'; choose a name and select 'ScambiFestival' as Group")
sleep(0.2)
print("\t5. Be sure to give all the permissions to your private token!")
sleep(0.2)
br_token = input("\n➔ What's your Pino access token?\nPINO TOKEN " + arrow)
sleep(0.3)
print("\nOK!\n\n➔ Now I need your Pino email with which you log inside our database.")
cprint("This info is needed for Backend API requests.\n", "green")
sleep(0.2)
br_email = input("PINO EMAIL " + arrow)
while True:
if "@" not in br_email or "." not in br_email:
sleep(0.2)
print("\nPlease insert a valid email.")
br_email = input(arrow)
continue
sleep(0.2)
ans = input("\nIs '" + br_email + "' correct?\n\t- Press ENTER to confirm or\n\t- Type your email again\n\n"
+ arrow)
if ans == "":
break
br_email = ans
sleep(0.3)
print("\nOK!\n\n➔ Last thing is your Pino password.")
cprint("This info is needed for Backend API requests.\n", "green")
sleep(0.2)
br_psw = input("PINO PASSWORD " + arrow)
while True:
sleep(0.2)
ans = input(
"\nIs '" + br_psw + "' correct?\n\t- Press ENTER to confirm or\n\t- Type your password again\n"
+ arrow)
if ans == "":
break
br_psw = ans
file = open("gb_tokens.txt", "w")
file.write("first_run True\ngit_user " + user + "\ngit_token " + git_token + "\npino_token " + br_token +
"\npino_email " + br_email + "\npino_psw " + br_psw)
file.close()
print("\n➔ File created!")
else:
file = open("gb_tokens.txt", "r")
lines = file.readlines()
file.close()
if len(lines) < 6:
s = set()
t = ("first_run", "git_user", "git_token", "pino_token", "pino_email", "pino_psw")
for line in lines:
s.add(line.split(" ")[0])
for el in t:
if el not in s:
if el == "first_run":
if len(lines) == 5:
tmp_file = open("tmp.txt", "w")
tmp_file.write("first_run True\n" + "".join(lines))
tmp_file.close()
break
continue
print()
cprint("! '" + el + "' missing in 'gb_tokens.txt' file.", "red")
if not (el == "first_run" and len(lines) == 5):
cprint("Please add missing details or delete 'gb_tokens.txt' file to be guided through the process.",
"red")
exit(-3)
if os.path.isfile("tmp.txt"):
os.remove("gb_tokens.txt")
os.rename("tmp.txt", "gb_tokens.txt")
f = open("gb_tokens.txt", "r")
lines = f.readlines()
f.close()
for line in lines:
if len(line.split(" ")) != 2:
cprint("CRITICAL ERROR: 'gb_tokens.txt' WRONG FORMATTED (LINE N." + str(lines.index(line) + 1) + ").\n"
"Please correct the file in the script directory.", "red")
exit(-3)
for line in lines:
if line.startswith("first_run"):
first_run = eval(line.split(" ")[1].removesuffix("\n"))
elif line.startswith("git_user"):
user = line.split(" ")[1]
elif line.startswith("git_token"):
git_token = line.split(" ")[1]
elif line.startswith("pino_token"):
br_token = line.split(" ")[1]
elif line.startswith("pino_email"):
br_email = line.split(" ")[1]
elif line.startswith("pino_psw"):
br_psw = line.split(" ")[1]
else:
cprint("! Unknown line '" + line.removesuffix("\n") + "' in 'gb_tokens.txt' file.", "yellow")
if first_run:
file = open("gb_tokens.txt", "w")
file.write("first_run False\n" + "".join(lines[1:]))
file.close()
user = user.removesuffix("\n")
git_token = git_token.removesuffix("\n")
br_token = br_token.removesuffix("\n")
br_email = br_email.removesuffix("\n")
br_psw = br_psw.removesuffix("\n")
g = Github(user, git_token)
try:
# noinspection PyUnusedLocal
b = g.get_user().get_repos().totalCount
except github.GithubException:
cprint("\nCRITICAL ERROR: GITHUB TOKEN IS NOT CORRECT.\nPlease correct 'gb_tokens.txt' file in "
"the script directory.\n", "red")
exit(-1)
res = requests.get(url="https://pino.scambi.org/api/database/fields/table/323/",
headers={"Authorization": "Token " + br_token})
if res.status_code != 200:
cprint("\nCRITICAL ERROR: BASEROW MAY NOT BE CORRECT.\nPlease check 'gb_tokens.txt' file in "
"the script directory.\n", "red")
exit(-2)
res = requests.post(url="https://pino.scambi.org/api/user/token-auth/", data={"email": br_email,
"password": br_psw})
if res.status_code != 200:
if res.status_code == 401 and json.loads(res.content.decode("utf-8"))["error"] == "ERROR_INVALID_CREDENTIALS":
cprint("Wrong Pino email or password! Please check it in the 'gb_tokens.txt' file.", "red")
exit(-4)
if res.status_code == 400 and "Enter a valid email address." in res.content.decode("utf-8"):
cprint("Baserow backend API didn't like your email. Please check it in the 'gb_tokens.txt' file.", "red")
exit(-4)
else:
cprint("UNKNOWN ERROR occurred trying to check Pino credentials (CODE: " + str(res.status_code) + " - " +
res.reason + ")\nCheck the 'gb_tokens.txt' file.", "red")
exit(-5)
br_access_token = json.loads(res.content.decode("utf-8"))["access_token"]
atc = datetime.datetime.now()
br_refresh_token = json.loads(res.content.decode("utf-8"))["refresh_token"]
rtc = datetime.datetime.now()
return Cred(git_user=user, git_token=git_token, br_token=br_token, br_email=br_email, br_psw=br_psw,
ats=atrt(
br_access_token=br_access_token,
br_refresh_token=br_refresh_token,
at_creation_time=atc,
rt_creation_time=rtc
)
)
def github_log(user: str, psw: str):
g = Github(user, psw)
repo = g.get_repo(dirs.url_r)
git = Git(
g=g,
repo=repo,
branch=repo.get_branch(dirs.dbranch)
)
return git
def config_getter(git: Git, config_file: str, tables_infos: dict | None):
sleep(0.5)
print("\n" + icyan + "Gathering '" + config_file + "' file...")
try:
r = git.repo.get_contents(dirs.config_folder.format(config_file), ref=dirs.cbranch)
except github.GithubException as e:
cprint("ERROR: GitHub API returned an error while requesting for '" + config_file + "'"".\nError Code: " +
str(e.status), "yellow")
sleep(1)
print("\nA good engineer should always have a plan B... so let me try another way...\n")
s = requests.get(dirs.config_raw_url.format(config_file))
if not s.ok:
cprint("ERROR: '" + config_file + "' request returned an error.\nError Code: " + str(s.status_code) +
"\nReason: " + s.reason, "red")
sleep(0.3)
print("\n" + ired + "I cannot work without the '" + config_file + "' configuration file. "
"Fix the issue first.")
exit(-1)
s = s.text
else:
s = r.decoded_content.decode("utf-8")
try:
y = yaml.load(s, Loader=yaml.Loader)['tables']
except KeyError as e:
cprint("ERROR: 'tables' entry missing in '" + config_file + "' file. Check the file.\n"
+ str(e.__cause__), "red")
exit(-1)
config_checker(y, config_file, tables_infos)
sleep(0.4)
print(igreen + "'" + config_file + "' correctly loaded.")
return y
def auto_update(tables_infos: dict, toUpdate: dict, git: Git):
global checking_outcome
global first_run
d = copy.deepcopy(toUpdate)
while True:
if checking_outcome:
print("\n---------------------------------------------------------------")
sleep(0.5)
print("Those files will be processed:\n")
count = 1
formats = copy.deepcopy(d)
for item in d:
sleep(0.2)
file, ft, ftc = d[item]["file"], d[item]["format"], colored(d[item]["format"].upper(), "yellow")
if file == "" or file == " ":
text = "\t" + str(count) + ". '" + item + "." + ft.lower() + "'"
while len(text) < 19:
text += " "
text += "\t(should be created in " + ftc + " format using table w/ reference name '" + \
item + "')"
else:
text = "\t" + str(count) + ". '" + file + "'"
while len(text) < 19:
text += " "
text += "\t(should be updated in " + ftc + " format using" \
" table w/ reference name '" + item + "')"
print(text)
count += 1
sleep(0.5)
while True:
if checking_outcome:
print("\nChoose an option:")
print("\t(Y) Proceed with processing those files.")
print("\t(N/B) End the script.")
sleep(0.3)
print("\nOther options:")
print("\t(U) Refresh 'toUpdate.yml' content.")
print("\t(I) Refresh 'tablesInfos.yml' content.")
print("\t(C) Change output file(s) format.")
print("\t(S) Select which file(s) you want to update/create.")
print("\t(E) Edit 'toUpdate.yml' file.")
print("\t(T) Edit 'tablesInfos.yml' file.")
sleep(0.3)
if first_run:
cprint("\n\t(W) Change working dirs.\t! Requested feature\n", "green")
else:
print("\n\t(W) Change working dirs.\n")
uinput = input("(Y/N/B/U/I/C/S/E/T/W) " + arrow).lower()
if uinput != "y" and uinput != "n" and uinput != "c" and uinput != "s" and uinput != "e" \
and uinput != "t" and uinput != "u" and uinput != "i" and uinput != "b" and uinput != "w":
print("\nDidn't understand the answer...")
continue
break
else:
sleep(0.4)
cprint("\n! Auto Update not available (fix configuration files first, then refresh their content "
"if needed)", "yellow")
sleep(1)
print("\nChoose an option:")
print("\t(U) Refresh 'toUpdate.yml' content.")
print("\t(I) Refresh 'tablesInfos.yml' content.'")
print("\t(E) Edit 'toUpdate.yml' file.")
print("\t(T) Edit 'tablesInfos.yml' file.")
print("\t(N/B) End the script.\n")
sleep(0.3)
uinput = input("(U/I/E/T/N/B) " + arrow).lower()
if uinput != "i" and uinput != "e" and uinput != "t" and uinput != "u" and uinput != "n"\
and uinput != "b":
print("\nDidn't understand the answer...")
continue
break
if uinput == "n" or uinput == "b":
return
if uinput == "c":
# PyunboundLocalVariable: uinput non può essere 'c' se checking_outcome è False
# noinspection PyUnboundLocalVariable
d = formats_changer(d, formats)
continue
if uinput == "s":
d = selector(d, toUpdate)
continue
if uinput == "e":
o = toUpdate_editor(toUpdate, tables_infos, git)
if o is not None:
sleep(0.4)
print("\n" + igreen + "Updating script 'toUpdate.yml' data...")
sleep(1)
toUpdate_copy = config_getter(git, "toUpdate.yml", tables_infos)
if o == "+":
for el in toUpdate_copy:
if el not in toUpdate:
toUpdate[el] = toUpdate_copy[el]
d[el] = copy.deepcopy(toUpdate[el])
else:
t = copy.deepcopy(toUpdate)
for el in t:
if el not in toUpdate_copy:
del toUpdate[el]
if el in d:
del d[el]
continue
if uinput == "t":
c = copy.deepcopy(tables_infos)
tables_infos = tablesInfos_editor(toUpdate, tables_infos, git)
if tables_infos != c:
toUpdate = config_getter(git, "toUpdate.yml", tables_infos)
e = copy.deepcopy(d)
for el in e:
if el not in toUpdate:
del d[el]
if uinput == "y":
for el in toUpdate:
if el in formats and formats[el]["format"] != toUpdate[el]["format"]:
dispatcher(tables_infos, d, formats, git)
return
dispatcher(tables_infos, d, None, git)
return
if uinput == "u":
print("\n" + icyan + "Refreshing 'toUpdate.yml' configuration...")
toUpdate = config_getter(git, "toUpdate.yml", tables_infos)
continue
if uinput == "i":
print("\n" + icyan + "Refreshing 'tablesInfos.yml' configuration...")
tables_infos = config_getter(git, "tablesInfos.yml", tables_infos)
continue
if uinput == "w":
branch_changer(git)
print()
print(icyan + "Updated 'updatingdata.py' working dirs:")
sleep(0.4)
print("\tRepository:\t\t" + dirs.repo)
sleep(0.4)
print("\tData Branch:\t\t" + dirs.dbranch + "\n\tData folder: " + dirs.data_folder + "\n")
sleep(0.4)
print("\tControl Branch:\t\t" + dirs.cbranch + "\n\tControl folder: " + dirs.config_folder + "\n")
sleep(0.7)
continue
# uinput è assegnata necessariamente qualore step = 1
# noinspection PyUnboundLocalVariable
def branch_changer(git: Git):
global dirs
step = 0
while True:
if step == 0:
print("\nChoose an option:")
sleep(0.2)
print("\t(R) Change working repo\t\t\t\t\t\t\tcurrently: '" + dirs.repo + "'")
sleep(0.2)
print("\t(D) Change the branch from which I get the data files I work with\tcurrently: '" + dirs.dbranch +
"'")
sleep(0.2)
print(
"\t(C) Change the branch from which I get the configuration files\t\tcurrently: '" + dirs.cbranch + "'")
sleep(0.2)
print("\t(DC) Change both data branch and control branch (if they'll be the same)\n")
sleep(0.2)
print("Other options:")
print(
"\t(DF) Change the data files folder\t\t\t\t\tcurrently: '" + dirs.data_folder.removesuffix("{}") + "'")
sleep(0.2)
print("\t(CF) Change the configuration files folder\t\t\t\tcurrently: '" + dirs.config_folder.removesuffix(
"{}") +
"'")
sleep(0.5)
print("\n\t(B) Go back to the menu.\n")
sleep(0.3)
while True:
uinput = input("(R/D/C/DC/DF/CF/B) " + arrow).lower()
if uinput != "r" and uinput != "d" and uinput != "c" and uinput != "dc" and uinput != "df" and \
uinput != "cf" and uinput != "b":
print("Didn't get the input...")
continue
step = 1
break
elif step == 1:
if uinput == "b":
return
if uinput == "r":
while True:
repo = input("\nNew working repository (empty string to go back) " + arrow)
if not repo:
step = 0
break
try:
git.repo = git.g.get_repo("scambifestival/{}".format(repo))
except github.UnknownObjectException:
cprint("\n'" + repo + "' not found in the scambifestival profile. It may not exist or you may"
" not have the right permissions to access this repository.", "yellow")
sleep(0.5)
continue
try:
git.branch = git.repo.get_branch(dirs.dbranch)
except github.GithubException as e:
if e.status == 404:
print(iyallow + " Data branch '" + dirs.dbranch + "' not found in the new "
"working repository. Make sure to change it as well.\n")
else:
cprint("\nERROR\t An error occurred while searching for '" + branch + "' in the repo.\n"
"Error Code:\t" + str(e.status), "red")
else:
dirs.config_raw_url = ("https://raw.githubusercontent.com/scambifestival/{}/".format(repo) +
dirs.cbranch + "/" + dirs.config_folder + "/{}")
cf = dirs.config_folder.removesuffix("/{}")
df = dirs.data_folder.removesuffix("/{}")
try:
contents = git.repo.get_contents("", ref=dirs.dbranch)
check = any(content.type == "dir" and content.name == df for content in contents)
except github.GithubException as e:
cprint("ERROR while searching for '" + df + "' folder in the '" + dirs.dbranch + "' branch"
" inside the new repository.\n\tError code: " + str(e.status) + "\nMake sure to"
" check if the data folder is in the branch inside the new repo.", "yellow")
else:
if not check:
print(iyallow + " Data folder '" + df + "' not found in the '" + dirs.dbranch +
"' branch inside the new repo. Make sure to change it as well.")
try:
contents = git.repo.get_contents("", ref=dirs.cbranch)
check = any(content.type == "dir" and content.name == cf for content in contents)
except github.GithubException as e:
cprint("ERROR while searching for '" + cf + "' folder in the '" + dirs.cbranch + "' branch"
" inside the new repository.\n\tError code: " + str(e.status) + "\nMake sure to"
" check if the config folder is in the branch inside the new repo.", "yellow")
else:
if not check:
print(iyallow + " Control folder '" + cf + "' not found in the '" + dirs.cbranch +
"' branch in the new repo. Make sure to change it as well.")
dirs.url_r = "scambifestival/{}".format(repo)
dirs.repo = repo
print(igreen + "Repository changed sucessfully.")
sleep(0.2)
step = 0
break
elif uinput == "d" or uinput == "c" or uinput == "dc":
while True:
branch = input("\nNew working branch (empty string to go back) " + arrow)
if not branch:
step = 0
break
try:
git.branch = git.repo.get_branch(branch)
except github.GithubException as e:
if e.status == 404:
cprint("\n'" + branch + "' not found in the scambifestival profile.\nIt may not exist"
" or you may not have the right permissions to access this branch.", "yellow")
sleep(0.5)
else:
cprint("\nERROR\t An error occurred while searching for '" + branch + "' in the repo.\n"
"Error Code:\t" + str(e.status), "red")
continue
cf = dirs.config_folder.removesuffix("/{}")
df = dirs.data_folder.removesuffix("/{}")
if uinput == "d" or uinput == "dc":
dirs.dbranch = branch
try:
contents = git.repo.get_contents("", ref=dirs.dbranch)
check = any(content.type == "dir" and content.name == df for content in contents)
except github.GithubException as e:
cprint("ERROR while searching for '" + df + "' folder in the new data branch.\n\t"
"Error code: " + str(e.status), "red")
continue
if not check:
print(iyallow + " Data folder '" + df + "' not found in the new data branch '"
+ dirs.dbranch + "'. Make sure to change it as well.")
print(igreen + "Data branch changed sucessfully.")
if uinput == "c" or uinput == "dc":
dirs.cbranch = branch
try:
contents = git.repo.get_contents("", ref=dirs.cbranch)
check = any(content.type == "dir" and content.name == cf for content in contents)
except github.GithubException as e:
cprint("ERROR while searching for '" + cf + "' folder in the new control branch.\n\t"
"Error code: " + str(e.status), "red")
continue
if not check:
print(iyallow + " Control folder '" + cf + "' not found in the new control branch '"
+ dirs.cbranch + "'. Make sure to change it as well.")
else:
dirs.config_raw_url = ("https://raw.githubusercontent.com/scambifestival/" + dirs.repo +
"/" + dirs.cbranch + "/" + dirs.config_folder)
print(igreen + "Control branch changed sucessfully.")
step = 0
break
elif uinput == "df" or uinput == "cf":
while True:
folder = input("\nNew folder (empty string to go back) " + arrow)
if not folder:
step = 0
break
if uinput == "df":
try:
contents = git.repo.get_contents("", ref=dirs.dbranch)
check = any(content.type == "dir" and content.name == folder for content in contents)
except github.GithubException as e:
cprint("ERROR while searching for '" + folder + "' folder in the data branch.\n\t"
"Error code: " + str(e.status), "red")
continue
if not check:
print(iyallow + " New data folder '" + folder + "' not found in the data branch '" +
dirs.dbranch + "'. It may not exist or you may not have the right permissions to "
"access this folder.")
continue
dirs.data_folder = folder + "/{}"
print(igreen + " Data folder changed successfully.")
step = 0
break
elif uinput == "cf":
try:
contents = git.repo.get_contents("", ref=dirs.dbranch)
check = any(content.type == "dir" and content.name == folder for content in contents)
except github.GithubException as e:
cprint("ERROR while searching for '" + folder + "' folder in the control branch.\n\t"
"Error code: " + str(e.status), "red")
continue
if not check:
print(iyallow + " New control folder '" + folder + "' not found in the control branch '" +
dirs.cbranch + "'. It may not exist or you may not have the right permissions to "
"access this folder.")
continue
dirs.config_folder = folder + "/{}"
dirs.config_raw_url = ("https://raw.githubusercontent.com/scambifestival/" + dirs.repo + "/"
+ dirs.cbranch + "/" + dirs.config_folder)
print(igreen + " Config folder changed successfully.")
step = 0
break
def formats_changer(d: dict, formats: dict):
print()
count = 1
indexes = ["{}".format(el) for el in d]
for item in d:
sleep(0.2)
file, ft = d[item]["file"], d[item]["format"]
if file == "" or file == " ":
text = "\t" + str(count) + ". '" + item + "." + ft.lower() + "'"
else:
text = "\t" + str(count) + ". '" + file + "'"
while len(text) < 18:
text += " "
print(text + "\t➔ Output format:\t" + ft.upper() + "\t(" + item + ")")
count += 1
sleep(0.5)
while True:
print("\nSend a list of space-separated numbers.")
sleep(0.5)
print("You can also:")
sleep(0.5)
print("\t- Send (B) to go back to the main section.\n")
li = input(arrow).split(" ")
while " " in li:
li.remove(" ")
while "" in li:
li.remove("")
if len(li) == 1 and not li[0].isnumeric() and li[0].lower() != "b":
print("\nDidn't understand your input...")
sleep(0.3)
else:
break
if li[0].lower() == "b":
return d
for el in li:
i = li.index(el)
while (not el.isnumeric() and el.lower() != "b") or (el.isnumeric() and len(d) < int(el)):
if el.isnumeric() and len(d) < int(el):
cprint("\n! Number '" + el + "' was not in the list.\n", "yellow")
sleep(0.5)
print("Please type a number in the list.")
else:
cprint("\n! '" + el + "' has something wrong.\n", "yellow")
sleep(0.5)
print("Please type it again without any other char.")
sleep(0.5)
print("Other options:\n\t- Send '0' to ignore this number.\n\t- Send (B) to go back to the main section.")
el = input(arrow)
if el.lower() == "b":
return d
if int(el) == 0:
li[i] = str(0)
continue
li[i] = el
while str(0) in li:
li.remove(str(0))
print("\nApplied changes:")
for el in d:
i = indexes.index(el)
if str(i + 1) in li:
sleep(0.3)
if formats[el]["format"].lower() == "csv":
formats[el]["format"] = "JSON"
print("\t➔ '" + el + "'\tCSV ➔ JSON")
else:
formats[el]["format"] = "CSV"
print("\t➔ '" + el + "'\tJSON ➔ CSV")
sleep(0.5)
while True:
print("\nConfirm changes?\n(Y) Yes.\n(N) No.\n")
uin = input("(Y/N) " + arrow).lower()
if uin != "y" and uin != "n":
print("\nDidn't understand your input...")
else:
break
if uin == "y":
return formats
return d
def selector(d: dict, toUpdate: dict):
count = 1
print("\nHere is an ordered list of files:\n")
for el in d:
sleep(0.2)
if d[el]["file"].replace(" ", "") == "":
text = "\t" + str(count) + ". '" + el + "." + d[el]["format"].lower() + "'"
while len(text) < 18:
text += " "
print(text + "\t➔ C")
else:
text = "\t" + str(count) + ". '" + d[el]["file"] + "'"
while len(text) < 18:
text += " "
print(text + "\t➔ U (" + d[el]["format"].upper() + ")")
count += 1
indexes = ["{}".format(el) for el in d]
while True:
print("\nSend a list of space-separated numbers.")
sleep(0.5)
print("You can also:")
sleep(0.5)
print("\t- Send (B) to go back to the main section.")
sleep(0.5)
print("\t- Send (A) to select all the files from 'toUpdate.yml' file.")
sleep(0.5)
print("\n" + iyallow + "You'll be able to change formats after the selection.\n")
li = input(arrow).split(" ")
while " " in li:
li.remove(" ")
while "" in li:
li.remove("")
if len(li) == 1 and not li[0].isnumeric() and li[0].lower() != "b" and li[0].lower() != "a":
print("\nDidn't understand your input...")
sleep(0.3)
else:
break
if li[0].lower() == "b":
return d
if li[0].lower() == "a":
return toUpdate
for el in li:
i = li.index(el)
while (not el.isnumeric() and el.lower() != "b") or (el.isnumeric() and len(d) < int(el)):
if el.isnumeric() and len(d) < int(el):
cprint("\n! Number '" + el + "' was not in the list.\n", "yellow")
sleep(0.5)
print("Please type a number in the list.")
else:
cprint("\n! '" + el + "' has something wrong.\n", "yellow")
sleep(0.5)
print("Please type it again without any other char.")
sleep(0.5)
print("Other options:\n\t- Send '0' to ignore this number.\n\t- Send (B) to go back to the main section.\n")
el = input(arrow)
if el.lower() == "b":
return d
if int(el) == 0:
li[i] = str(0)
continue
li[i] = el
while str(0) in li:
li.remove(str(0))
if len(li) == 0:
print("\nNo files selected.")
return d
e = copy.deepcopy(d)
for el in d:
i = indexes.index(el)
if str(i + 1) not in li:
del e[el]
return e
def toUpdate_editor(toUpdate: dict, tables_infos: dict, git: Git):
print("\nHere's the 'toUpdate.yml' configuration:\n")
for el in toUpdate:
if len(el) < 11:
e = el + "\t"
else:
e = el
sleep(0.2)
if toUpdate[el]["file"].replace(" ", "") == "":
n = colored("-----None-----", "yellow")
print("\tKey: " + e + "\t➔\tOld File: " + n + "\tNew File Format: " + toUpdate[el]["format"])
else:
print("\tKey: " + e + "\t➔\tOld File: '" + toUpdate[el]["file"] + "'\tNew File Format: " +
toUpdate[el]["format"])
print("\nSelect a key to edit its configuration.")
sleep(0.3)
print("Other options:")
sleep(0.3)
print("\t- Send (+) to add a key (and its config.) to the file.")
sleep(0.3)
print("\t- Send (-) to remove a key (and its config.) from the file.")
sleep(0.3)
print("\t- Send (B) to go back without edit the file.\n")
sleep(0.3)
while True:
uin = input(arrow)
if len(uin) == 1 and uin != "+" and uin != "-" and uin.lower() != "b":
print("\nDidn't understand your input...")
continue
if len(uin) != 1 and uin not in toUpdate:
print("\nSelected key '" + uin + "' is not in 'toUpdate.yml'.")
continue
break
if uin.lower() == "b":
return None
if uin == "+":
add = {}
parameter = "key"
while parameter:
parameter = toUpdate_parameter_getter(add, parameter, tables_infos, toUpdate)
if parameter is None:
flag = 0
for el in tables_infos:
if el not in toUpdate:
flag = 1
break
if not flag:
return None
return toUpdate_editor(toUpdate, tables_infos, git)
d = copy.deepcopy(toUpdate)
d[add["key"]] = {}
d[add["key"]]["file"] = add["file"]
d[add["key"]]["format"] = add["format"]
toUpdate_updater(d, git, from_editor=True)
return "+"
if uin == "-":
sleep(0.3)
while True:
print("\nType the key you want to remove from the configuration file."
"\n- Send (B) to go back without changes.\n")
uin = input(arrow)
if uin.lower() != "b" and uin not in toUpdate:
sleep(0.3)
cprint("\nSelected key '" + uin + "' is not in 'toUpdate.yml'", "yellow")
sleep(0.3)
continue
break
if uin.lower() == "b":
return toUpdate_editor(toUpdate, tables_infos, git)
sleep(0.4)
print("\nSelected key:\t'" + uin + "'")
while True:
sleep(0.3)
print("\nProceed?\n\t(Y) Yes.\n\t(N) No.\n")
u = input(arrow).lower()
if u != "y" and u != "n":
sleep(0.3)
print("\nDidn't understand your input...")
break
if u == "y":
d = copy.deepcopy(toUpdate)
del d[uin]
toUpdate_updater(d, git, True)
return "-"
def toUpdate_parameter_getter(add: dict, parameter: str, tables_infos: dict, toUpdate: dict):
if parameter == "key":
add[parameter] = key_selector(tables_infos, toUpdate)
if add[parameter] is not None:
return "file"
return None
if parameter == "file":
add[parameter] = file_selector(add)
if add[parameter] is not None:
return "format"
return "key"
if parameter == "format":
add[parameter] = format_selector(add)
if add[parameter] is not None:
return False # devo usare False per terminare il ciclo
return "file"
def key_selector(tables_infos: dict, toUpdate: dict):
count = 0
print("\n" + icyan + " KEY SELECTION\n")
for el in tables_infos:
if el not in toUpdate:
if tables_infos[el]["view_id"] == 0:
view_id = "0\t(Not Specified)"
else:
view_id = str(tables_infos[el]["view_id"])
sleep(0.2)
print("\tKEY: " + el)
sleep(0.1)
print("\t\t➔ Table name:\t\t" + tables_infos[el]["name"])
sleep(0.1)
print("\t\t➔ Table ID:\t\t" + str(tables_infos[el]["id"]))
sleep(0.1)
print("\t\t➔ View ID:\t\t" + view_id)
sleep(0.1)
print("\t\t➔ Included columns:\t" + tables_infos[el]["included"])
sleep(0.1)
if tables_infos[el]["filters"].replace(" ", "") == "":
print("\t\t➔ Filters:\t\tNo additional filters applied.")
else:
count = 1
print("\t\t➔ Filters:\t\tAddiotional Filters:")
for el1 in tables_infos[el]["filters"].split(","):
el1.replace(" ", "")
print("\t\t\t\t\t\t" + str(count) + ". " + el1)
count += 1
print()
count += 1
if count == 0:
print("\n" + iyallow + "All available tables had been added to 'toUpdate.yml'.")
sleep(0.3)
print("First, add your tables on 'tablesInfos.yml' using (T) funcion on the main menu, than you'll be able to "
"add them to 'toUpdate.yml'")
return None
sleep(0.5)
while True: