Browse Source

Merge branch 'master' into 'master'

some cleanup

See merge request h44z/cfgs!1
Christoph Haas 2 months ago
parent
commit
c989927e82
1 changed files with 67 additions and 58 deletions
  1. 67
    58
      cfgs.py

+ 67
- 58
cfgs.py View File

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

Loading…
Cancel
Save