Browse Source

Refactor color handling into some functions

Markus Mittendrein 3 months ago
parent
commit
d4b08cba0e
1 changed files with 57 additions and 49 deletions
  1. 57
    49
      cfgs.py

+ 57
- 49
cfgs.py View File

@@ -36,23 +36,31 @@ class bcolors:
36 36
 # UI helper functions
37 37
 # -----------------------------------------
38 38
 
39
+def color_message(color, message, colorend=bcolors.ENDC, bold=False):
40
+    if bold:
41
+        return bcolors.BOLD + color_message(color, message, colorend, False)
42
+
43
+    return color + message + colorend
44
+
45
+def print_color(color, message, colorend=bcolors.ENDC, bold=False):
46
+    print(color_message(color, message, colorend))
47
+
39 48
 def check_dependencies():
40 49
     status = True
41 50
     try:
42 51
         subprocess.call(["git", "version"], stdout=subprocess.DEVNULL)
43 52
     except OSError:
44 53
         status = False
45
-        print(bcolors.FAIL + "git cannot be found on your system!" + bcolors.ENDC)
54
+        print_color(bcolors.FAIL, "git cannot be found on your system!")
46 55
         print("Install git: pacman -S git")
47 56
 
48 57
     return status
49 58
 
50
-
51 59
 def print_splash():
52
-    print(bcolors.HEADER + "---=== cfgs ===---" + bcolors.ENDC)
60
+    print_color(bcolors.HEADER, "---=== cfgs ===---")
53 61
     print("Version: " + CONFIG_SYNC_VERSION)
54 62
     print()
55
-    print(bcolors.HEADER + "---=== USAGE ===---" + bcolors.ENDC)
63
+    print_color(bcolors.HEADER, "---=== USAGE ===---")
56 64
     print("cfgs init")
57 65
     print("cfgs add <file path>")
58 66
     print("cfgs remove <file path>")
@@ -63,36 +71,36 @@ def print_splash():
63 71
 
64 72
 def init_dialog():
65 73
     config = get_config()
66
-    print(bcolors.HEADER + "---=== Welcome to cfgs! ===---" + bcolors.ENDC)
74
+    print_color(bcolors.HEADER, "---=== Welcome to cfgs! ===---")
67 75
     print()
68 76
 
69 77
     if config['DEFAULT']['INITIALIZED']:
70
-        reinitialize = input(bcolors.WARNING + "WARNING: cfgs has already been initialized! Do you really want to change the configuration? [y/N]: " + bcolors.ENDC)
78
+        reinitialize = input(color_message(bcolors.WARNING, "WARNING: cfgs has already been initialized! Do you really want to change the configuration? [y/N]: "))
71 79
         if not reinitialize or reinitialize != "y":
72 80
             print("Skipping new initialization!")
73 81
             sys.exit(0)
74 82
 
75
-    local_path = input(bcolors.OKBLUE + "Enter the local storage directory for configuration files [" + config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + "]: " + bcolors.ENDC)
83
+    local_path = input(color_message(bcolors.OKBLUE, "Enter the local storage directory for configuration files [" + config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + "]: "))
76 84
     if not local_path:
77 85
         local_path = config['DEFAULT']['LOCAL_STORAGE_DIRECTORY']
78 86
     config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] = local_path
79 87
 
80
-    remote_repo = input(bcolors.OKBLUE + "Enter the remote repository url [" + config['GIT']['REMOTE_REPOSITORY'] + "]: " + bcolors.ENDC)
88
+    remote_repo = input(color_message(bcolors.OKBLUE, "Enter the remote repository url [" + config['GIT']['REMOTE_REPOSITORY'] + "]: "))
81 89
     if not remote_repo:
82 90
         remote_repo = config['GIT']['REMOTE_REPOSITORY']
83 91
     config['GIT']['REMOTE_REPOSITORY'] = remote_repo
84 92
 
85
-    git_ssh_key = input(bcolors.OKBLUE + "Enter the path to the ssh key to use [" + config['GIT']['SSHKEY'] + "]: " + bcolors.ENDC)
93
+    git_ssh_key = input(color_message(bcolors.OKBLUE, "Enter the path to the ssh key to use [" + config['GIT']['SSHKEY'] + "]: "))
86 94
     if not git_ssh_key:
87 95
         git_ssh_key = config['GIT']['SSHKEY']
88 96
     config['GIT']['SSHKEY'] = git_ssh_key
89 97
 
90
-    git_user = input(bcolors.OKBLUE + "Enter the git user name (displayname) [" + config['GIT']['USER'] + "]: " + bcolors.ENDC)
98
+    git_user = input(color_message(bcolors.OKBLUE, "Enter the git user name (displayname) [" + config['GIT']['USER'] + "]: "))
91 99
     if not git_user:
92 100
         git_user = config['GIT']['USER']
93 101
     config['GIT']['USER'] = git_user
94 102
 
95
-    git_email = input(bcolors.OKBLUE + "Enter the git user email address [" + config['GIT']['EMAIL'] + "]: " + bcolors.ENDC)
103
+    git_email = input(color_message(bcolors.OKBLUE, "Enter the git user email address [" + config['GIT']['EMAIL'] + "]: "))
96 104
     if not git_email:
97 105
         git_email = config['GIT']['EMAIL']
98 106
     config['GIT']['EMAIL'] = git_email
@@ -108,7 +116,7 @@ def init_dialog():
108 116
 
109 117
 def validate_or_create_config(config):
110 118
     if not os.path.exists(CONFIG_SYNC_FILE):
111
-        print(bcolors.OKBLUE + "Creating default configuration file: " + CONFIG_SYNC_FILE + bcolors.ENDC)
119
+        print_color(bcolors.OKBLUE, "Creating default configuration file: " + CONFIG_SYNC_FILE)
112 120
         config['DEFAULT'] = {}
113 121
         config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] = "/opt/cfgs/storage"
114 122
         config['DEFAULT']['INITIALIZED'] = ""
@@ -136,10 +144,10 @@ def update_config(config):
136 144
     try:
137 145
         config.write(open(CONFIG_SYNC_FILE, 'w'))
138 146
     except PermissionError as e:
139
-        print(bcolors.FAIL + "Unable to write config file! Error: " + e.strerror + bcolors.ENDC)
147
+        print_color(bcolors.FAIL, "Unable to write config file! Error: " + e.strerror)
140 148
         sys.exit(1)
141 149
     except Exception as e:
142
-        print(bcolors.FAIL + "Unable to write config file! Error: " + str(e) + bcolors.ENDC)
150
+        print_color(bcolors.FAIL, "Unable to write config file! Error: " + str(e))
143 151
         sys.exit(1)
144 152
 
145 153
 
@@ -148,19 +156,19 @@ def create_initialization_file(path):
148 156
         with open(path + "/cfgs.info", mode='w') as file:
149 157
             file.write('cfgs repo initialized: %s. host: %s\n' % ( datetime.datetime.now(), socket.gethostname() ))
150 158
     except PermissionError as e:
151
-        print(bcolors.FAIL + "Unable to write initialization file! Error: " + e.strerror + bcolors.ENDC)
159
+        print_color(bcolors.FAIL, "Unable to write initialization file! Error: " + e.strerror)
152 160
         sys.exit(1)
153 161
     except Exception as e:
154
-        print(bcolors.FAIL + "Unable to write initialization file! Error: " + str(e) + bcolors.ENDC)
162
+        print_color(bcolors.FAIL, "Unable to write initialization file! Error: " + str(e))
155 163
         sys.exit(1)
156 164
 
157 165
     try:
158 166
         open(path + "/cfgs.db", mode='a').close()
159 167
     except PermissionError as e:
160
-        print(bcolors.FAIL + "Unable to write database file! Error: " + e.strerror + bcolors.ENDC)
168
+        print_color(bcolors.FAIL, "Unable to write database file! Error: " + e.strerror)
161 169
         sys.exit(1)
162 170
     except Exception as e:
163
-        print(bcolors.FAIL + "Unable to write database file! Error: " + str(e) + bcolors.ENDC)
171
+        print_color(bcolors.FAIL, "Unable to write database file! Error: " + str(e))
164 172
         sys.exit(1)
165 173
 
166 174
 
@@ -181,10 +189,10 @@ def add_file_to_db(file_path):
181 189
             with open(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + "/cfgs.db", mode='a') as file:
182 190
                 file.write('%s\n' % (file_path))
183 191
     except PermissionError as e:
184
-        print(bcolors.FAIL + "Unable to write db file! Error: " + e.strerror + bcolors.ENDC)
192
+        print_color(bcolors.FAIL, "Unable to write db file! Error: " + e.strerror)
185 193
         sys.exit(1)
186 194
     except Exception as e:
187
-        print(bcolors.FAIL + "Unable to write db file! Error: " + str(e) + bcolors.ENDC)
195
+        print_color(bcolors.FAIL, "Unable to write db file! Error: " + str(e))
188 196
         sys.exit(1)
189 197
 
190 198
 
@@ -199,10 +207,10 @@ def delete_file_from_db(file_path):
199 207
                     search.write(line.rstrip() + "\n")
200 208
             search.truncate()
201 209
     except PermissionError as e:
202
-        print(bcolors.FAIL + "Unable to write db file! Error: " + e.strerror + bcolors.ENDC)
210
+        print_color(bcolors.FAIL, "Unable to write db file! Error: " + e.strerror)
203 211
         sys.exit(1)
204 212
     except Exception as e:
205
-        print(bcolors.FAIL + "Unable to write db file! Error: " + str(e) + bcolors.ENDC)
213
+        print_color(bcolors.FAIL, "Unable to write db file! Error: " + str(e))
206 214
         sys.exit(1)
207 215
 
208 216
 
@@ -259,8 +267,8 @@ def git_pull(path):
259 267
 def git_check_status(status):
260 268
     config = get_config()
261 269
     if not status:
262
-        print(bcolors.FAIL + bcolors.BOLD + "FATAL: Git operation failed! Repository has to be recovered manually!" + bcolors.ENDC)
263
-        print(bcolors.FAIL + "FATAL: Repository path: " + config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + bcolors.ENDC)
270
+        print_color(bcolors.FAIL, "FATAL: Git operation failed! Repository has to be recovered manually!", bold=True)
271
+        print_color(bcolors.FAIL, "FATAL: Repository path: " + config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'])
264 272
         sys.exit(1)
265 273
 
266 274
 
@@ -273,11 +281,11 @@ def init_local_repo():
273 281
 
274 282
     print("Setting up local repository.")
275 283
     if not os.path.exists(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY']):
276
-        print(bcolors.OKBLUE + "Creating new directory: " + config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + bcolors.ENDC)
284
+        print_color(bcolors.OKBLUE, "Creating new directory: " + config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'])
277 285
         try:
278 286
             os.makedirs(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'])
279 287
         except OSError as e:
280
-            print(bcolors.FAIL + "Failed to create local repository directory: " + e.strerror + bcolors.ENDC)
288
+            print_color(bcolors.FAIL, "Failed to create local repository directory: " + e.strerror)
281 289
             sys.exit(1)
282 290
 
283 291
     # init git repo
@@ -294,8 +302,8 @@ def init_local_repo():
294 302
     git_check_status(git_push(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'], "cfgs initialized"))
295 303
     git_check_status(git_pull(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY']))
296 304
 
297
-    print(bcolors.OKGREEN + "cfgs initialization successfull!" + bcolors.ENDC)
298
-    print(bcolors.OKBLUE + "You can now use cfgs to keep your config files up to date." + bcolors.ENDC)
305
+    print_color(bcolors.OKGREEN, "cfgs initialization successfull!")
306
+    print_color(bcolors.OKBLUE, "You can now use cfgs to keep your config files up to date.")
299 307
 
300 308
 
301 309
 def add_file(filepath):
@@ -303,15 +311,15 @@ def add_file(filepath):
303 311
     abs_path = os.path.abspath(filepath)
304 312
 
305 313
     if not os.path.exists(abs_path):
306
-        print(bcolors.WARNING + "Invalid file, skipping!" + bcolors.ENDC)
314
+        print_color(bcolors.WARNING, "Invalid file, skipping!")
307 315
         sys.exit(1)
308 316
     else:
309
-        print(bcolors.OKBLUE + "Adding '" + abs_path + "' to cfgs..." + bcolors.ENDC)
317
+        print_color(bcolors.OKBLUE, "Adding '" + abs_path + "' to cfgs...")
310 318
 
311 319
     local_path = config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + abs_path
312 320
 
313 321
     if os.path.exists(local_path):
314
-        print(bcolors.WARNING + "File is already registered to cfgs, skipping!" + bcolors.ENDC)
322
+        print_color(bcolors.WARNING, "File is already registered to cfgs, skipping!")
315 323
         sys.exit(1)
316 324
     else:
317 325
         target_directory = os.path.abspath(os.path.join(local_path, os.pardir))
@@ -329,10 +337,10 @@ def add_file(filepath):
329 337
             with open(local_path + ".cfgs", mode='w') as file:
330 338
                 file.write('%s;%s;%s;%s;%s;%s' % ( file_permissions, file_owner, file_group, file_owner_name, file_group_name, socket.gethostname() ))
331 339
         except PermissionError as e:
332
-            print(bcolors.FAIL + "Unable to write stat file! Error: " + e.strerror + bcolors.ENDC)
340
+            print_color(bcolors.FAIL, "Unable to write stat file! Error: " + e.strerror)
333 341
             sys.exit(1)
334 342
         except Exception as e:
335
-            print(bcolors.FAIL + "Unable to write stat file! Error: " + str(e) + bcolors.ENDC)
343
+            print_color(bcolors.FAIL, "Unable to write stat file! Error: " + str(e))
336 344
             sys.exit(1)
337 345
 
338 346
         shutil.copy2(abs_path, local_path)
@@ -343,8 +351,8 @@ def add_file(filepath):
343 351
 
344 352
         add_file_to_db(abs_path)
345 353
 
346
-        print(bcolors.OKGREEN + "File added to cfgs!" + bcolors.ENDC)
347
-        print(bcolors.OKBLUE + "Use cfgs store to push the file to the remote repository!" + bcolors.ENDC)
354
+        print_color(bcolors.OKGREEN, "File added to cfgs!")
355
+        print_color(bcolors.OKBLUE, "Use cfgs store to push the file to the remote repository!")
348 356
 
349 357
 
350 358
 def remove_file(filepath):
@@ -354,19 +362,19 @@ def remove_file(filepath):
354 362
     local_path = config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + abs_path
355 363
 
356 364
     if not os.path.exists(local_path):
357
-        print(bcolors.WARNING + "File not registered to cfgs, skipping!" + bcolors.ENDC)
365
+        print_color(bcolors.WARNING, "File not registered to cfgs, skipping!")
358 366
         sys.exit(1)
359 367
     else:
360
-        print(bcolors.OKBLUE + "Removing '" + abs_path + "' from cfgs..." + bcolors.ENDC)
368
+        print_color(bcolors.OKBLUE, "Removing '" + abs_path + "' from cfgs...")
361 369
 
362 370
     target_directory = os.path.abspath(os.path.join(abs_path, os.pardir))
363 371
     if not os.path.exists(target_directory):
364 372
         os.makedirs(target_directory)
365 373
 
366 374
     if os.path.exists(abs_path):
367
-        confirmed = input(bcolors.OKBLUE + "Do you really want to override the local file '" + abs_path + "'? [y/N]: " + bcolors.ENDC)
375
+        confirmed = input(color_message(bcolors.OKBLUE, "Do you really want to override the local file '" + abs_path + "'? [y/N]: "))
368 376
         if not confirmed or confirmed != "y":
369
-            print(bcolors.WARNING + "Skipping removal process!" + bcolors.ENDC)
377
+            print_color(bcolors.WARNING, "Skipping removal process!")
370 378
             sys.exit(0)
371 379
         else:
372 380
             os.remove(abs_path)
@@ -385,8 +393,8 @@ def remove_file(filepath):
385 393
 
386 394
     delete_file_from_db(abs_path)
387 395
 
388
-    print(bcolors.OKGREEN + "File removed from cfgs!" + bcolors.ENDC)
389
-    print(bcolors.OKBLUE + "Use cfgs store to push the file to the remote repository!" + bcolors.ENDC)
396
+    print_color(bcolors.OKGREEN, "File removed from cfgs!")
397
+    print_color(bcolors.OKBLUE, "Use cfgs store to push the file to the remote repository!")
390 398
 
391 399
 
392 400
 def store():
@@ -394,8 +402,8 @@ def store():
394 402
     git_setup_ssh_environment()
395 403
     git_push(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'])
396 404
 
397
-    print(bcolors.OKGREEN + "cfgs store successfull!" + bcolors.ENDC)
398
-    print(bcolors.OKBLUE + "You can now restore the configuration on your other systems." + bcolors.ENDC)
405
+    print_color(bcolors.OKGREEN, "cfgs store successfull!")
406
+    print_color(bcolors.OKBLUE, "You can now restore the configuration on your other systems.")
399 407
 
400 408
 
401 409
 def update_local_metadata():
@@ -406,7 +414,7 @@ def update_local_metadata():
406 414
             local_path = config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + abs_path
407 415
 
408 416
             if not os.path.exists(local_path):
409
-                print(bcolors.WARNING + "Invalid file in database, skipping! (" + abs_path + ")" + bcolors.ENDC)
417
+                print_color(bcolors.WARNING, "Invalid file in database, skipping! (" + abs_path + ")")
410 418
             else:
411 419
                 with open(local_path + ".cfgs", "r") as metadata_file:
412 420
                     metadata_string = metadata_file.readline().rstrip()
@@ -427,9 +435,9 @@ def restore():
427 435
 
428 436
     update_local_metadata()
429 437
 
430
-    confirmed = input(bcolors.WARNING + "Do you really want to restore files from the repository? Local files will be overwritten! [y/N]: " + bcolors.ENDC)
438
+    confirmed = input(color_message(bcolors.WARNING, "Do you really want to restore files from the repository? Local files will be overwritten! [y/N]: "))
431 439
     if not confirmed or confirmed != "y":
432
-        print(bcolors.WARNING + "Skipping restore process!" + bcolors.ENDC)
440
+        print_color(bcolors.WARNING, "Skipping restore process!")
433 441
         sys.exit(0)
434 442
     else:
435 443
         with open(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + "/cfgs.db", "r") as search:
@@ -438,7 +446,7 @@ def restore():
438 446
                 local_path = config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + abs_path
439 447
 
440 448
                 if not os.path.exists(local_path):
441
-                    print(bcolors.WARNING + "Invalid file, skipping!" + bcolors.ENDC)
449
+                    print_color(bcolors.WARNING, "Invalid file, skipping!")
442 450
                 else:
443 451
                     target_directory = os.path.abspath(os.path.join(abs_path, os.pardir))
444 452
                     if not os.path.exists(target_directory):
@@ -455,8 +463,8 @@ def restore():
455 463
 
456 464
                     os.chown(abs_path, file_owner, file_group, follow_symlinks=False)
457 465
 
458
-    print(bcolors.OKGREEN + "cfgs restore successfull!" + bcolors.ENDC)
459
-    print(bcolors.OKBLUE + "Configuration files have been updated. A reboot might be required." + bcolors.ENDC)
466
+    print_color(bcolors.OKGREEN, "cfgs restore successfull!")
467
+    print_color(bcolors.OKBLUE, "Configuration files have been updated. A reboot might be required.")
460 468
 
461 469
 
462 470
 # -----------------------------------------

Loading…
Cancel
Save