Browse Source

Renamed to cfgs, style updates

Christoph Haas 6 months ago
parent
commit
58f51cd36b
1 changed files with 129 additions and 73 deletions
  1. 129
    73
      cfgs.py

configsync.py → cfgs.py View File

@@ -1,3 +1,5 @@
1
+#!/usr/bin/env python
2
+
1 3
 import os
2 4
 import sys
3 5
 import subprocess
@@ -10,8 +12,14 @@ import stat
10 12
 import pwd
11 13
 import grp
12 14
 
15
+
13 16
 CONFIG_SYNC_VERSION = "1.0.0"
14
-CONFIG_SYNC_FILE = "/etc/configsync.conf"
17
+CONFIG_SYNC_FILE = "/etc/cfgs.conf"
18
+
19
+
20
+# -----------------------------------------
21
+# color defintions
22
+# -----------------------------------------
15 23
 
16 24
 class bcolors:
17 25
     HEADER = '\033[95m'
@@ -23,6 +31,11 @@ class bcolors:
23 31
     BOLD = '\033[1m'
24 32
     UNDERLINE = '\033[4m'
25 33
 
34
+
35
+# -----------------------------------------
36
+# UI helper functions
37
+# -----------------------------------------
38
+
26 39
 def check_dependencies():
27 40
     status = True
28 41
     try:
@@ -34,59 +47,27 @@ def check_dependencies():
34 47
 
35 48
     return status
36 49
 
50
+
37 51
 def print_splash():
38
-    print(bcolors.HEADER + "---=== CONFIG-SYNC ===---" + bcolors.ENDC)
52
+    print(bcolors.HEADER + "---=== cfgs ===---" + bcolors.ENDC)
39 53
     print("Version: " + CONFIG_SYNC_VERSION)
40 54
     print()
41 55
     print(bcolors.HEADER + "---=== USAGE ===---" + bcolors.ENDC)
42
-    print("configsync init")
43
-    print("configsync add <file path>")
44
-    print("configsync remove <file path>")
45
-    print("configsync store")
46
-    print("configsync restore")
56
+    print("cfgs init")
57
+    print("cfgs add <file path>")
58
+    print("cfgs remove <file path>")
59
+    print("cfgs store")
60
+    print("cfgs restore")
47 61
     sys.exit(1)
48 62
 
49
-def validate_or_create_config(config):
50
-    if not os.path.exists(CONFIG_SYNC_FILE):
51
-        print(bcolors.OKBLUE + "Creating default configuration file: " + CONFIG_SYNC_FILE + bcolors.ENDC)
52
-        config['DEFAULT'] = {}
53
-        config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] = "/opt/configsync/storage"
54
-        config['DEFAULT']['INITIALIZED'] = ""
55
-        config['GIT'] = {}
56
-        config['GIT']['REMOTE_REPOSITORY'] = ""
57
-        config['GIT']['USER'] = "configsync"
58
-        config['GIT']['EMAIL'] = "configsync@" + socket.gethostname()
59
-        config['GIT']['SSHKEY'] = str(Path.home()) + "/.ssh/id_rsa"
60
-
61
-        update_config(config)
62
-    else:
63
-        config.read(CONFIG_SYNC_FILE)
64
-
65
-    return config
66
-
67
-def get_config():
68
-    config = configparser.ConfigParser()
69
-    config = validate_or_create_config(config)
70
-
71
-    return config
72
-
73
-def update_config(config):
74
-    try:
75
-        config.write(open(CONFIG_SYNC_FILE, 'w'))
76
-    except PermissionError as e:
77
-        print(bcolors.FAIL + "Unable to write config file! Error: " + e.strerror + bcolors.ENDC)
78
-        sys.exit(1)
79
-    except Exception as e:
80
-        print(bcolors.FAIL + "Unable to write config file! Error: " + str(e) + bcolors.ENDC)
81
-        sys.exit(1)
82 63
 
83 64
 def init_dialog():
84 65
     config = get_config()
85
-    print(bcolors.HEADER + "---=== Welcome to CONFIG-SYNC! ===---" + bcolors.ENDC)
66
+    print(bcolors.HEADER + "---=== Welcome to cfgs! ===---" + bcolors.ENDC)
86 67
     print()
87 68
 
88 69
     if config['DEFAULT']['INITIALIZED']:
89
-        reinitialize = input(bcolors.WARNING + "WARNING: CONFIG-SYNC has already been initialized! Do you really want to change the configuration? [y/N]: " + bcolors.ENDC)
70
+        reinitialize = input(bcolors.WARNING + "WARNING: cfgs has already been initialized! Do you really want to change the configuration? [y/N]: " + bcolors.ENDC)
90 71
         if not reinitialize or reinitialize != "y":
91 72
             print("Skipping new initialization!")
92 73
             sys.exit(0)
@@ -120,10 +101,52 @@ def init_dialog():
120 101
 
121 102
     update_config(config)
122 103
 
104
+
105
+# -----------------------------------------
106
+# local config helper functions
107
+# -----------------------------------------
108
+
109
+def validate_or_create_config(config):
110
+    if not os.path.exists(CONFIG_SYNC_FILE):
111
+        print(bcolors.OKBLUE + "Creating default configuration file: " + CONFIG_SYNC_FILE + bcolors.ENDC)
112
+        config['DEFAULT'] = {}
113
+        config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] = "/opt/cfgs/storage"
114
+        config['DEFAULT']['INITIALIZED'] = ""
115
+        config['GIT'] = {}
116
+        config['GIT']['REMOTE_REPOSITORY'] = ""
117
+        config['GIT']['USER'] = "cfgs"
118
+        config['GIT']['EMAIL'] = "cfgs@" + socket.gethostname()
119
+        config['GIT']['SSHKEY'] = str(Path.home()) + "/.ssh/id_rsa"
120
+
121
+        update_config(config)
122
+    else:
123
+        config.read(CONFIG_SYNC_FILE)
124
+
125
+    return config
126
+
127
+
128
+def get_config():
129
+    config = configparser.ConfigParser()
130
+    config = validate_or_create_config(config)
131
+
132
+    return config
133
+
134
+
135
+def update_config(config):
136
+    try:
137
+        config.write(open(CONFIG_SYNC_FILE, 'w'))
138
+    except PermissionError as e:
139
+        print(bcolors.FAIL + "Unable to write config file! Error: " + e.strerror + bcolors.ENDC)
140
+        sys.exit(1)
141
+    except Exception as e:
142
+        print(bcolors.FAIL + "Unable to write config file! Error: " + str(e) + bcolors.ENDC)
143
+        sys.exit(1)
144
+
145
+
123 146
 def create_initialization_file(path):
124 147
     try:
125
-        with open(path + "/configsync.info", mode='w') as file:
126
-            file.write('CONFIG-SYNC Repo initialized: %s.\n' % ( datetime.datetime.now()))
148
+        with open(path + "/cfgs.info", mode='w') as file:
149
+            file.write('cfgs repo initialized: %s. host: %s\n' % ( datetime.datetime.now(), socket.gethostname() ))
127 150
     except PermissionError as e:
128 151
         print(bcolors.FAIL + "Unable to write initialization file! Error: " + e.strerror + bcolors.ENDC)
129 152
         sys.exit(1)
@@ -132,7 +155,7 @@ def create_initialization_file(path):
132 155
         sys.exit(1)
133 156
 
134 157
     try:
135
-        open(path + "/configsync.db", mode='a').close()
158
+        open(path + "/cfgs.db", mode='a').close()
136 159
     except PermissionError as e:
137 160
         print(bcolors.FAIL + "Unable to write database file! Error: " + e.strerror + bcolors.ENDC)
138 161
         sys.exit(1)
@@ -140,17 +163,22 @@ def create_initialization_file(path):
140 163
         print(bcolors.FAIL + "Unable to write database file! Error: " + str(e) + bcolors.ENDC)
141 164
         sys.exit(1)
142 165
 
166
+
167
+# -----------------------------------------
168
+# local database helper functions
169
+# -----------------------------------------
170
+
143 171
 def add_file_to_db(file_path):
144 172
     config = get_config()
145 173
     try:
146 174
         insert = True
147
-        with open(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + "/configsync.db", "r+") as search:
175
+        with open(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + "/cfgs.db", "r+") as search:
148 176
             for line in search:
149 177
                 line = line.rstrip()  # remove '\n' at end of line
150 178
                 if file_path == line:
151 179
                     insert = False
152 180
         if insert:
153
-            with open(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + "/configsync.db", mode='a') as file:
181
+            with open(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + "/cfgs.db", mode='a') as file:
154 182
                 file.write('%s\n' % (file_path))
155 183
     except PermissionError as e:
156 184
         print(bcolors.FAIL + "Unable to write db file! Error: " + e.strerror + bcolors.ENDC)
@@ -159,10 +187,11 @@ def add_file_to_db(file_path):
159 187
         print(bcolors.FAIL + "Unable to write db file! Error: " + str(e) + bcolors.ENDC)
160 188
         sys.exit(1)
161 189
 
190
+
162 191
 def delete_file_from_db(file_path):
163 192
     config = get_config()
164 193
     try:
165
-        with open(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + "/configsync.db", "r+") as search:
194
+        with open(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + "/cfgs.db", "r+") as search:
166 195
             lines = search.readlines()
167 196
             search.seek(0)
168 197
             for line in lines:
@@ -176,20 +205,28 @@ def delete_file_from_db(file_path):
176 205
         print(bcolors.FAIL + "Unable to write db file! Error: " + str(e) + bcolors.ENDC)
177 206
         sys.exit(1)
178 207
 
179
-def setup_git_ssh_environment():
208
+
209
+# -----------------------------------------
210
+# git helper functions
211
+# -----------------------------------------
212
+
213
+def git_setup_ssh_environment():
180 214
     config = get_config()
181 215
 
182 216
     os.environ['GIT_SSH_COMMAND'] = "ssh -i " + config['GIT']['SSHKEY']
183 217
 
218
+
184 219
 def git_is_repo(path):
185 220
     return subprocess.call(["git", "branch"], stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL, cwd=path) == 0
186 221
 
222
+
187 223
 def git_set_author(path, user, email):
188 224
     status = subprocess.call(["git", "config", "user.name", user], stderr=subprocess.STDOUT, stdout=subprocess.DEVNULL, cwd=path) == 0
189 225
     status |= subprocess.call(["git", "config", "user.email", email], stderr=subprocess.STDOUT, stdout=subprocess.DEVNULL, cwd=path) == 0
190 226
 
191 227
     return status
192 228
 
229
+
193 230
 def git_set_upstream(path, remote_url):
194 231
     # make sure that remote origin does not exist
195 232
     status = subprocess.call(["git", "remote", "rm", "origin"], stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL, cwd=path) == 0
@@ -198,11 +235,13 @@ def git_set_upstream(path, remote_url):
198 235
 
199 236
     return status
200 237
 
238
+
201 239
 def git_init_repo(path):
202 240
     status = subprocess.call(["git", "init"], cwd=path) == 0
203 241
 
204 242
     return status
205 243
 
244
+
206 245
 def git_push(path, message = "configuration update"):
207 246
     status = subprocess.call(["git", "add", "-A"], cwd=path) == 0
208 247
     status |= subprocess.call(["git", "commit", "-a", "-m", message], cwd=path) == 0
@@ -210,11 +249,13 @@ def git_push(path, message = "configuration update"):
210 249
     
211 250
     return status
212 251
 
252
+
213 253
 def git_pull(path):
214 254
     status = subprocess.call(["git", "pull", "origin", "master"], cwd=path) == 0
215 255
     
216 256
     return status
217 257
 
258
+
218 259
 def git_check_status(status):
219 260
     config = get_config()
220 261
     if not status:
@@ -222,6 +263,11 @@ def git_check_status(status):
222 263
         print(bcolors.FAIL + "FATAL: Repository path: " + config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + bcolors.ENDC)
223 264
         sys.exit(1)
224 265
 
266
+
267
+# -----------------------------------------
268
+# main business logic
269
+# -----------------------------------------
270
+
225 271
 def init_local_repo():
226 272
     config = get_config()
227 273
 
@@ -241,15 +287,16 @@ def init_local_repo():
241 287
     git_check_status(git_set_author(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'], config['GIT']['USER'], config['GIT']['EMAIL']))
242 288
     git_check_status(git_set_upstream(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'], config['GIT']['REMOTE_REPOSITORY']))
243 289
 
244
-    setup_git_ssh_environment()
290
+    git_setup_ssh_environment()
245 291
 
246 292
     git_check_status(git_pull(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY']))
247 293
     create_initialization_file(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'])
248
-    git_check_status(git_push(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'], "configsync initialized"))
294
+    git_check_status(git_push(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'], "cfgs initialized"))
249 295
     git_check_status(git_pull(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY']))
250 296
 
251
-    print(bcolors.OKGREEN + "CONFIG-SYNC initialization successfull!" + bcolors.ENDC)
252
-    print(bcolors.OKBLUE + "You can now use CONFIG-SYNC to keep your config files up to date." + bcolors.ENDC)
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)
299
+
253 300
 
254 301
 def add_file(filepath):
255 302
     config = get_config()
@@ -259,12 +306,12 @@ def add_file(filepath):
259 306
         print(bcolors.WARNING + "Invalid file, skipping!" + bcolors.ENDC)
260 307
         sys.exit(1)
261 308
     else:
262
-        print(bcolors.OKBLUE + "Adding '" + abs_path + "' to CONFIG-SYNC..." + bcolors.ENDC)
309
+        print(bcolors.OKBLUE + "Adding '" + abs_path + "' to cfgs..." + bcolors.ENDC)
263 310
 
264 311
     local_path = config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + abs_path
265 312
 
266 313
     if os.path.exists(local_path):
267
-        print(bcolors.WARNING + "File is already registered to CONFIG-SYNC, skipping!" + bcolors.ENDC)
314
+        print(bcolors.WARNING + "File is already registered to cfgs, skipping!" + bcolors.ENDC)
268 315
         sys.exit(1)
269 316
     else:
270 317
         target_directory = os.path.abspath(os.path.join(local_path, os.pardir))
@@ -279,8 +326,8 @@ def add_file(filepath):
279 326
         file_group_name = grp.getgrgid(file_group).gr_name
280 327
 
281 328
         try:
282
-            with open(local_path + ".cfsinfo", mode='w') as file:
283
-                file.write('%s;%s;%s;%s;%s' % (file_permissions, file_owner, file_group, file_owner_name, file_group_name))
329
+            with open(local_path + ".cfgs", mode='w') as file:
330
+                file.write('%s;%s;%s;%s;%s;%s' % ( file_permissions, file_owner, file_group, file_owner_name, file_group_name, socket.gethostname() ))
284 331
         except PermissionError as e:
285 332
             print(bcolors.FAIL + "Unable to write stat file! Error: " + e.strerror + bcolors.ENDC)
286 333
             sys.exit(1)
@@ -296,8 +343,9 @@ def add_file(filepath):
296 343
 
297 344
         add_file_to_db(abs_path)
298 345
 
299
-        print(bcolors.OKGREEN + "File added to CONFIG-SYNC!" + bcolors.ENDC)
300
-        print(bcolors.OKBLUE + "Use configsync store to push the file to the remote repository!" + bcolors.ENDC)
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)
348
+
301 349
 
302 350
 def remove_file(filepath):
303 351
     config = get_config()
@@ -306,10 +354,10 @@ def remove_file(filepath):
306 354
     local_path = config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + abs_path
307 355
 
308 356
     if not os.path.exists(local_path):
309
-        print(bcolors.WARNING + "File not registered to CONFIG-SYNC, skipping!" + bcolors.ENDC)
357
+        print(bcolors.WARNING + "File not registered to cfgs, skipping!" + bcolors.ENDC)
310 358
         sys.exit(1)
311 359
     else:
312
-        print(bcolors.OKBLUE + "Removing '" + abs_path + "' from CONFIG-SYNC..." + bcolors.ENDC)
360
+        print(bcolors.OKBLUE + "Removing '" + abs_path + "' from cfgs..." + bcolors.ENDC)
313 361
 
314 362
     target_directory = os.path.abspath(os.path.join(abs_path, os.pardir))
315 363
     if not os.path.exists(target_directory):
@@ -333,25 +381,26 @@ def remove_file(filepath):
333 381
     os.chown(abs_path, file_owner, file_group)
334 382
     os.chmod(abs_path, file_permissions)
335 383
     os.remove(local_path)
336
-    os.remove(local_path + ".cfsinfo")
384
+    os.remove(local_path + ".cfgs")
337 385
 
338 386
     delete_file_from_db(abs_path)
339 387
 
340
-    print(bcolors.OKGREEN + "File removed from CONFIG-SYNC!" + bcolors.ENDC)
341
-    print(bcolors.OKBLUE + "Use configsync store to push the file to the remote repository!" + bcolors.ENDC)
342
-    
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)
390
+
391
+
343 392
 def store():
344 393
     config = get_config()
345
-    setup_git_ssh_environment()
394
+    git_setup_ssh_environment()
346 395
     git_push(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'])
347 396
 
348
-    print(bcolors.OKGREEN + "CONFIG-SYNC store successfull!" + bcolors.ENDC)
397
+    print(bcolors.OKGREEN + "cfgs store successfull!" + bcolors.ENDC)
349 398
     print(bcolors.OKBLUE + "You can now restore the configuration on your other systems." + bcolors.ENDC)
350 399
 
351 400
 
352 401
 def update_local_metadata():
353 402
     config = get_config()
354
-    with open(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + "/configsync.db", "r") as search:
403
+    with open(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + "/cfgs.db", "r") as search:
355 404
         for line in search:
356 405
             abs_path = line.rstrip()  # remove '\n' at end of line
357 406
             local_path = config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + abs_path
@@ -359,7 +408,7 @@ def update_local_metadata():
359 408
             if not os.path.exists(local_path):
360 409
                 print(bcolors.WARNING + "Invalid file in database, skipping! (" + abs_path + ")" + bcolors.ENDC)
361 410
             else:
362
-                with open(local_path + ".cfsinfo", "r") as metadata_file:
411
+                with open(local_path + ".cfgs", "r") as metadata_file:
363 412
                     metadata_string = metadata_file.readline().rstrip()
364 413
                     metadata = metadata_string.split(";")
365 414
 
@@ -369,10 +418,11 @@ def update_local_metadata():
369 418
 
370 419
                     os.chmod(local_path, file_permissions)
371 420
                     os.chown(local_path, file_owner, file_group)
372
-                    
421
+
422
+
373 423
 def restore():
374 424
     config = get_config()
375
-    setup_git_ssh_environment()
425
+    git_setup_ssh_environment()
376 426
     git_pull(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'])
377 427
 
378 428
     update_local_metadata()
@@ -382,7 +432,7 @@ def restore():
382 432
         print(bcolors.WARNING + "Skipping restore process!" + bcolors.ENDC)
383 433
         sys.exit(0)
384 434
     else:
385
-        with open(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + "/configsync.db", "r") as search:
435
+        with open(config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + "/cfgs.db", "r") as search:
386 436
             for line in search:
387 437
                 abs_path = line.rstrip()  # remove '\n' at end of line
388 438
                 local_path = config['DEFAULT']['LOCAL_STORAGE_DIRECTORY'] + abs_path
@@ -405,9 +455,14 @@ def restore():
405 455
 
406 456
                     os.chown(abs_path, file_owner, file_group, follow_symlinks=False)
407 457
 
408
-    print(bcolors.OKGREEN + "CONFIG-SYNC restore successfull!" + bcolors.ENDC)
458
+    print(bcolors.OKGREEN + "cfgs restore successfull!" + bcolors.ENDC)
409 459
     print(bcolors.OKBLUE + "Configuration files have been updated. A reboot might be required." + bcolors.ENDC)
410 460
 
461
+
462
+# -----------------------------------------
463
+# main entry point
464
+# -----------------------------------------
465
+
411 466
 def main(argv):
412 467
     if not check_dependencies():
413 468
         sys.exit(1)
@@ -437,5 +492,6 @@ def main(argv):
437 492
     else:
438 493
         print_splash()
439 494
 
495
+
440 496
 if __name__ == "__main__":
441 497
     main(sys.argv)

Loading…
Cancel
Save