-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathBlenderUpdaterCLI.py
349 lines (304 loc) · 10.6 KB
/
BlenderUpdaterCLI.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
"""
Overmind Studios BlenderUpdaterCLI - update Blender to latest buildbot version
Copyright (C) 2018-2022 by Tobias Kummer for Overmind Studios
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from colorama import init, Fore
from progress.bar import IncrementalBar
from packaging import version
import json
import argparse
import configparser
import os
import platform
import re
import requests
import shutil
import subprocess
import sys
import threading
import time
appversion = "v1.7.1"
init(autoreset=True) # enable Colorama autoreset
failed = False
url = "https://builder.blender.org/download/daily/"
config = configparser.ConfigParser()
updateurl = (
"https://api.github.com/repos/overmindstudios/BlenderUpdaterCLI/releases/latest"
)
tempDir = "./blendertemp/"
class Spinner:
busy = False
delay = 0.1
@staticmethod
def spinning_cursor():
while 1:
for cursor in "|/-\\":
yield cursor
def __init__(self, title, delay=None):
self.spinner_generator = self.spinning_cursor()
if delay and float(delay):
self.delay = delay
self.title = title
def spinner_task(self):
while self.busy:
sys.stdout.write(self.title + next(self.spinner_generator))
sys.stdout.flush()
time.sleep(self.delay)
sys.stdout.write("\b" * (len(self.title) + 1))
sys.stdout.flush()
def start(self):
self.busy = True
threading.Thread(target=self.spinner_task).start()
def stop(self):
self.busy = False
time.sleep(self.delay)
parser = argparse.ArgumentParser(
description="Update Blender to latest nightly build. (c) 2018-2021 by Tobias Kummer/Overmind Studios.",
epilog="example usage: BlenderUpdaterCLI -b 2.93.2 -p C:\\Blender",
)
parser.add_argument("-p", "--path", help="Destination path", required=True, type=str)
parser.add_argument(
"-o",
"--operatingsystem",
help="Operating system. 'linux' or 'windows'. If omitted, it will try to autodetect current OS.",
type=str,
)
parser.add_argument(
"-y", "--yes", help="Install even if version already installed", action="store_true"
)
parser.add_argument(
"-n", "--no", help="Don't install if version already installed", action="store_true"
)
parser.add_argument(
"-k", "--keep", help="Keep temporary downloaded archive file", action="store_true"
)
parser.add_argument("-t", "--temp", help="Temporary file path", required=False, type=str)
parser.add_argument(
"-b",
"--blender",
help="Desired Blender version - for example '-b 2.93.2'",
required=True,
type=str,
)
parser.add_argument(
"-r",
"--run",
help="Run downloaded Blender version when finished",
action="store_true",
)
parser.add_argument(
"-v",
"--version",
action="version",
version=appversion,
help="Print program version",
)
args = parser.parse_args()
# Check for updates for BlenderUpdaterCLI
try:
appupdate = requests.get(
"https://api.github.com/repos/overmindstudios/BlenderUpdaterCLI/releases/latest"
).text
UpdateData = json.loads(appupdate)
applatestversion = UpdateData["tag_name"]
if version.parse(applatestversion) > version.parse(appversion):
print(" ERROR ".center(80, "-"))
print(f"{Fore.RED}Updated version of BlenderUpdaterCLI found.")
print(f"{Fore.RED}The current version might not work properly anymore.")
print(
f"{Fore.RED}Please visit https://github.com/overmindstudios/BlenderUpdaterCLI/releases"
)
print(f"{Fore.RED}to download the latest version.")
print(f"{Fore.RED}Current: {appversion} - Latest: {applatestversion}")
quit()
except Exception:
print(" NOTICE ".center(80, "-"))
print("Cannot check for updates.")
raise Exception
# Start update process
print(" SETTINGS ".center(80, "-"))
# check for path validity
if os.path.isdir(args.path):
dir_ = args.path
print(f"Destination path: {Fore.GREEN}{args.path}")
else:
print(Fore.RED + f"'{args.path}' is an invalid path, make sure directory exists")
failed = True
if args.temp:
print(f"Temporary path: {Fore.GREEN}{args.temp}")
tempDir = args.temp
# check for desired blender version
blender = args.blender
# check for desired operating system or autodetect when empty
if args.operatingsystem == "windows":
opsys = "windows"
extension = "zip"
print(f"Operating system: {Fore.GREEN}{opsys}")
elif args.operatingsystem == "linux":
opsys = "linux"
extension = "tar.xz"
print(f"Operating system: {Fore.GREEN}{opsys}")
# autodetect OS
elif not args.operatingsystem:
if platform.system() == "Windows":
opsys = "windows"
extension = "zip"
elif platform.system() == "Linux":
opsys = "linux"
extension = "tar.xz"
print(f"Operating system: {Fore.GREEN}{opsys}{Fore.CYAN} (autodetected)")
else:
print(f"{Fore.RED}Syntax error - use '-o windows' or '-o linux'")
failed = True
# Only 64bit supported for all OS in experimental builds
arch = "64"
# check for --keep flag
if args.keep:
print(f"{Fore.MAGENTA}Will keep temporary archive file")
keep_temp = True
else:
print(f"{Fore.MAGENTA}Will NOT keep temporary archive file")
keep_temp = False
# check for --run flag
if args.run:
print(f"{Fore.MAGENTA}Will run Blender when finished")
will_run = True
else:
print(f"{Fore.MAGENTA}Will NOT run Blender when finished")
will_run = False
print("-".center(80, "-"))
if args.yes and args.no:
print("You cannot pass both -y and -n flags at the same time!")
failed = True
# Abort if any error occured during parsing
if failed is True:
print(f"{Fore.RED}Input errors detected, aborted (check above for details)")
quit()
else:
try:
req = requests.get(url)
except Exception:
print(f"{Fore.RED}Error connecting to {url}, check your internet connection")
try:
filename = re.findall(
r"blender-" + blender + r"[^\s]+" + opsys + r"[^\s]+" + extension,
req.text,
)
except Exception:
print(f"{Fore.RED}No valid Blender version specified ({args.blender} not found)")
sys.exit()
if os.path.isfile("./config.ini"):
config.read("./config.ini")
try:
lastversion = config.get("main", "version")
except Exception: # TODO: Handle errors a bit more gracefully
lastversion = ""
try:
if lastversion == filename[0]:
while True:
if args.yes:
break
elif args.no:
print(
"This version is already installed. -n option present, exiting..."
)
sys.exit()
else:
anyway = str(
input(
"This version is already installed. Continue anyways? [Y]es or [N]o: "
)
).lower()
if anyway == "n":
sys.exit()
elif anyway == "y":
break
print("Invalid choice, try again!")
except Exception:
print(
f"{Fore.RED}No valid Blender version specified ({args.blender} not found)"
)
sys.exit()
else:
config.read("config.ini")
config.add_section("main")
with open("config.ini", "w") as f:
config.write(f)
if not keep_temp:
if os.path.isdir(tempDir):
shutil.rmtree(tempDir)
os.makedirs(tempDir, exist_ok=True)
dir_ = os.path.join(args.path, "")
print(f"{Fore.GREEN}All settings valid, proceeding...")
print(f"Downloading {filename[0]}")
chunkSize = 10240
try:
r = requests.get(url + filename[0], stream=True)
with open(tempDir + filename[0], "wb") as f:
pbar = IncrementalBar(
"Downloading",
max=int(r.headers["Content-Length"]) / chunkSize,
suffix="%(percent)d%%",
)
for chunk in r.iter_content(chunk_size=chunkSize):
if chunk: # filter out keep-alive new chunks
pbar.next()
f.write(chunk)
pbar.finish()
except Exception:
print(f"Download {Fore.RED}failed, please try again. Exiting.")
sys.exit()
print(f"Download {Fore.GREEN}done")
# Extraction
spinnerExtract = Spinner("Extracting... ")
spinnerExtract.start()
try:
shutil.unpack_archive(tempDir + filename[0], tempDir)
except Exception:
print(f"Extraction {Fore.RED}failed, please try again. Exiting.")
exit()
spinnerExtract.stop()
print(f"Extraction {Fore.GREEN}done")
# Copying
source = next(os.walk(tempDir))[1]
spinnerCopy = Spinner("Copying... ")
spinnerCopy.start()
shutil.copytree(os.path.join(tempDir, source[0]), dir_, dirs_exist_ok=True)
spinnerCopy.stop()
print(f"Copying {Fore.GREEN}done")
opsys = platform.system()
# Cleanup
spinnerCleanup = Spinner("Cleanup... ")
spinnerCleanup.start()
if keep_temp:
# just remove the extracted files
shutil.rmtree(os.path.join(tempDir, source[0]))
else:
shutil.rmtree(tempDir)
spinnerCleanup.stop()
print(f"Cleanup {Fore.GREEN}done")
# Finished
print("-".center(80, "-"))
print(f"{Fore.GREEN}All tasks finished")
# write configuration file
config.read("config.ini")
config.set("main", "version", filename[0])
with open("config.ini", "w") as f:
config.write(f)
# run Blender if -r flag present
if args.run:
print(f"{Fore.MAGENTA}Starting up Blender...")
if opsys == "Windows":
p = subprocess.Popen(os.path.join('"' + dir_ + "\\blender.exe" + '"'))
elif opsys == "Linux":
p = subprocess.Popen(os.path.join(dir_ + "/blender"))