-
Notifications
You must be signed in to change notification settings - Fork 1
/
web_update.py
366 lines (223 loc) · 8.58 KB
/
web_update.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
""" I had some trouble trying to update my website source code on the server with github WHILE keeping
some local files / content / DB etc files, so the point of this script is to keep specific local files,
and then download the latest source code from github, and move the local files back into the source code.
"""
import os
import json
import time
import shutil
import logging
import random
from git import Repo, rmtree
from dotenv import load_dotenv
load_dotenv()
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', )
# These file are kept between updates.
# They get removed from the main repo, and re-added after git clone.
# use a relative path to the specific file or directory.
KEEP_FILES = [
".env",
"db.sqlite3",
"media",
# "venv",
"home/static/images",
"mysite/settings.py",
"mysite/static/font-awesome",
"mysite/static/images",
"game/static/models",
"game/static/three",
"game/static/textures"
]
VERSIONS = False # Currently no function for this.
BACKUP_FILES = [
".env",
"db.sqlite3",
"mysite/settings.py",
]
# BRANCH = "master"
GITHUB_REPO = "https://github.com/LouisRossouw/portfolio_website.git"
TOOLNAME = "web_updater"
LOCAL_REPO = "/home/Kpow636/louisrossouw_env/portfolio_website"
BACKUP_DIR = "/home/Kpow636/louisrossouw_env/"
UPDATER_DIR = os.path.join(BACKUP_DIR, TOOLNAME)
def perform_backup():
""" Performs a simple backup for the backup_files list. """
logging.info("Backup True.")
for f in BACKUP_FILES:
src = f"{LOCAL_REPO}/{f}"
dst = f"{UPDATER_DIR}/backup"
dir_exists = check_dirs(dst)
logging.info(f"Backing up: -- {f}")
if dir_exists:
try:
shutil.copy(src, dst)
except FileNotFoundError:
logging.warning(f" ** {f} - File does not exist.")
def write_to_json(json_path, data):
""" Create and write to json file. """
logging.info("Writing json data.")
with open(json_path, 'w') as f:
json.dump(data, f, indent=6)
def read_json(json_path):
""" Reads json file """
logging.info("Reading json data.")
with open(json_path) as f:
json_file = json.loads(f.read())
return (json_file)
def check_dirs(destination_path):
""" Makes destination dir if does not exist. """
logging.info("Checking if tmp directory exists.")
if os.path.exists(destination_path) != True:
logging.info("Tmp does not exist - making directory.")
os.mkdir(destination_path)
return True
def is_dir(file_path):
""" Checks if the source file is a directory. """
return os.path.isdir(file_path)
def execute_shutil(source_path,
destination_path,
is_directory, file, generate_id):
""" copies out files """
f_name = os.path.basename(source_path)
ID_DIR = f"{destination_path}/{generate_id}"
if os.path.exists(source_path):
if is_directory:
if os.path.exists(ID_DIR) == False:
os.mkdir(ID_DIR)
logging.info(f"Copying: {f_name} directory, to /" + TOOLNAME)
shutil.move(src=str(source_path),
dst=str(f"{destination_path}/{generate_id}/{f_name}"))
else:
if os.path.exists(ID_DIR) == False:
os.mkdir(ID_DIR)
logging.info(f"Copying: {file} file, to /" + TOOLNAME)
shutil.move(src=str(source_path),
dst=str(f"{destination_path}/{generate_id}/{f_name}"))
else:
logging.warning(f"{file} - does not exist. skipping.")
def record_data(data, file_source,
file_destination, is_directory, generate_id,):
""" Records the copied files path into a .json file,
so it can easily move it back to where they came from. """
file_name = os.path.basename(file_source)
data[str(generate_id) + "|" + file_name] = {
"file_name": os.path.basename(file_source),
"file_source": file_source,
"file_destination": file_destination,
"is_dir": is_directory,
"ID": generate_id,
}
return data
def perform_update_copy():
""" copies files to external directory and writes out a json
file of the data so that we can do the reverse option. """
data = {}
if check_dirs(UPDATER_DIR) == True:
for file in KEEP_FILES:
file_source = f"{LOCAL_REPO}/{file}"
file_destination = f"{UPDATER_DIR}"
is_directory = is_dir(file_source)
generate_id = random.randint(1000, 10000)
data = record_data(data, file_source,
file_destination, is_directory, generate_id)
execute_shutil(
file_source,
file_destination,
is_directory,
file,
generate_id
)
write_to_json(f"{file_destination}/data.json", data)
def clear_directory():
""" clears out the websites directory before doing a git pull. """
logging.info("Clearing out Directory.")
for f in os.listdir(LOCAL_REPO):
file_path = f"{LOCAL_REPO}/{f}"
logging.info(f"Removing: {f} - from: {os.path.basename(LOCAL_REPO)}")
try:
if is_dir(file_path):
rmtree(f"{LOCAL_REPO}/{f}")
else:
os.remove(f"{LOCAL_REPO}/{f}")
except PermissionError:
logging.warning(f"Failed to remove: {f}")
def clone_git(BRANCH):
""" Creates a nice fresh clone from GitHub repository. """
Repo.clone_from(GITHUB_REPO,
LOCAL_REPO,
branch=BRANCH)
def move_files_back():
""" Copies files back into repository. """
data = read_json(f"{UPDATER_DIR}/data.json")
for d in data:
file_destination = data[d]["file_destination"]
file_source = data[d]["file_source"]
ID = data[d]["ID"]
file_name = data[d]["file_name"]
src = f"{file_destination}/{str(ID)}/{file_name}"
dst = f"{os.path.dirname(file_source)}/{file_name}"
# The os.shutil func cant replace directories, instead it places the moved dir
# into the directory it was supposed to overwrite, so this func removes the dir first.
if is_dir(dst):
logging.info(f" ** {dst} is a directory - Removing first and then replacing.")
rmtree(dst)
time.sleep(1)
logging.info(f" -- moving: {d} - to: {dst}")
try:
shutil.move(src=src, dst=dst)
except FileNotFoundError:
logging.warning(f"{d} - does not exist. skipping.")
def final_cleanup():
""" Remove ID dirs left over after the update. """
data = read_json(f"{UPDATER_DIR}/data.json")
for d in data:
ID = str((data[d]["ID"]))
try:
rmtree(os.path.join(UPDATER_DIR, ID))
except FileNotFoundError:
logging.warning(f" ** {d} -- file not found, ignoring removal.")
def run_update():
""" Runs the update procedure. """
BRANCH = input("Select a branch to pull from? ex: 'master' or 'v01 .. v02' etc.. :")
update = input("Run update - [ y / n ]?")
line_length = 100
if update.lower() == "y":
to_backup = input("Backup - [ y / n ]?")
check_dirs(UPDATER_DIR)
logging.info("Starting Update")
logging.info(("-")*line_length)
if to_backup.lower() == "y":
perform_backup()
logging.info("Copying important local files to /" + TOOLNAME)
perform_update_copy()
logging.info(("-")*line_length)
logging.info("Copying complete.")
time.sleep(2)
logging.info(("-")*line_length)
clear_directory()
logging.info(("-")*line_length)
logging.info("Clearing complete.")
time.sleep(2)
logging.info(("-")*line_length)
logging.info(f"Creating a fresh clone from {GITHUB_REPO} -- {BRANCH}")
clone_git(BRANCH)
for f in os.listdir(LOCAL_REPO):
logging.info(f" -- {f}")
logging.info(("-")*100)
logging.info("Clone complete.")
time.sleep(2)
move_files_back()
final_cleanup()
logging.info("Cleaning.")
logging.info(("-")*line_length)
logging.info("Update complete.")
input()
else:
exit()
if __name__ == "__main__":
try:
run_update()
except Exception as e:
logging.error(e)
input()