|
| 1 | +import os |
| 2 | +import sys |
| 3 | +from pathlib import Path |
| 4 | + |
| 5 | +from .version import VERSION |
| 6 | + |
| 7 | +# language=python |
| 8 | +install_code = """ |
| 9 | +# add devtools `debug` function to builtins |
| 10 | +try: |
| 11 | + from devtools import debug |
| 12 | +except ImportError: |
| 13 | + pass |
| 14 | +else: |
| 15 | + __builtins__['debug'] = debug |
| 16 | +""" |
| 17 | + |
| 18 | + |
| 19 | +def print_code() -> int: |
| 20 | + print(install_code) |
| 21 | + return 0 |
| 22 | + |
| 23 | + |
| 24 | +def install() -> int: |
| 25 | + print('[WARNING: this command is experimental, report issues at github.com/samuelcolvin/python-devtools]\n') |
| 26 | + |
| 27 | + if 'debug' in __builtins__.__dict__: |
| 28 | + print('Looks like devtools is already installed.') |
| 29 | + return 0 |
| 30 | + |
| 31 | + try: |
| 32 | + import sitecustomize # type: ignore |
| 33 | + except ImportError: |
| 34 | + paths = [Path(p) for p in sys.path] |
| 35 | + try: |
| 36 | + path = next(p for p in paths if p.is_dir() and p.name == 'site-packages') |
| 37 | + except StopIteration: |
| 38 | + # what else makes sense to try? |
| 39 | + print(f'unable to file a suitable path to save `sitecustomize.py` to from sys.path: {paths}') |
| 40 | + return 1 |
| 41 | + else: |
| 42 | + install_path = path / 'sitecustomize.py' |
| 43 | + else: |
| 44 | + install_path = Path(sitecustomize.__file__) |
| 45 | + |
| 46 | + print(f'Found path "{install_path}" to install devtools into __builtins__') |
| 47 | + print('To install devtools, run the following command:\n') |
| 48 | + if os.access(install_path, os.W_OK): |
| 49 | + print(f' python -m devtools print-code >> {install_path}\n') |
| 50 | + else: |
| 51 | + print(f' python -m devtools print-code | sudo tee -a {install_path} > /dev/null\n') |
| 52 | + print('Note: "sudo" is required because the path is not writable by the current user.') |
| 53 | + |
| 54 | + return 0 |
| 55 | + |
| 56 | + |
| 57 | +if __name__ == '__main__': |
| 58 | + if 'install' in sys.argv: |
| 59 | + sys.exit(install()) |
| 60 | + elif 'print-code' in sys.argv: |
| 61 | + sys.exit(print_code()) |
| 62 | + else: |
| 63 | + print(f'python-devtools v{VERSION}, CLI usage: python -m devtools [install|print-code]') |
| 64 | + sys.exit(1) |
0 commit comments