mozInstall 2.0.1__tar.gz → 2.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,19 +1,33 @@
1
- Metadata-Version: 1.1
1
+ Metadata-Version: 2.4
2
2
  Name: mozInstall
3
- Version: 2.0.1
3
+ Version: 2.2.0
4
4
  Summary: package for installing and uninstalling Mozilla applications
5
5
  Home-page: https://wiki.mozilla.org/Auto-tools/Projects/Mozbase
6
6
  Author: Mozilla Automation and Tools team
7
7
  Author-email: tools@lists.mozilla.org
8
8
  License: MPL 2.0
9
- Description: see https://firefox-source-docs.mozilla.org/mozbase/index.html
10
9
  Keywords: mozilla
11
- Platform: UNKNOWN
12
10
  Classifier: Environment :: Console
13
11
  Classifier: Intended Audience :: Developers
14
12
  Classifier: License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)
15
13
  Classifier: Natural Language :: English
16
14
  Classifier: Operating System :: OS Independent
17
15
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
18
- Classifier: Programming Language :: Python :: 2.7
19
- Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Requires-Python: >=3.9
19
+ Requires-Dist: mozinfo>=0.7
20
+ Requires-Dist: mozfile>=1.0
21
+ Requires-Dist: requests
22
+ Dynamic: author
23
+ Dynamic: author-email
24
+ Dynamic: classifier
25
+ Dynamic: description
26
+ Dynamic: home-page
27
+ Dynamic: keywords
28
+ Dynamic: license
29
+ Dynamic: requires-dist
30
+ Dynamic: requires-python
31
+ Dynamic: summary
32
+
33
+ see https://firefox-source-docs.mozilla.org/mozbase/index.html
@@ -1,19 +1,33 @@
1
- Metadata-Version: 1.1
1
+ Metadata-Version: 2.4
2
2
  Name: mozInstall
3
- Version: 2.0.1
3
+ Version: 2.2.0
4
4
  Summary: package for installing and uninstalling Mozilla applications
5
5
  Home-page: https://wiki.mozilla.org/Auto-tools/Projects/Mozbase
6
6
  Author: Mozilla Automation and Tools team
7
7
  Author-email: tools@lists.mozilla.org
8
8
  License: MPL 2.0
9
- Description: see https://firefox-source-docs.mozilla.org/mozbase/index.html
10
9
  Keywords: mozilla
11
- Platform: UNKNOWN
12
10
  Classifier: Environment :: Console
13
11
  Classifier: Intended Audience :: Developers
14
12
  Classifier: License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)
15
13
  Classifier: Natural Language :: English
16
14
  Classifier: Operating System :: OS Independent
17
15
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
18
- Classifier: Programming Language :: Python :: 2.7
19
- Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Requires-Python: >=3.9
19
+ Requires-Dist: mozinfo>=0.7
20
+ Requires-Dist: mozfile>=1.0
21
+ Requires-Dist: requests
22
+ Dynamic: author
23
+ Dynamic: author-email
24
+ Dynamic: classifier
25
+ Dynamic: description
26
+ Dynamic: home-page
27
+ Dynamic: keywords
28
+ Dynamic: license
29
+ Dynamic: requires-dist
30
+ Dynamic: requires-python
31
+ Dynamic: summary
32
+
33
+ see https://firefox-source-docs.mozilla.org/mozbase/index.html
@@ -8,4 +8,8 @@ mozInstall.egg-info/not-zip-safe
8
8
  mozInstall.egg-info/requires.txt
9
9
  mozInstall.egg-info/top_level.txt
10
10
  mozinstall/__init__.py
11
- mozinstall/mozinstall.py
11
+ mozinstall/mozinstall.py
12
+ tests/test_binary.py
13
+ tests/test_install.py
14
+ tests/test_is_installer.py
15
+ tests/test_uninstall.py
@@ -0,0 +1,5 @@
1
+ [console_scripts]
2
+ moz_add_to_system = mozinstall:install_cli
3
+ moz_remove_from_system = mozinstall:uninstall_cli
4
+ mozinstall = mozinstall:install_cli
5
+ mozuninstall = mozinstall:uninstall_cli
@@ -1,4 +1,3 @@
1
1
  mozinfo>=0.7
2
2
  mozfile>=1.0
3
3
  requests
4
- six>=1.10.0
@@ -3,6 +3,4 @@
3
3
  # License, v. 2.0. If a copy of the MPL was not distributed with this file,
4
4
  # You can obtain one at http://mozilla.org/MPL/2.0/.
5
5
 
6
- from __future__ import absolute_import
7
-
8
6
  from .mozinstall import *
@@ -0,0 +1,587 @@
1
+ # This Source Code Form is subject to the terms of the Mozilla Public
2
+ # License, v. 2.0. If a copy of the MPL was not distributed with this file,
3
+ # You can obtain one at http://mozilla.org/MPL/2.0/.
4
+
5
+ import os
6
+ import plistlib
7
+ import shutil
8
+ import subprocess
9
+ import sys
10
+ import tarfile
11
+ import tempfile
12
+ import time
13
+ import zipfile
14
+ from optparse import OptionParser
15
+
16
+ import mozfile
17
+ import mozinfo
18
+ import requests
19
+
20
+ try:
21
+ import pefile
22
+
23
+ has_pefile = True
24
+ except ImportError:
25
+ has_pefile = False
26
+
27
+
28
+ TIMEOUT_UNINSTALL = 60
29
+
30
+
31
+ class InstallError(Exception):
32
+ """Thrown when installation fails. Includes traceback if available."""
33
+
34
+
35
+ class InvalidBinary(Exception):
36
+ """Thrown when the binary cannot be found after the installation."""
37
+
38
+
39
+ class InvalidSource(Exception):
40
+ """Thrown when the specified source is not a recognized file type."""
41
+
42
+
43
+ class UninstallError(Exception):
44
+ """Thrown when uninstallation fails. Includes traceback if available."""
45
+
46
+
47
+ def _readPlist(path):
48
+ with open(path, "rb") as fp:
49
+ return plistlib.load(fp)
50
+
51
+
52
+ def get_binary(path, app_name):
53
+ """Find the binary in the specified path, and return its path. If binary is
54
+ not found throw an InvalidBinary exception.
55
+
56
+ :param path: Path within to search for the binary
57
+ :param app_name: Application binary without file extension to look for
58
+ """
59
+ binary = None
60
+
61
+ # On OS X we can get the real binary from the app bundle
62
+ if mozinfo.isMac:
63
+ plist = "%s/Contents/Info.plist" % path
64
+ if not os.path.isfile(plist):
65
+ raise InvalidBinary("%s/Contents/Info.plist not found" % path)
66
+
67
+ binary = os.path.join(
68
+ path, "Contents/MacOS/", _readPlist(plist)["CFBundleExecutable"]
69
+ )
70
+
71
+ else:
72
+ app_name = app_name.lower()
73
+
74
+ if mozinfo.isWin:
75
+ app_name = app_name + ".exe"
76
+
77
+ for root, dirs, files in os.walk(path):
78
+ for filename in files:
79
+ # os.access evaluates to False for some reason, so not using it
80
+ if filename.lower() == app_name:
81
+ binary = os.path.realpath(os.path.join(root, filename))
82
+ break
83
+
84
+ if not binary:
85
+ # The expected binary has not been found.
86
+ raise InvalidBinary('"%s" does not contain a valid binary.' % path)
87
+
88
+ return binary
89
+
90
+
91
+ def install(src, dest, verify=True, dmg_tool=None, hfs_tool=None):
92
+ """Install a zip, exe, tar.gz, tar.bz2, tar.xz or dmg file, and return the path of
93
+ the installation folder.
94
+
95
+ :param src: Path to the install file
96
+ :param dest: Path to install to (to ensure we do not overwrite any existent
97
+ files the folder should not exist yet)
98
+ :param verify: Whether to verify the checksum of a dmg file when mounting it.
99
+ Only affects dmg files on macOS; other formats verify
100
+ integrity as part of extraction.
101
+ :param dmg_tool: Path to the libdmg-hfsplus `dmg` tool. Together with
102
+ `hfs_tool`, lets a dmg file be extracted without mounting
103
+ it. Defaults to the DMG_TOOL build config or environment variable,
104
+ then to `dmg/dmg` in MOZ_FETCHES_DIR.
105
+ :param hfs_tool: Path to the libdmg-hfsplus `hfsplus` tool. Defaults to the
106
+ HFS_TOOL build config or environment variable, then to `dmg/hfsplus` in
107
+ MOZ_FETCHES_DIR.
108
+ """
109
+ if not is_installer(src):
110
+ msg = f"{src} is not a valid installer file"
111
+ if "://" in src:
112
+ try:
113
+ return _install_url(src, dest, verify=verify)
114
+ except Exception:
115
+ exc, val, tb = sys.exc_info()
116
+ error = InvalidSource(f"{msg} ({val})")
117
+ raise error.with_traceback(tb)
118
+ raise InvalidSource(msg)
119
+
120
+ src = os.path.realpath(src)
121
+ dest = os.path.realpath(dest)
122
+
123
+ did_we_create = False
124
+ if not os.path.exists(dest):
125
+ did_we_create = True
126
+ os.makedirs(dest)
127
+
128
+ trbk = None
129
+ try:
130
+ install_dir = None
131
+ if src.lower().endswith(".msix"):
132
+ # MSIX packages _are_ ZIP files, so we need to look for them first.
133
+ install_dir = _install_msix(src)
134
+ elif src.lower().endswith(".dmg"):
135
+ install_dir = _install_dmg(
136
+ src, dest, verify=verify, dmg_tool=dmg_tool, hfs_tool=hfs_tool
137
+ )
138
+ elif src.lower().endswith(".exe"):
139
+ install_dir = _install_exe(src, dest)
140
+ elif zipfile.is_zipfile(src) or tarfile.is_tarfile(src):
141
+ install_dir = mozfile.extract(src, dest)[0]
142
+ else:
143
+ raise InvalidSource(f"{src} is not a valid installer file")
144
+
145
+ return install_dir
146
+
147
+ except BaseException:
148
+ cls, exc, trbk = sys.exc_info()
149
+ if did_we_create:
150
+ try:
151
+ # try to uninstall this properly
152
+ uninstall(dest)
153
+ except Exception:
154
+ # uninstall may fail, let's just try to clean the folder
155
+ # in this case
156
+ try:
157
+ mozfile.remove(dest)
158
+ except Exception:
159
+ pass
160
+ if issubclass(cls, Exception):
161
+ error = InstallError('Failed to install "%s (%s)"' % (src, str(exc)))
162
+ raise error.with_traceback(trbk)
163
+ # any other kind of exception like KeyboardInterrupt is just re-raised.
164
+ raise exc.with_traceback(trbk)
165
+
166
+ finally:
167
+ # trbk won't get GC'ed due to circular reference
168
+ # http://docs.python.org/library/sys.html#sys.exc_info
169
+ del trbk
170
+
171
+
172
+ def is_installer(src):
173
+ """Tests if the given file is a valid installer package.
174
+
175
+ Supported types:
176
+ All: zip, tar.gz, tar.bz2, tar.xz
177
+ Linux, Mac: dmg
178
+ Windows: exe, msix
179
+
180
+ On Windows pefile will be used to determine if the executable is the
181
+ right type, if it is installed on the system.
182
+
183
+ :param src: Path to the install file.
184
+ """
185
+ src = os.path.realpath(src)
186
+
187
+ if not os.path.isfile(src):
188
+ return False
189
+
190
+ if mozinfo.isWin and src.lower().endswith(".msix"):
191
+ # MSIX packages _are_ ZIP files, so look for them first.
192
+ return True
193
+ if zipfile.is_zipfile(src):
194
+ return True
195
+ if tarfile.is_tarfile(src):
196
+ return True
197
+ if mozinfo.isMac or mozinfo.isLinux:
198
+ return src.lower().endswith(".dmg")
199
+ if mozinfo.isWin:
200
+ if os.access(src, os.X_OK) and src.lower().endswith(".exe"):
201
+ if has_pefile:
202
+ # try to determine if binary is actually a gecko installer
203
+ pe_data = pefile.PE(src)
204
+ data = {}
205
+ for info in getattr(pe_data, "FileInfo", []):
206
+ if info.Key == "StringFileInfo":
207
+ for string in info.StringTable:
208
+ data.update(string.entries)
209
+ return "BuildID" not in data
210
+ else:
211
+ # pefile not available, just assume a proper binary was passed in
212
+ return True
213
+
214
+ return False
215
+
216
+
217
+ def uninstall(install_folder):
218
+ """Uninstalls the application in the specified path. If it has been
219
+ installed via an installer on Windows, use the uninstaller first.
220
+
221
+ :param install_folder: Path of the installation folder
222
+
223
+ """
224
+ # Uninstallation for MSIX applications is totally different than
225
+ # any other installs...
226
+ if "WindowsApps" in install_folder:
227
+ # At the time of writing, the package installation directory is always
228
+ # the package full name, so this assumption is valid (for now....).
229
+ packageFullName = install_folder.split("WindowsApps\\")[1].split("\\")[0]
230
+ cmd = f"powershell.exe Remove-AppxPackage -Package {packageFullName}"
231
+ subprocess.check_call(cmd)
232
+ return
233
+
234
+ install_folder = os.path.realpath(install_folder)
235
+ assert os.path.isdir(install_folder), (
236
+ 'installation folder "%s" exists.' % install_folder
237
+ )
238
+
239
+ # On Windows we have to use the uninstaller. If it's not available fallback
240
+ # to the directory removal code
241
+ if mozinfo.isWin:
242
+ uninstall_folder = "%s\\uninstall" % install_folder
243
+ log_file = "%s\\uninstall.log" % uninstall_folder
244
+
245
+ if os.path.isfile(log_file):
246
+ trbk = None
247
+ try:
248
+ cmdArgs = ["%s\\uninstall\\helper.exe" % install_folder, "/S"]
249
+ result = subprocess.call(cmdArgs)
250
+ if result != 0:
251
+ raise Exception("Execution of uninstaller failed.")
252
+
253
+ # The uninstaller spawns another process so the subprocess call
254
+ # returns immediately. We have to wait until the uninstall
255
+ # folder has been removed or until we run into a timeout.
256
+ end_time = time.time() + TIMEOUT_UNINSTALL
257
+ while os.path.exists(uninstall_folder):
258
+ time.sleep(1)
259
+
260
+ if time.time() > end_time:
261
+ raise Exception("Failure removing uninstall folder.")
262
+
263
+ except Exception as ex:
264
+ cls, exc, trbk = sys.exc_info()
265
+ error = UninstallError(
266
+ "Failed to uninstall %s (%s)" % (install_folder, str(ex))
267
+ )
268
+ raise error.with_traceback(trbk)
269
+
270
+ finally:
271
+ # trbk won't get GC'ed due to circular reference
272
+ # http://docs.python.org/library/sys.html#sys.exc_info
273
+ del trbk
274
+
275
+ # Ensure that we remove any trace of the installation. Even the uninstaller
276
+ # on Windows leaves files behind we have to explicitely remove.
277
+ mozfile.remove(install_folder)
278
+
279
+
280
+ def _install_url(url, dest, verify=True):
281
+ """Saves a url to a temporary file, and passes that through to the
282
+ install function.
283
+
284
+ :param url: Url to the install file
285
+ :param dest: Path to install to (to ensure we do not overwrite any existent
286
+ files the folder should not exist yet)
287
+ :param verify: Whether to verify the checksum of a dmg file when attaching it.
288
+ Only affects dmg files on macOS; other formats verify
289
+ integrity as part of extraction.
290
+ """
291
+ r = requests.get(url, stream=True)
292
+ name = tempfile.mkstemp()[1]
293
+ try:
294
+ with open(name, "w+b") as fh:
295
+ for chunk in r.iter_content(chunk_size=16 * 1024):
296
+ fh.write(chunk)
297
+ result = install(name, dest, verify=verify)
298
+ finally:
299
+ mozfile.remove(name)
300
+ return result
301
+
302
+
303
+ def _find_dmg_tools(dmg_tool=None, hfs_tool=None):
304
+ substs = {}
305
+ try:
306
+ import buildconfig
307
+
308
+ substs = buildconfig.substs
309
+ except ImportError:
310
+ pass
311
+ fetches_dir = os.environ.get("MOZ_FETCHES_DIR")
312
+
313
+ def find(tool, var, name):
314
+ tool = tool or substs.get(var) or os.environ.get(var)
315
+ if not tool and fetches_dir:
316
+ path = os.path.join(fetches_dir, "dmg", name)
317
+ if os.path.isfile(path):
318
+ tool = path
319
+ return tool
320
+
321
+ return find(dmg_tool, "DMG_TOOL", "dmg"), find(hfs_tool, "HFS_TOOL", "hfsplus")
322
+
323
+
324
+ def _install_dmg(src, dest_app, verify=True, dmg_tool=None, hfs_tool=None):
325
+ """Extract a dmg file into the destination folder and return the
326
+ application folder.
327
+
328
+ src -- DMG image which has to be extracted
329
+ dest -- the path to extract to
330
+ verify -- whether to verify the checksum of the image when mounting it
331
+ dmg_tool, hfs_tool -- libdmg-hfsplus tools to extract the image without
332
+ mounting it
333
+
334
+ """
335
+ dmg_tool, hfs_tool = _find_dmg_tools(dmg_tool, hfs_tool)
336
+ if dmg_tool and hfs_tool:
337
+ return _install_dmg_extract(src, dest_app, dmg_tool, hfs_tool)
338
+ if mozinfo.isLinux:
339
+ raise InstallError(
340
+ "DMG_TOOL and HFS_TOOL are required to install a dmg on Linux"
341
+ )
342
+
343
+ def _detach_with_retry(volume, retries=4, delay=0.25):
344
+ for i in range(retries):
345
+ try:
346
+ subprocess.check_call(f'hdiutil detach "{volume}" -quiet', shell=True)
347
+ return
348
+ except subprocess.CalledProcessError as e:
349
+ # 16 == EBUSY
350
+ if e.returncode != 16 or i == retries - 1:
351
+ raise
352
+ time.sleep(delay)
353
+
354
+ # Final fallback (CI-safe)
355
+ subprocess.check_call(f'hdiutil detach "{volume}" -force -quiet', shell=True)
356
+
357
+ app_dir = None
358
+ try:
359
+ macos_major = int(str(mozinfo.os_version).split(".")[0])
360
+ if macos_major >= 27:
361
+ # Use diskutil instead of hdiutil on macOS 27+. On macOS 27,
362
+ # `hdiutil attach` is deprecated and prints deprecation warnings
363
+ # on stderr. Use thew newer `diskutil` command instead.
364
+ output = subprocess.check_output(
365
+ [
366
+ "diskutil",
367
+ "image",
368
+ "attach",
369
+ "--plist",
370
+ "--readOnly",
371
+ "--nobrowse",
372
+ src,
373
+ ],
374
+ stderr=subprocess.STDOUT,
375
+ )
376
+ entities = plistlib.loads(output)["system-entities"]
377
+ app_dir = next(
378
+ (e["mount-point"] for e in entities if "mount-point" in e), None
379
+ )
380
+ if not app_dir:
381
+ raise InstallError(f"No mounted volume found for {src}")
382
+ else:
383
+ # `hdiutil attach` is now deprecated (macOS 27+). Limit its use
384
+ # to older macOS versions. According to the Apple docs, the hdiutil
385
+ # output is stable and is based on the tab separators. Therefore,
386
+ # $3 should give us the mounted path.
387
+ verify_flag = "" if verify else " -noverify"
388
+ app_dir = (
389
+ subprocess
390
+ .check_output(
391
+ f'hdiutil attach -noautoopen -nobrowse -readonly{verify_flag} "{src}"'
392
+ "| grep /Volumes/ | awk 'BEGIN{FS=\"\t\"} {print $3}'",
393
+ shell=True,
394
+ stderr=subprocess.STDOUT,
395
+ )
396
+ .strip()
397
+ .decode("utf-8")
398
+ )
399
+
400
+ app_name = None
401
+ for entry in os.listdir(app_dir):
402
+ if entry.endswith(".app"):
403
+ app_name = entry
404
+ break
405
+
406
+ if not app_name:
407
+ raise InstallError(f"No .app bundle found in {src}")
408
+
409
+ src_app = os.path.join(app_dir, app_name)
410
+ dest_app = os.path.join(dest_app, app_name)
411
+
412
+ # copytree() would fail if dest already exists.
413
+ if os.path.exists(dest_app):
414
+ raise InstallError(f"App bundle already exists: {dest_app}")
415
+
416
+ shutil.copytree(src_app, dest_app, False)
417
+
418
+ finally:
419
+ if app_dir:
420
+ try:
421
+ _detach_with_retry(app_dir)
422
+ except Exception as e:
423
+ # Log, but do not override the original exception
424
+ print(f"Warning: failed to detach {app_dir}: {e}")
425
+
426
+ return dest_app
427
+
428
+
429
+ def _install_dmg_extract(src, dest, dmg_tool, hfs_tool):
430
+ """Extract the .app bundle of a dmg file into dest without mounting the
431
+ image, and return the path of the bundle."""
432
+ tmpdir = tempfile.mkdtemp(dir=dest)
433
+ try:
434
+ hfs_file = os.path.join(tmpdir, "image.hfs")
435
+ contents = os.path.join(tmpdir, "contents")
436
+ os.mkdir(contents)
437
+ subprocess.check_call(
438
+ [dmg_tool, "extract", src, hfs_file], stdout=subprocess.DEVNULL
439
+ )
440
+ subprocess.check_call(
441
+ [hfs_tool, hfs_file, "extractall", "/", contents],
442
+ stdout=subprocess.DEVNULL,
443
+ )
444
+
445
+ app_name = next((e for e in os.listdir(contents) if e.endswith(".app")), None)
446
+ if not app_name:
447
+ raise InstallError(f"No .app bundle found in {src}")
448
+
449
+ dest_app = os.path.join(dest, app_name)
450
+ if os.path.exists(dest_app):
451
+ raise InstallError(f"App bundle already exists: {dest_app}")
452
+
453
+ os.rename(os.path.join(contents, app_name), dest_app)
454
+ finally:
455
+ shutil.rmtree(tmpdir, ignore_errors=True)
456
+
457
+ return dest_app
458
+
459
+
460
+ def _install_exe(src, dest):
461
+ """Run the MSI installer to silently install the application into the
462
+ destination folder. Return the folder path.
463
+
464
+ Arguments:
465
+ src -- MSI installer to be executed
466
+ dest -- the path to install to
467
+
468
+ """
469
+ # The installer doesn't automatically create a sub folder. Lets guess the
470
+ # best name from the src file name
471
+ filename = os.path.basename(src)
472
+ dest = os.path.join(dest, filename.split(".")[0])
473
+
474
+ # possibly gets around UAC in vista (still need to run as administrator)
475
+ os.environ["__compat_layer"] = "RunAsInvoker"
476
+ cmd = '"%s" /extractdir=%s' % (src, os.path.realpath(dest))
477
+
478
+ subprocess.check_call(cmd)
479
+
480
+ return dest
481
+
482
+
483
+ def _get_msix_install_location(pkg):
484
+ with zipfile.ZipFile(pkg) as zf:
485
+ # First, we pull the app identity out of the AppxManifest...
486
+ with zf.open("AppxManifest.xml") as am:
487
+ for line in am.readlines():
488
+ line = line.decode("utf-8")
489
+ if "<Identity" in line:
490
+ for part in line.split(" "):
491
+ if part.startswith("Name"):
492
+ pkgname = part.split("=")[-1].strip('"\r\n')
493
+
494
+ # ...then we can use it to find the install location
495
+ # with this cmdlet
496
+ cmd = (
497
+ f'powershell.exe "Get-AppxPackage" "-Name" "{pkgname}"'
498
+ )
499
+ # Powershell "helpfully" wraps long lines and there's
500
+ # no tidy way to tell it not to, so we'll have to
501
+ # reconstruct the value. Output could look like this:
502
+ # InstallLocation : C:\Program
503
+ # Files\WindowsApps\...
504
+ # Don't strip trailing spaces. The space between
505
+ # "Program" and "Files" is at the end of the first
506
+ # line. (Not in this comment, due to linting.)
507
+ location = None
508
+ for line in (
509
+ subprocess
510
+ .check_output(cmd)
511
+ .decode("utf-8")
512
+ .splitlines()
513
+ ):
514
+ if line.startswith("InstallLocation"):
515
+ location = line[line.find(": ") + 2 :]
516
+ elif location is not None:
517
+ if line.startswith(" "):
518
+ location += line.lstrip()
519
+ else:
520
+ break
521
+ return location
522
+
523
+ raise Exception(f"Couldn't find install location of {pkg}")
524
+
525
+
526
+ def _install_msix(src):
527
+ """Install the MSIX package and return the installation path.
528
+
529
+ Arguments:
530
+ src -- MSIX package to install
531
+
532
+ """
533
+ # possibly gets around UAC in vista (still need to run as administrator)
534
+ cmd = f'powershell.exe "Add-AppxPackage" "-Path" "{src}"'
535
+ subprocess.check_call(cmd)
536
+
537
+ return _get_msix_install_location(src)
538
+
539
+
540
+ def install_cli(argv=sys.argv[1:]):
541
+ parser = OptionParser(usage="usage: %prog [options] installer")
542
+ parser.add_option(
543
+ "-d",
544
+ "--destination",
545
+ dest="dest",
546
+ default=os.getcwd(),
547
+ help='Directory to install application into. [default: "%default"]',
548
+ )
549
+ parser.add_option(
550
+ "--app",
551
+ dest="app",
552
+ default="firefox",
553
+ help="Application being installed. [default: %default]",
554
+ )
555
+ parser.add_option(
556
+ "--no-verify",
557
+ dest="verify",
558
+ action="store_false",
559
+ default=True,
560
+ help="Skip checksum verification when attaching a dmg file.",
561
+ )
562
+
563
+ (options, args) = parser.parse_args(argv)
564
+ if not len(args) == 1:
565
+ parser.error("An installer file has to be specified.")
566
+
567
+ src = args[0]
568
+
569
+ # Run it
570
+ if os.path.isdir(src):
571
+ binary = get_binary(src, app_name=options.app)
572
+ else:
573
+ install_path = install(src, options.dest, verify=options.verify)
574
+ binary = get_binary(install_path, app_name=options.app)
575
+
576
+ print(binary)
577
+
578
+
579
+ def uninstall_cli(argv=sys.argv[1:]):
580
+ parser = OptionParser(usage="usage: %prog install_path")
581
+
582
+ (options, args) = parser.parse_args(argv)
583
+ if not len(args) == 1:
584
+ parser.error("An installation path has to be specified.")
585
+
586
+ # Run it
587
+ uninstall(argv[0])