diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index cd3510ed..82f0c8ee 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -1,6 +1,19 @@ name: Tests -on: [push, pull_request] +on: + push: + branches: + - main + pull_request: + +concurrency: + # Concurrency group that uses the workflow name and PR number if available + # or commit SHA as a fallback. If a new build is triggered under that + # concurrency group while a previous build is running it will be canceled. + # Repeated pushes to a PR will cancel all previous builds, while multiple + # merges to main will not cancel. + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.sha }} + cancel-in-progress: true jobs: run_test_suite: @@ -8,43 +21,50 @@ jobs: runs-on: ${{ matrix.os }}-latest timeout-minutes: 30 env: - test-dependencies: pytest pytest-cov conda + CONDA_NUMBER_CHANNEL_NOTICES: 0 strategy: fail-fast: false matrix: - os: [windows] - python-version: [3.7, 3.8, 3.9] + os: [windows, ubuntu, macos] + python-version: ["3.8", "3.9", "3.10",] # "3.11"] steps: - - uses: actions/checkout@v2 - - - uses: conda-incubator/setup-miniconda@v2 + - uses: actions/checkout@v3 with: - auto-update-conda: true - python-version: ${{ matrix.python-version }} + fetch-depth: 0 + - name: Install dependencies + uses: mamba-org/provision-with-micromamba@main + with: + environment-file: false + environment-name: test + channels: conda-canary/label/conda-conda-pr-11882,conda-forge + extra-specs: | + python=${{ matrix.python-version }} + conda-canary/label/conda-conda-pr-11882::conda + pip + pytest + pytest-cov + pydantic + hypothesis + hypothesis-jsonschema - - shell: bash -l {0} + - shell: bash -el {0} name: Conda info run: | conda info conda list - - shell: bash -l {0} - name: Install dependencies - run: | - conda install ${{ env.dependencies }} ${{ env.test-dependencies }} - conda list - - - shell: bash -l {0} + - shell: bash -el {0} name: Install menuinst run: | - pip install -e . + python -m pip install -vv . + conda list - - shell: bash -l {0} + - shell: bash -el {0} name: Run test suite run: | - pytest tests --cov-append --cov-report=xml --cov=menuinst + python -I -m pytest tests/ --cov-append --cov-report=xml --cov=menuinst - uses: codecov/codecov-action@v1 with: diff --git a/.gitignore b/.gitignore index 1a23b741..572542fb 100644 --- a/.gitignore +++ b/.gitignore @@ -1,10 +1,144 @@ -# file types to ignore -*.pyc -*.pyd -*~ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class -# ignore the build directories -*.egg-info/ +# C extensions +*.so + +# Distribution / packaging +.Python build/ +develop-eggs/ dist/ -.cache/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# MacOS +.DS_Store + +# setuptools-scm +menuinst/_version.py diff --git a/MANIFEST.in b/MANIFEST.in index 577edc94..56892bf9 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,2 +1,4 @@ -include versioneer.py include menuinst/_version.py +include menuinst/data/*.json +include menuinst/data/osx_launcher_* +exclude *.h *.cpp diff --git a/TODO.txt b/TODO.txt deleted file mode 100644 index e3ba63c1..00000000 --- a/TODO.txt +++ /dev/null @@ -1,7 +0,0 @@ -Bugs: -===== - - -Enhancements: -============= - * should we create Desktop icons on MaxOSX as well? diff --git a/cwp.py b/cwp.py index 7f747594..4ed77c93 100644 --- a/cwp.py +++ b/cwp.py @@ -5,26 +5,43 @@ import sys import subprocess from os.path import join, pathsep +import argparse -from menuinst.knownfolders import FOLDERID, get_folder_path, PathNotFoundException +from menuinst._legacy.knownfolders import FOLDERID, get_folder_path -# call as: python cwp.py PREFIX ARGs... +# call as: python cwp.py [--no-console] PREFIX ARGs... +parser = argparse.ArgumentParser() +parser.add_argument( + "--no-console", action="store_true", help="Create subprocess with CREATE_NO_WINDOW flag." +) +parser.add_argument("prefix", help="Prefix to be 'activated' before calling `args`.") +parser.add_argument("args", nargs="*", help="Command (and arguments) to be executed.") +parsed_args = parser.parse_args() -prefix = sys.argv[1] -args = sys.argv[2:] +no_console = parsed_args.no_console +prefix = parsed_args.prefix +args = parsed_args.args -new_paths = pathsep.join([prefix, - join(prefix, "Library", "mingw-w64", "bin"), - join(prefix, "Library", "usr", "bin"), - join(prefix, "Library", "bin"), - join(prefix, "Scripts")]) +new_paths = pathsep.join( + [ + prefix, + join(prefix, "Library", "mingw-w64", "bin"), + join(prefix, "Library", "usr", "bin"), + join(prefix, "Library", "bin"), + join(prefix, "Scripts"), + ] +) env = os.environ.copy() -env['PATH'] = new_paths + pathsep + env['PATH'] -env['CONDA_PREFIX'] = prefix +env["PATH"] = new_paths + pathsep + env["PATH"] +env["CONDA_PREFIX"] = prefix documents_folder, exception = get_folder_path(FOLDERID.Documents) if exception: documents_folder, exception = get_folder_path(FOLDERID.PublicDocuments) if not exception: os.chdir(documents_folder) -sys.exit(subprocess.call(args, env=env)) + +creationflags = {} +if no_console: + creationflags["creationflags"] = getattr(subprocess, "CREATE_NO_WINDOW", 0x08000000) +sys.exit(subprocess.call(args, env=env, **creationflags)) diff --git a/menuinst/PythonApplet.icns b/menuinst/PythonApplet.icns deleted file mode 100644 index c8aad9fc..00000000 Binary files a/menuinst/PythonApplet.icns and /dev/null differ diff --git a/menuinst/__init__.py b/menuinst/__init__.py index 1dad2af5..e116286f 100644 --- a/menuinst/__init__.py +++ b/menuinst/__init__.py @@ -1,77 +1,53 @@ -# Copyright (c) 2008-2011 by Enthought, Inc. -# Copyright (c) 2013-2015 Continuum Analytics, Inc. -# All rights reserved. +""" +""" -from __future__ import absolute_import -import logging +import os import sys import json -from os.path import abspath, basename, exists, join +from os import PathLike +from logging import getLogger as _getLogger -from ._version import get_versions -__version__ = get_versions()['version'] -del get_versions +try: + from ._version import __version__ +except ImportError: + __version__ = "dev" -if sys.platform.startswith('linux'): - from .linux import Menu, ShortCut +from ._legacy import install as _legacy_install +from .api import install as _api_install, remove as _api_remove +from .utils import DEFAULT_PREFIX, DEFAULT_BASE_PREFIX -elif sys.platform == 'darwin': - from .darwin import Menu, ShortCut +_log = _getLogger(__name__) -elif sys.platform == 'win32': - from .win32 import Menu, ShortCut - from .win_elevate import isUserAdmin, runAsAdmin - -def _install(path, remove=False, prefix=sys.prefix, mode=None, root_prefix=sys.prefix): - if abspath(prefix) == abspath(root_prefix): - env_name = None - else: - env_name = basename(prefix) - - data = json.load(open(path)) - try: - menu_name = data['menu_name'] - except KeyError: - menu_name = 'Python-%d.%d' % sys.version_info[:2] - - shortcuts = data['menu_items'] - m = Menu(menu_name, prefix=prefix, env_name=env_name, mode=mode, root_prefix=root_prefix) - if remove: - for sc in shortcuts: - ShortCut(m, sc).remove() - m.remove() - else: - m.create() - for sc in shortcuts: - ShortCut(m, sc).create() - - -def install(path, remove=False, prefix=sys.prefix, recursing=False, root_prefix=sys.prefix): +def install(path: PathLike, remove: bool = False, prefix: PathLike = DEFAULT_PREFIX, **kwargs): """ - Install Menu and shortcuts - - # Specifying `root_prefix` is used with conda-standalone, because we can't use - # `sys.prefix`, therefore we need to specify it + This function is only here as a legacy adapter for menuinst v1.x. + Please use `menuinst.api` functions instead. """ - # this root_prefix is intentional. We want to reflect the state of the root installation. - if sys.platform == 'win32' and not exists(join(root_prefix, '.nonadmin')): - if isUserAdmin(): - _install(path, remove, prefix, mode='system', root_prefix=root_prefix) + if sys.platform == "win32": + path = path.replace("/", "\\") + json_path = os.path.join(prefix, path) + with open(json_path) as f: + metadata = json.load(f) + if "$id" not in metadata: # old style JSON + if sys.platform == "win32": + kwargs.setdefault("root_prefix", kwargs.pop("base_prefix", DEFAULT_BASE_PREFIX)) + if kwargs["root_prefix"] is None: + kwargs["root_prefix"] = DEFAULT_BASE_PREFIX + _legacy_install(json_path, remove=remove, prefix=prefix, **kwargs) else: - retcode = 1 - try: - if not recursing: - retcode = runAsAdmin([join(root_prefix, 'python'), '-c', - "import menuinst; menuinst.install(%r, %r, %r, %r, %r)" % ( - path, bool(remove), prefix, True, root_prefix)]) - except WindowsError: - pass - - if retcode != 0: - logging.warn("Insufficient permissions to write menu folder. " - "Falling back to user location") - _install(path, remove, prefix, mode='user', root_prefix=root_prefix) + _log.warn( + "menuinst._legacy is only supported on Windows. " + "Switch to the new-style menu definitions " + "for cross-platform compatibility." + ) else: - _install(path, remove, prefix, mode='user', root_prefix=root_prefix) + # patch kwargs to reroute root_prefix to base_prefix + kwargs.setdefault("base_prefix", kwargs.pop("root_prefix", DEFAULT_BASE_PREFIX)) + if kwargs["base_prefix"] is None: + kwargs["base_prefix"] = DEFAULT_BASE_PREFIX + if remove: + _api_remove(metadata, target_prefix=prefix, **kwargs) + else: + _api_install(metadata, target_prefix=prefix, **kwargs) diff --git a/menuinst/_legacy/__init__.py b/menuinst/_legacy/__init__.py new file mode 100644 index 00000000..72bf5e17 --- /dev/null +++ b/menuinst/_legacy/__init__.py @@ -0,0 +1,81 @@ +# Copyright (c) 2008-2011 by Enthought, Inc. +# Copyright (c) 2013-2015 Continuum Analytics, Inc. +# All rights reserved. + +from __future__ import absolute_import +import logging +import sys +import json +from os.path import abspath, basename, exists, join + +try: + from .._version import __version__ +except ImportError: + __version__ = "dev" + +from ..utils import DEFAULT_PREFIX, DEFAULT_BASE_PREFIX + +if sys.platform == 'win32': + from .win32 import Menu, ShortCut + from ..platforms.win_utils.win_elevate import isUserAdmin, runAsAdmin + + +def _install(path, remove=False, prefix=None, mode=None, root_prefix=None): + prefix = prefix or DEFAULT_PREFIX + root_prefix = root_prefix or DEFAULT_BASE_PREFIX + if abspath(prefix) == abspath(root_prefix): + env_name = None + else: + env_name = basename(prefix) + + data = json.load(open(path)) + try: + menu_name = data['menu_name'] + except KeyError: + menu_name = 'Python-%d.%d' % sys.version_info[:2] + + shortcuts = data['menu_items'] + m = Menu(menu_name, prefix=prefix, env_name=env_name, mode=mode, root_prefix=root_prefix) + if remove: + for sc in shortcuts: + ShortCut(m, sc).remove() + m.remove() + else: + m.create() + for sc in shortcuts: + ShortCut(m, sc).create() + + +def install(path, remove=False, prefix=None, recursing=False, root_prefix=None): + """ + Install Menu and shortcuts + + # Specifying `root_prefix` is used with conda-standalone, because we can't use + # `sys.prefix`, therefore we need to specify it + """ + prefix = prefix or DEFAULT_PREFIX + root_prefix = root_prefix or DEFAULT_BASE_PREFIX + if not sys.platform == 'win32': + raise RuntimeError("menuinst._legacy is only supported on Windows.") + + # this root_prefix is intentional. We want to reflect the state of the root installation. + + if not exists(join(root_prefix, '.nonadmin')): + if isUserAdmin(): + _install(path, remove, prefix, mode='system', root_prefix=root_prefix) + else: + retcode = 1 + try: + if not recursing: + retcode = runAsAdmin([join(root_prefix, 'python'), '-c', + "import menuinst; menuinst.install(%r, %r, %r, %r, %r)" % ( + path, bool(remove), prefix, True, root_prefix)]) + except OSError: + pass + + if retcode != 0: + logging.warn("Insufficient permissions to write menu folder. " + "Falling back to user location") + _install(path, remove, prefix, mode='user', root_prefix=root_prefix) + else: + _install(path, remove, prefix, mode='user', root_prefix=root_prefix) diff --git a/menuinst/main.py b/menuinst/_legacy/main.py similarity index 85% rename from menuinst/main.py rename to menuinst/_legacy/main.py index 73f5ceca..d34bc9ca 100644 --- a/menuinst/main.py +++ b/menuinst/_legacy/main.py @@ -1,8 +1,8 @@ import sys from os.path import join -import menuinst - +import menuinst._legacy as menuinst +from ..utils import DEFAULT_PREFIX def main(): from optparse import OptionParser @@ -13,7 +13,7 @@ def main(): p.add_option('-p', '--prefix', action="store", - default=sys.prefix) + default=DEFAULT_PREFIX) p.add_option('--remove', action="store_true") diff --git a/menuinst/_legacy/utils.py b/menuinst/_legacy/utils.py new file mode 100644 index 00000000..7e09a644 --- /dev/null +++ b/menuinst/_legacy/utils.py @@ -0,0 +1,22 @@ +import os +import shutil +from os.path import isdir, isfile, islink + + + +def rm_empty_dir(path): + try: + os.rmdir(path) + except OSError: # directory might not exist or not be empty + pass + + +def rm_rf(path): + if islink(path) or isfile(path): + # Note that we have to check if the destination is a link because + # exists('/path/to/dead-link') will return False, although + # islink('/path/to/dead-link') is True. + os.unlink(path) + + elif isdir(path): + shutil.rmtree(path) diff --git a/menuinst/win32.py b/menuinst/_legacy/win32.py similarity index 73% rename from menuinst/win32.py rename to menuinst/_legacy/win32.py index 6aabd933..d39c5260 100644 --- a/menuinst/win32.py +++ b/menuinst/_legacy/win32.py @@ -7,16 +7,15 @@ import ctypes import logging import os -from os.path import isdir, join, exists, split +from os.path import isdir, join, exists import sys import locale from .utils import rm_empty_dir, rm_rf -from .knownfolders import get_folder_path, FOLDERID -# KNOWNFOLDERID does provide a direct path to Quick Launch. No additional path necessary. -from .winshortcut import create_shortcut - +from ..platforms.win_utils.knownfolders import dirs_src, folder_path +from ..platforms.win_utils.winshortcut import create_shortcut +from ..utils import DEFAULT_BASE_PREFIX # This allows debugging installer issues using DebugView from Microsoft. OutputDebugString = ctypes.windll.kernel32.OutputDebugStringW @@ -37,70 +36,6 @@ def emit(self, record): logger.addHandler(dbgview) logger.addHandler(stream_handler) -# When running as 'nt authority/system' as sometimes people do via SCCM, -# various folders do not exist, such as QuickLaunch. This doesn't matter -# as we'll use the "system" key finally and check for the "quicklaunch" -# subkey before adding any Quick Launch menu items. - -# It can happen that some of the dirs[] entires refer to folders that do not -# exist, in which case, the 2nd entry of the value tuple is a sub-class of -# Exception. - -dirs_src = {"system": { "desktop": get_folder_path(FOLDERID.PublicDesktop), - "start": get_folder_path(FOLDERID.CommonPrograms), - "documents": get_folder_path(FOLDERID.PublicDocuments), - "profile": get_folder_path(FOLDERID.Profile)}, - - "user": { "desktop": get_folder_path(FOLDERID.Desktop), - "start": get_folder_path(FOLDERID.Programs), - "quicklaunch": get_folder_path(FOLDERID.QuickLaunch), - "documents": get_folder_path(FOLDERID.Documents), - "profile": get_folder_path(FOLDERID.Profile)}} - - -def folder_path(preferred_mode, check_other_mode, key): - ''' This function implements all heuristics and workarounds for messed up - KNOWNFOLDERID registry values. It's also verbose (OutputDebugStringW) - about whether fallbacks worked or whether they would have worked if - check_other_mode had been allowed. - ''' - other_mode = 'system' if preferred_mode == 'user' else 'user' - path, exception = dirs_src[preferred_mode][key] - if not exception: - return path - logger.info("WARNING: menuinst key: '%s'\n" - " path: '%s'\n" - " .. excepted with: '%s' in knownfolders.py, implementing workarounds .." - % (key, path, type(exception).__name__)) - # Since I have seen 'user', 'documents' set as '\\vmware-host\Shared Folders\Documents' - # when there's no such server, we check 'user', 'profile' + '\Documents' before maybe - # trying the other_mode (though I have chickened out on that idea). - if preferred_mode == 'user' and key == 'documents': - user_profile, exception = dirs_src['user']['profile'] - if not exception: - path = join(user_profile, 'Documents') - if os.access(path, os.W_OK): - logger.info(" .. worked-around to: '%s'" % (path)) - return path - path, exception = dirs_src[other_mode][key] - # Do not fall back to something we cannot write to. - if exception: - if check_other_mode: - logger.info(" .. despite 'check_other_mode'\n" - " and 'other_mode' 'path' of '%s'\n" - " it excepted with: '%s' in knownfolders.py" % (path, - type(exception).__name__)) - else: - logger.info(" .. 'check_other_mode' is False,\n" - " and 'other_mode' 'path' is '%s'\n" - " but it excepted anyway with: '%s' in knownfolders.py" % (path, type(exception).__name__)) - return None - if not check_other_mode: - logger.info(" .. due to lack of 'check_other_mode' not picking\n" - " non-excepting path of '%s'\n in knownfolders.py" % (path)) - return None - return path - def quoted(s): """ @@ -151,9 +86,9 @@ def to_bytes(var, codec=locale.getpreferredencoding()): return var -unicode_root_prefix = to_unicode(sys.prefix) +unicode_root_prefix = to_unicode(DEFAULT_BASE_PREFIX) if u'\\envs\\' in unicode_root_prefix: - logger.warn('menuinst called from non-root env %s', unicode_root_prefix) + logger.warning('menuinst called from non-root env %s', unicode_root_prefix) def substitute_env_variables(text, dir): diff --git a/menuinst/_schema.py b/menuinst/_schema.py new file mode 100644 index 00000000..6d01265e --- /dev/null +++ b/menuinst/_schema.py @@ -0,0 +1,407 @@ +""" +Generate JSON schemas from pydantic models +""" + +from pprint import pprint +from typing import Optional, Union, List, Literal, Dict +from pathlib import Path +from logging import getLogger +import json + +from pydantic import BaseModel as _BaseModel, Field, constr, conlist + +log = getLogger(__name__) + + +class BaseModel(_BaseModel): + class Config: + extra = "forbid" + + +class MenuItemMetadata(BaseModel): + name: constr(min_length=1) = Field(..., description="The name of the menu item") + description: str = Field( + ..., description="A longer description of the menu item. Shown on popup messages." + ) + icon: constr(min_length=1) = Field( + None, description="Path to the file representing or containing the icon." + ) + precommand: constr(min_length=1) = Field( + None, + description="(Simple, preferrably single-line) logic to run before the command is run. " + "Runs before the env is activated, if that applies." + ) + precreate: constr(min_length=1) = Field( + None, + description="(Simple, preferrably single-line) logic to run before the shortcut is created." + ) + command: conlist(str, min_items=1) = Field( + ..., + description="Command to run with the menu item, expressed as a " + "list of strings where each string is an argument", + ) + working_dir: constr(min_length=1) = Field( + None, + description="Working directory for the running process. " + "Defaults to user directory on each platform.", + ) + activate: bool = Field( + True, + description="Whether to activate the target environment before running `command`.", + ) + terminal: bool = Field( + False, + description="Whether run the program in a terminal/console or not. " + "On Windows, it only has an effect if activate is true. " + "On MacOS, arguments are ignored.", + ) + + +class OptionalMenuItemMetadata(MenuItemMetadata): + """ + Same as MenuItemMetadata, but all is optional. + + Note: + * This needs to be kept up-to-date with MenuItemMetadata! + * Default value is always None. + """ + + name: Optional[constr(min_length=1)] = Field(None, description="The name of the menu item") + description: Optional[str] = Field( + None, description="A longer description of the menu item. Shown on popup messages." + ) + icon: Optional[constr(min_length=1)] = Field( + None, description="Path to the file representing or containing the icon." + ) + command: Optional[conlist(str, min_items=1)] = Field( + None, + description="Command to run with the menu item, expressed as a " + "list of strings where each string is an argument", + ) + working_dir: Optional[constr(min_length=1)] = Field( + None, + description="Working directory for the running process. " + "Defaults to user directory on each platform.", + ) + precommand: Optional[constr(min_length=1)] = Field( + None, + description="(Simple, preferrably single-line) logic to run before the command is run. " + "Runs before the env is activated, if that applies." + ) + precreate: Optional[constr(min_length=1)] = Field( + None, + description="(Simple, preferrably single-line) logic to run before the shortcut is created." + ) + activate: Optional[bool] = Field( + None, + description="Whether to activate the target environment before running `command`.", + ) + terminal: Optional[bool] = Field( + None, + description="Whether run the program in a terminal/console or not. " + "On Windows, it only has an effect if activate is true. " + "On MacOS, arguments are ignored.", + ) + + + +class MenuInstSchema(BaseModel): + "Metadata required to create menu items across operating systems with `menuinst`" + + class MenuItem(MenuItemMetadata): + "Instructions to create a menu item across operating systems." + + class Platforms(BaseModel): + "Platform specific options. Presence of a platform enables menu items in that platform" + + class Windows(OptionalMenuItemMetadata): + "Windows-specific instructions. You can override global keys here if needed" + + desktop: Optional[bool] = Field( + True, + description="Whether to create a desktop icon in " + "addition to the Start Menu item.", + ) + quicklaunch: Optional[bool] = Field( + True, + description="Whether to create a quick launch icon in " + "addition to the Start Menu item.", + ) + + class Linux(OptionalMenuItemMetadata): + """Linux-specific instructions. Check + https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#recognized-keys + for more information. You can override global keys here if needed""" + + Categories: Optional[Union[List[str], constr(regex="^.+;$")]] = Field( + None, + description="Categories in which the entry should be shown in a menu. " + "See 'Registered categories' in " + "http://www.freedesktop.org/Standards/menu-spec.", + ) + DBusActivatable: Optional[bool] = Field( + None, + description="A boolean value specifying if D-Bus activation " + "is supported for this application.", + ) + GenericName: Optional[str] = Field( + None, + description="Generic name of the application; e.g. if the name is 'conda', " + "this would be 'Package Manager'.", + ) + Hidden: Optional[bool] = Field( + None, + description="Disable shortcut, signaling a missing resource.", + ) + Implements: Optional[Union[List[str], constr(regex="^.+;$")]] = Field( + None, + description="List of supported interfaces. See " + "https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#interfaces", + ) + Keywords: Optional[Union[List[str], constr(regex="^.+;$")]] = Field( + None, + description="Additional terms to describe this shortcut to aid in searching.", + ) + MimeType: Optional[Union[List[str], constr(regex="^.+;$")]] = Field( + None, + description="The MIME type(s) supported by this application.", + ) + NoDisplay: Optional[bool] = Field( + None, + description="Do not show this item in the menu. Useful to associate MIME types " + "and other registrations, without having an actual clickable item. Not to be " + "confused with 'Hidden'.", + ) + NotShowIn: Optional[Union[List[str], constr(regex="^.+;$")]] = Field( + None, + description="Desktop environments that should NOT display this item. " + "It'll check against $XDG_CURRENT_DESKTOP.", + ) + OnlyShowIn: Optional[Union[List[str], constr(regex="^.+;$")]] = Field( + None, + description="Desktop environments that should display this item. " + "It'll check against $XDG_CURRENT_DESKTOP.", + ) + PrefersNonDefaultGPU: Optional[bool] = Field( + None, + description="Hint that the app prefers to be run on a more powerful discrete " + "GPU if available", + ) + StartupNotify: Optional[bool] = Field( + None, + description="Advanced. See " + "https://www.freedesktop.org/wiki/Specifications/startup-notification-spec/", + ) + StartupWMClass: Optional[str] = Field( + None, + description="Advanced. See " + "https://www.freedesktop.org/wiki/Specifications/startup-notification-spec/", + ) + TryExec: Optional[str] = Field( + None, + description="Filename or absolute path to an executable file on disk used to " + "determine if the program is actually installed and can be run. If the test " + "fails, the shortcut might be ignored / hidden.", + ) + + class MacOS(OptionalMenuItemMetadata): + """Mac-specific instructions. Check these URLs for more info: + - CF* keys: https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html + - LS* keys: https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/LaunchServicesKeys.html + - entitlements: list those which should be true for the shortcut signing + See https://developer.apple.com/documentation/bundleresources/entitlements. + + You can also override global keys here if needed. + """ + + class _CFBundleURLTypes(BaseModel): + "Describes a URL scheme associated with the app." + CFBundleTypeRole: Literal["Editor", "Viewer", "Shell", "None"] = Field( + ..., + description="This key specifies the app's role with respect to the URL." + ) + CFBundleURLSchemes: List[str] = Field( + ..., + description="URL schemes / protocols handled by this type (e.g. 'mailto').", + ) + CFBundleURLName: Optional[str] = Field( + None, + description="Abstract name for this URL type. Uniqueness recommended.", + ) + CFBundleURLIconFile: Optional[str] = Field( + None, + description="Name of the icon image file (minus the .icns extension).", + ) + + class _CFBundleDocumentTypes(BaseModel): + "Describes a document type associated with the app." + CFBundleTypeIconFile: Optional[str] = Field( + None, + description="Name of the icon image file (minus the .icns extension).", + ) + CFBundleTypeName: str = Field( + ..., + description="Abstract name for this document type. Uniqueness recommended.", + ) + CFBundleTypeRole: Literal["Editor", "Viewer", "Shell", "None"] = Field( + ..., + description="This key specifies the app's role with respect to the type." + ) + LSItemContentTypes: List[str] = Field( + ..., + description="List of UTI strings defining a supported file type; e.g. for " + "PNG files, use 'public.png'. Sync with 'NSExportableTypes' key with the " + "appropriate entries" + ) + LSHandlerRank: Literal["Owner", "Default", "Alternate"] = Field( + ..., + description="Determines how Launch Services ranks this app among the apps " + "that declare themselves editors or viewers of files of this type." + ) + + CFBundleDisplayName: Optional[str] = Field( + None, + description="Display name of the bundle, visible to users and used by Siri. If " + "not provided, 'menuinst' will use the 'name' field.", + ) + CFBundleIdentifier: Optional[str] = Field( + None, + description="", + ) + CFBundleName: Optional[constr(max_length=16)] = Field( + None, + description="Short name of the bundle. Maybe used if 'CFBundleDisplayName' is " + "absent. If not provided, 'menuinst' will generate one from the 'name' field.", + ) + CFBundleSpokenName: Optional[str] = Field( + None, + description="Suitable replacement for text-to-speech operations on the app " + "For example, 'my app one two three' instead of 'MyApp123'.", + ) + CFBundleVersion: Optional[constr(regex=r"^\S+$")] = Field( + None, + description="Build version number for the bundle. In the context of 'menuinst' " + "this can be used to signal a new version of the menu item for the same " + "application version.", + ) + CFBundleURLTypes: Optional[List[_CFBundleURLTypes]] = Field( + None, + description="URL types supported by this app.", + ) + CFBundleDocumentTypes: Optional[List[_CFBundleDocumentTypes]] = Field( + None, + description="Document types supported by this app.", + ) + LSApplicationCategoryType: Optional[constr(regex=r"^public\.app-category\.\S+$")] = Field( + None, + description="The App Store uses this string to determine the appropriate " + "categorization for the app", + ) + LSBackgroundOnly: Optional[bool] = Field( + None, + description="Specifies whether this app runs only in the background.", + ) + LSEnvironment: Optional[Dict[str, str]] = Field( + None, + description="List of key-value pairs used to define environment variables.", + ) + LSMinimumSystemVersion: Optional[constr(regex=r"^\d+\.\d+\.\d+$")] = Field( + None, + description="Minimum version of macOS required for this app to run, as x.y.z. " + "For example, for macOS v10.4 and later, use '10.4.0'.", + ) + LSMultipleInstancesProhibited: Optional[bool] = Field( + None, + description="Whether an app is prohibited from running simultaneously in " + "multiple user sessions", + ) + LSRequiresNativeExecution: Optional[bool] = Field( + None, + description="If true, prevent a universal binary from being run under Rosetta " + "emulation on an Intel-based Mac", + ) + entitlements: Optional[List[constr(regex=r"[a-z0-9\.\-]+")]] = Field( + None, + description="List of permissions to request for the launched application. " + "See https://developer.apple.com/documentation/bundleresources/entitlements " + "for a full list of possible values.", + ) + link_in_bundle: Optional[Dict[constr(min_length=1), constr(regex=r"^(?!\/)(?!\.\./).*")]] = Field( + None, + description="Paths that should be symlinked into the shortcut app bundle. " + "It takes a mapping of source to destination paths. Destination paths must be " + "relative. Placeholder `{{ MENU_ITEM_LOCATION }}` can be useful.", + ) + + win: Optional[Windows] + linux: Optional[Linux] + osx: Optional[MacOS] + + platforms: Platforms + + menu_name: constr(min_length=1) = Field( + description="Name for the category containing the items specified in `menu_items`." + ) + menu_items: conlist(MenuItem, min_items=1) = Field( + description="List of menu entries to create across main desktop systems" + ) + + id_: Literal["https://schemas.conda.io/menuinst-1.schema.json"] = Field( + description="Version of the menuinst schema", + alias="$id", + ) + + schema_: Literal["https://json-schema.org/draft-07/schema"] = Field( + description="Standard of the JSON schema we adhere to", + alias="$schema", + ) + + +def dump_schema_to_json(write=True): + if write: + here = Path(__file__).parent + schema = MenuInstSchema.schema_json(indent=2) + print(schema) + with open(here / "data" / "menuinst.schema.json", "w") as f: + f.write(schema) + return MenuInstSchema.schema() + + +def dump_default_to_json(write=True): + here = Path(__file__).parent + default = MenuInstSchema.MenuItem( + name="Default", + description="", + command=["replace", "this"], + platforms={} + ).dict() + def platform_default(platform): + return { + k: v + for k, v in getattr(MenuInstSchema.MenuItem.Platforms, platform)().dict().items() + if k not in MenuInstSchema.MenuItem.__fields__ + } + default["platforms"] = { + "win": platform_default("Windows"), + "osx": platform_default("MacOS"), + "linux": platform_default("Linux"), + } + if write: + pprint(default) + with open(here / "data" / "menuinst.menu_item.default.json", "w") as f: + json.dump(default, f, indent=2) + return default + + +def validate(metadata_or_path): + if isinstance(metadata_or_path, (str, Path)): + with open(metadata_or_path) as f: + metadata = json.load(f) + else: + metadata = metadata_or_path + return MenuInstSchema(**metadata) + + +if __name__ == "__main__": + dump_schema_to_json() + dump_default_to_json() diff --git a/menuinst/_version.py b/menuinst/_version.py deleted file mode 100644 index c64fca00..00000000 --- a/menuinst/_version.py +++ /dev/null @@ -1,460 +0,0 @@ - -# This file helps to compute a version number in source trees obtained from -# git-archive tarball (such as those provided by githubs download-from-tag -# feature). Distribution tarballs (built by setup.py sdist) and build -# directories (produced by setup.py build) will contain a much shorter file -# that just contains the computed version number. - -# This file is released into the public domain. Generated by -# versioneer-0.15 (https://github.com/warner/python-versioneer) - -import errno -import os -import re -import subprocess -import sys - - -def get_keywords(): - # these strings will be replaced by git during git-archive. - # setup.py/versioneer.py will grep for the variable names, so they must - # each be defined on a line of their own. _version.py will just call - # get_keywords(). - git_refnames = "$Format:%d$" - git_full = "$Format:%H$" - keywords = {"refnames": git_refnames, "full": git_full} - return keywords - - -class VersioneerConfig: - pass - - -def get_config(): - # these strings are filled in when 'setup.py versioneer' creates - # _version.py - cfg = VersioneerConfig() - cfg.VCS = "git" - cfg.style = "pep440" - cfg.tag_prefix = "" - cfg.parentdir_prefix = "menuinst-" - cfg.versionfile_source = "menuinst/_version.py" - cfg.verbose = False - return cfg - - -class NotThisMethod(Exception): - pass - - -LONG_VERSION_PY = {} -HANDLERS = {} - - -def register_vcs_handler(vcs, method): # decorator - def decorate(f): - if vcs not in HANDLERS: - HANDLERS[vcs] = {} - HANDLERS[vcs][method] = f - return f - return decorate - - -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False): - assert isinstance(commands, list) - p = None - for c in commands: - try: - dispcmd = str([c] + args) - # remember shell=False, so use git.cmd on windows, not just git - p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None)) - break - except EnvironmentError: - e = sys.exc_info()[1] - if e.errno == errno.ENOENT: - continue - if verbose: - print("unable to run %s" % dispcmd) - print(e) - return None - else: - if verbose: - print("unable to find command, tried %s" % (commands,)) - return None - stdout = p.communicate()[0].strip() - if sys.version_info[0] >= 3: - stdout = stdout.decode() - if p.returncode != 0: - if verbose: - print("unable to run %s (error)" % dispcmd) - return None - return stdout - - -def versions_from_parentdir(parentdir_prefix, root, verbose): - # Source tarballs conventionally unpack into a directory that includes - # both the project name and a version string. - dirname = os.path.basename(root) - if not dirname.startswith(parentdir_prefix): - if verbose: - print("guessing rootdir is '%s', but '%s' doesn't start with " - "prefix '%s'" % (root, dirname, parentdir_prefix)) - raise NotThisMethod("rootdir doesn't start with parentdir_prefix") - return {"version": dirname[len(parentdir_prefix):], - "full-revisionid": None, - "dirty": False, "error": None} - - -@register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): - # the code embedded in _version.py can just fetch the value of these - # keywords. When used from setup.py, we don't want to import _version.py, - # so we do it with a regexp instead. This function is not used from - # _version.py. - keywords = {} - try: - f = open(versionfile_abs, "r") - for line in f.readlines(): - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - f.close() - except EnvironmentError: - pass - return keywords - - -@register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): - if not keywords: - raise NotThisMethod("no keywords at all, weird") - refnames = keywords["refnames"].strip() - if refnames.startswith("$Format"): - if verbose: - print("keywords are unexpanded, not using") - raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set([r.strip() for r in refnames.strip("()").split(",")]) - # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of - # just "foo-1.0". If we see a "tag: " prefix, prefer those. - TAG = "tag: " - tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) - if not tags: - # Either we're using git < 1.8.3, or there really are no tags. We use - # a heuristic: assume all version tags have a digit. The old git %d - # expansion behaves like git log --decorate=short and strips out the - # refs/heads/ and refs/tags/ prefixes that would let us distinguish - # between branches and tags. By ignoring refnames without digits, we - # filter out many common branch names like "release" and - # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r'\d', r)]) - if verbose: - print("discarding '%s', no digits" % ",".join(refs-tags)) - if verbose: - print("likely tags: %s" % ",".join(sorted(tags))) - for ref in sorted(tags): - # sorting will prefer e.g. "2.0" over "2.0rc1" - if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] - if verbose: - print("picking %s" % r) - return {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None - } - # no suitable tags, so version is "0+unknown", but full hex is still there - if verbose: - print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags"} - - -@register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): - # this runs 'git' from the root of the source tree. This only gets called - # if the git-archive 'subst' keywords were *not* expanded, and - # _version.py hasn't already been rewritten with a short version string, - # meaning we're inside a checked out source tree. - - if not os.path.exists(os.path.join(root, ".git")): - if verbose: - print("no .git in %s" % root) - raise NotThisMethod("no .git directory") - - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - # if there is a tag, this yields TAG-NUM-gHEX[-dirty] - # if there are no tags, this yields HEX[-dirty] (no NUM) - describe_out = run_command(GITS, ["describe", "--tags", "--dirty", - "--always", "--long"], - cwd=root) - # --long was added in git-1.5.5 - if describe_out is None: - raise NotThisMethod("'git describe' failed") - describe_out = describe_out.strip() - full_out = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) - if full_out is None: - raise NotThisMethod("'git rev-parse' failed") - full_out = full_out.strip() - - pieces = {} - pieces["long"] = full_out - pieces["short"] = full_out[:7] # maybe improved later - pieces["error"] = None - - # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] - # TAG might have hyphens. - git_describe = describe_out - - # look for -dirty suffix - dirty = git_describe.endswith("-dirty") - pieces["dirty"] = dirty - if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] - - # now we have TAG-NUM-gHEX or HEX - - if "-" in git_describe: - # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) - if not mo: - # unparseable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%s'" - % describe_out) - return pieces - - # tag - full_tag = mo.group(1) - if not full_tag.startswith(tag_prefix): - if verbose: - fmt = "tag '%s' doesn't start with prefix '%s'" - print(fmt % (full_tag, tag_prefix)) - pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" - % (full_tag, tag_prefix)) - return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] - - # distance: number of commits since tag - pieces["distance"] = int(mo.group(2)) - - # commit: short hex revision ID - pieces["short"] = mo.group(3) - - else: - # HEX: no tags - pieces["closest-tag"] = None - count_out = run_command(GITS, ["rev-list", "HEAD", "--count"], - cwd=root) - pieces["distance"] = int(count_out) # total number of commits - - return pieces - - -def plus_or_dot(pieces): - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces): - # now build up version string, with post-release "local version - # identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you - # get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty - - # exceptions: - # 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] - - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += plus_or_dot(pieces) - rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_pre(pieces): - # TAG[.post.devDISTANCE] . No -dirty - - # exceptions: - # 1: no tags. 0.post.devDISTANCE - - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += ".post.dev%d" % pieces["distance"] - else: - # exception #1 - rendered = "0.post.dev%d" % pieces["distance"] - return rendered - - -def render_pep440_post(pieces): - # TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that - # .dev0 sorts backwards (a dirty tree will appear "older" than the - # corresponding clean one), but you shouldn't be releasing software with - # -dirty anyways. - - # exceptions: - # 1: no tags. 0.postDISTANCE[.dev0] - - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%s" % pieces["short"] - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += "+g%s" % pieces["short"] - return rendered - - -def render_pep440_old(pieces): - # TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. - - # exceptions: - # 1: no tags. 0.postDISTANCE[.dev0] - - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - return rendered - - -def render_git_describe(pieces): - # TAG[-DISTANCE-gHEX][-dirty], like 'git describe --tags --dirty - # --always' - - # exceptions: - # 1: no tags. HEX[-dirty] (note: no 'g' prefix) - - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render_git_describe_long(pieces): - # TAG-DISTANCE-gHEX[-dirty], like 'git describe --tags --dirty - # --always -long'. The distance/hash is unconditional. - - # exceptions: - # 1: no tags. HEX[-dirty] (note: no 'g' prefix) - - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render(pieces, style): - if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"]} - - if not style or style == "default": - style = "pep440" # the default - - if style == "pep440": - rendered = render_pep440(pieces) - elif style == "pep440-pre": - rendered = render_pep440_pre(pieces) - elif style == "pep440-post": - rendered = render_pep440_post(pieces) - elif style == "pep440-old": - rendered = render_pep440_old(pieces) - elif style == "git-describe": - rendered = render_git_describe(pieces) - elif style == "git-describe-long": - rendered = render_git_describe_long(pieces) - else: - raise ValueError("unknown style '%s'" % style) - - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None} - - -def get_versions(): - # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have - # __file__, we can work backwards from there to the root. Some - # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which - # case we can only use expanded keywords. - - cfg = get_config() - verbose = cfg.verbose - - try: - return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, - verbose) - except NotThisMethod: - pass - - try: - root = os.path.realpath(__file__) - # versionfile_source is the relative path from the top of the source - # tree (where the .git directory might live) to this file. Invert - # this to find the root from __file__. - for i in cfg.versionfile_source.split('/'): - root = os.path.dirname(root) - except NameError: - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to find root of source tree"} - - try: - pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) - return render(pieces, cfg.style) - except NotThisMethod: - pass - - try: - if cfg.parentdir_prefix: - return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) - except NotThisMethod: - pass - - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to compute version"} diff --git a/menuinst/api.py b/menuinst/api.py new file mode 100644 index 00000000..15454527 --- /dev/null +++ b/menuinst/api.py @@ -0,0 +1,130 @@ +""" +""" + +from os import PathLike +import sys +from typing import Union, List, Tuple, Literal, Optional, Callable, Any +from pathlib import Path +import warnings +import json +from logging import getLogger + +from .platforms import Menu, MenuItem +from .utils import elevate_as_needed, DEFAULT_PREFIX, DEFAULT_BASE_PREFIX + +log = getLogger(__name__) + + +__all__ = [ + "install", + "remove", + "install_all", + "remove_all", +] + + +def _load( + metadata_or_path: Union[PathLike, dict], + target_prefix: Optional[PathLike] = None, + base_prefix: Optional[PathLike] = None, + _mode: Union[Literal["user"], Literal["system"]] = "user", +) -> Tuple[Menu, List[MenuItem]]: + target_prefix = target_prefix or DEFAULT_PREFIX + base_prefix = base_prefix or DEFAULT_BASE_PREFIX + if isinstance(metadata_or_path, (str, Path)): + with open(metadata_or_path) as f: + metadata = json.load(f) + else: + metadata = metadata_or_path + menu = Menu(metadata["menu_name"], target_prefix, base_prefix, _mode) + menu_items = [MenuItem(menu, item) for item in metadata["menu_items"]] + return menu, menu_items + + +@elevate_as_needed +def install( + metadata_or_path: Union[PathLike, dict], + *, + target_prefix: Optional[PathLike] = None, + base_prefix: Optional[PathLike] = None, + _mode: Union[Literal["user"], Literal["system"]] = "user", +) -> List[PathLike]: + target_prefix = target_prefix or DEFAULT_PREFIX + base_prefix = base_prefix or DEFAULT_BASE_PREFIX + menu, menu_items = _load(metadata_or_path, target_prefix, base_prefix, _mode) + if not any(item.enabled_for_platform() for item in menu_items): + warnings.warn(f"Metadata for {menu.name} is not enabled for {sys.platform}") + return () + + paths = [] + paths += menu.create() + for menu_item in menu_items: + paths += menu_item.create() + + return paths + + +@elevate_as_needed +def remove( + metadata_or_path: Union[PathLike, dict], + *, + target_prefix: Optional[PathLike] = None, + base_prefix: Optional[PathLike] = None, + _mode: Union[Literal["user"], Literal["system"]] = "user", +) -> List[PathLike]: + target_prefix = target_prefix or DEFAULT_PREFIX + base_prefix = base_prefix or DEFAULT_BASE_PREFIX + menu, menu_items = _load(metadata_or_path, target_prefix, base_prefix, _mode) + if not any(item.enabled_for_platform() for item in menu_items): + warnings.warn(f"Metadata for {menu.name} is not enabled for {sys.platform}") + return () + + paths = [] + for menu_item in menu_items: + paths += menu_item.remove() + paths += menu.remove() + + return paths + + +@elevate_as_needed +def install_all( + *, + target_prefix: Optional[PathLike] = None, + base_prefix: Optional[PathLike] = None, + filter: Union[Callable, None] = None, + _mode: Union[Literal["user"], Literal["system"]] = "user", +) -> List[List[PathLike]]: + target_prefix = target_prefix or DEFAULT_PREFIX + base_prefix = base_prefix or DEFAULT_BASE_PREFIX + return _process_all(install, target_prefix, base_prefix, filter, _mode) + + +@elevate_as_needed +def remove_all( + *, + target_prefix: Optional[PathLike] = None, + base_prefix: Optional[PathLike] = None, + filter: Union[Callable, None] = None, + _mode: Union[Literal["user"], Literal["system"]] = "user", +) -> List[List[Union[str, PathLike]]]: + target_prefix = target_prefix or DEFAULT_PREFIX + base_prefix = base_prefix or DEFAULT_BASE_PREFIX + return _process_all(remove, target_prefix, base_prefix, filter, _mode) + + +def _process_all( + function: Callable, + target_prefix: Optional[PathLike] = None, + base_prefix: Optional[PathLike] = None, + filter: Union[Callable, None] = None, + _mode: Union[Literal["user"], Literal["system"]] = "user", +) -> List[Any]: + target_prefix = target_prefix or DEFAULT_PREFIX + base_prefix = base_prefix or DEFAULT_BASE_PREFIX + jsons = (Path(target_prefix) / "Menu").glob("*.json") + results = [] + for path in jsons: + if filter is not None and filter(path): + results.append(function(path, target_prefix, base_prefix, _mode)) + return results diff --git a/menuinst/darwin.py b/menuinst/darwin.py deleted file mode 100644 index 481c84dd..00000000 --- a/menuinst/darwin.py +++ /dev/null @@ -1,124 +0,0 @@ -# Copyright (c) 2008-2011 by Enthought, Inc. -# Copyright (c) 2013 Continuum Analytics, Inc. -# All rights reserved. - -import os -import sys -import shutil -from os.path import basename, join -from plistlib import Plist, writePlist - -from utils import rm_rf - - -class Menu(object): - def __init__(self, unused_name, prefix, env_name, mode=None): - self.prefix = prefix - self.env_name = env_name - def create(self): - pass - def remove(self): - pass - - -class ShortCut(object): - - def __init__(self, menu, shortcut): - self.shortcut = shortcut - self.prefix = menu.prefix - self.name = shortcut['name'] - self.path = '/Applications/%s.app' % self.name - self.shortcut = shortcut - - def remove(self): - rm_rf(self.path) - - def create(self): - Application(self.path, self.shortcut, self.prefix).create() - - -class Application(object): - """ - Class for creating an application folder on OSX. The application may - be standalone executable, but more likely a Python script which is - interpreted by the framework Python interpreter. - """ - def __init__(self, app_path, shortcut, prefix, env_name, env_setup_cmd): - """ - Required: - --------- - shortcut is a dictionary defining a shortcut per the AppInst standard. - """ - # Store the required values out of the shortcut definition. - self.app_path = app_path - self.prefix = prefix - self.name = shortcut['name'] - self.cmd = shortcut['cmd'] - self.icns = shortcut['icns'] - self.env_name = env_name - self.env_setup_cmd = env_setup_cmd - - - for a, b in [ - ('${BIN_DIR}', join(prefix, 'bin')), - ('${MENU_DIR}', join(prefix, 'Menu')), - ]: - self.cmd = self.cmd.replace(a, b) - self.icns = self.icns.replace(a, b) - - # Calculate some derived values just once. - self.contents_dir = join(self.app_path, 'Contents') - self.resources_dir = join(self.contents_dir, 'Resources') - self.macos_dir = join(self.contents_dir, 'MacOS') - self.executable = self.name - self.executable_path = join(self.macos_dir, self.executable) - - def create(self): - self._create_dirs() - self._write_pkginfo() - shutil.copy(self.icns, self.resources_dir) - self._writePlistInfo() - self._write_script() - - def _create_dirs(self): - rm_rf(self.app_path) - os.makedirs(self.resources_dir) - os.makedirs(self.macos_dir) - - def _write_pkginfo(self): - fo = open(join(self.contents_dir, 'PkgInfo'), 'w') - fo.write(('APPL%s????' % self.name.replace(' ', ''))[:8]) - fo.close() - - def _writePlistInfo(self): - """ - Writes the Info.plist file in the Contests directory. - """ - pl = Plist( - CFBundleExecutable=self.executable, - CFBundleGetInfoString='%s-1.0.0' % self.name, - CFBundleIconFile=basename(self.icns), - CFBundleIdentifier='com.%s' % self.name, - CFBundlePackageType='APPL', - CFBundleVersion='1.0.0', - CFBundleShortVersionString='1.0.0', - ) - writePlist(pl, join(self.contents_dir, 'Info.plist')) - - def _write_script(self): - fo = open(self.executable_path, 'w') - fo.write( """\ -#!/bin/bash -%s/python.app/Contents/MacOS/python %s -""" % (self.prefix, self.cmd)) - fo.close() - os.chmod(self.executable_path, 0o755) - - -if __name__ == '__main__': - sc = { - "name": "Launcher", - "cmd": "${BIN_DIR}/launcher", - "icns": "${MENU_DIR}/launcher.icns", - } - ShortCut(None, sc).remove() diff --git a/menuinst/data/menuinst.menu_item.default.json b/menuinst/data/menuinst.menu_item.default.json new file mode 100644 index 00000000..1544e37f --- /dev/null +++ b/menuinst/data/menuinst.menu_item.default.json @@ -0,0 +1,53 @@ +{ + "name": "Default", + "description": "", + "icon": null, + "precommand": null, + "precreate": null, + "command": [ + "replace", + "this" + ], + "working_dir": null, + "activate": true, + "terminal": false, + "platforms": { + "win": { + "desktop": true, + "quicklaunch": true + }, + "osx": { + "CFBundleDisplayName": null, + "CFBundleIdentifier": null, + "CFBundleName": null, + "CFBundleSpokenName": null, + "CFBundleVersion": null, + "CFBundleURLTypes": null, + "CFBundleDocumentTypes": null, + "LSApplicationCategoryType": null, + "LSBackgroundOnly": null, + "LSEnvironment": null, + "LSMinimumSystemVersion": null, + "LSMultipleInstancesProhibited": null, + "LSRequiresNativeExecution": null, + "entitlements": null, + "link_in_bundle": null + }, + "linux": { + "Categories": null, + "DBusActivatable": null, + "GenericName": null, + "Hidden": null, + "Implements": null, + "Keywords": null, + "MimeType": null, + "NoDisplay": null, + "NotShowIn": null, + "OnlyShowIn": null, + "PrefersNonDefaultGPU": null, + "StartupNotify": null, + "StartupWMClass": null, + "TryExec": null + } + } +} \ No newline at end of file diff --git a/menuinst/data/menuinst.schema.json b/menuinst/data/menuinst.schema.json new file mode 100644 index 00000000..62f9814a --- /dev/null +++ b/menuinst/data/menuinst.schema.json @@ -0,0 +1,660 @@ +{ + "title": "MenuInstSchema", + "description": "Metadata required to create menu items across operating systems with `menuinst`", + "type": "object", + "properties": { + "menu_name": { + "title": "Menu Name", + "description": "Name for the category containing the items specified in `menu_items`.", + "minLength": 1, + "type": "string" + }, + "menu_items": { + "title": "Menu Items", + "description": "List of menu entries to create across main desktop systems", + "minItems": 1, + "type": "array", + "items": { + "$ref": "#/definitions/MenuItem" + } + }, + "$id": { + "title": "$Id", + "description": "Version of the menuinst schema", + "enum": [ + "https://schemas.conda.io/menuinst-1.schema.json" + ], + "type": "string" + }, + "$schema": { + "title": "$Schema", + "description": "Standard of the JSON schema we adhere to", + "enum": [ + "https://json-schema.org/draft-07/schema" + ], + "type": "string" + } + }, + "required": [ + "menu_name", + "menu_items", + "$id", + "$schema" + ], + "additionalProperties": false, + "definitions": { + "Windows": { + "title": "Windows", + "description": "Windows-specific instructions. You can override global keys here if needed", + "type": "object", + "properties": { + "name": { + "title": "Name", + "description": "The name of the menu item", + "minLength": 1, + "type": "string" + }, + "description": { + "title": "Description", + "description": "A longer description of the menu item. Shown on popup messages.", + "type": "string" + }, + "icon": { + "title": "Icon", + "description": "Path to the file representing or containing the icon.", + "minLength": 1, + "type": "string" + }, + "precommand": { + "title": "Precommand", + "description": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the env is activated, if that applies.", + "minLength": 1, + "type": "string" + }, + "precreate": { + "title": "Precreate", + "description": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "minLength": 1, + "type": "string" + }, + "command": { + "title": "Command", + "description": "Command to run with the menu item, expressed as a list of strings where each string is an argument", + "minItems": 1, + "type": "array", + "items": { + "type": "string" + } + }, + "working_dir": { + "title": "Working Dir", + "description": "Working directory for the running process. Defaults to user directory on each platform.", + "minLength": 1, + "type": "string" + }, + "activate": { + "title": "Activate", + "description": "Whether to activate the target environment before running `command`.", + "type": "boolean" + }, + "terminal": { + "title": "Terminal", + "description": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if activate is true. On MacOS, arguments are ignored.", + "type": "boolean" + }, + "desktop": { + "title": "Desktop", + "description": "Whether to create a desktop icon in addition to the Start Menu item.", + "default": true, + "type": "boolean" + }, + "quicklaunch": { + "title": "Quicklaunch", + "description": "Whether to create a quick launch icon in addition to the Start Menu item.", + "default": true, + "type": "boolean" + } + }, + "additionalProperties": false + }, + "Linux": { + "title": "Linux", + "description": "Linux-specific instructions. Check\nhttps://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#recognized-keys\nfor more information. You can override global keys here if needed", + "type": "object", + "properties": { + "name": { + "title": "Name", + "description": "The name of the menu item", + "minLength": 1, + "type": "string" + }, + "description": { + "title": "Description", + "description": "A longer description of the menu item. Shown on popup messages.", + "type": "string" + }, + "icon": { + "title": "Icon", + "description": "Path to the file representing or containing the icon.", + "minLength": 1, + "type": "string" + }, + "precommand": { + "title": "Precommand", + "description": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the env is activated, if that applies.", + "minLength": 1, + "type": "string" + }, + "precreate": { + "title": "Precreate", + "description": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "minLength": 1, + "type": "string" + }, + "command": { + "title": "Command", + "description": "Command to run with the menu item, expressed as a list of strings where each string is an argument", + "minItems": 1, + "type": "array", + "items": { + "type": "string" + } + }, + "working_dir": { + "title": "Working Dir", + "description": "Working directory for the running process. Defaults to user directory on each platform.", + "minLength": 1, + "type": "string" + }, + "activate": { + "title": "Activate", + "description": "Whether to activate the target environment before running `command`.", + "type": "boolean" + }, + "terminal": { + "title": "Terminal", + "description": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if activate is true. On MacOS, arguments are ignored.", + "type": "boolean" + }, + "Categories": { + "title": "Categories", + "description": "Categories in which the entry should be shown in a menu. See 'Registered categories' in http://www.freedesktop.org/Standards/menu-spec.", + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string", + "pattern": "^.+;$" + } + ] + }, + "DBusActivatable": { + "title": "Dbusactivatable", + "description": "A boolean value specifying if D-Bus activation is supported for this application.", + "type": "boolean" + }, + "GenericName": { + "title": "Genericname", + "description": "Generic name of the application; e.g. if the name is 'conda', this would be 'Package Manager'.", + "type": "string" + }, + "Hidden": { + "title": "Hidden", + "description": "Disable shortcut, signaling a missing resource.", + "type": "boolean" + }, + "Implements": { + "title": "Implements", + "description": "List of supported interfaces. See https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#interfaces", + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string", + "pattern": "^.+;$" + } + ] + }, + "Keywords": { + "title": "Keywords", + "description": "Additional terms to describe this shortcut to aid in searching.", + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string", + "pattern": "^.+;$" + } + ] + }, + "MimeType": { + "title": "Mimetype", + "description": "The MIME type(s) supported by this application.", + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string", + "pattern": "^.+;$" + } + ] + }, + "NoDisplay": { + "title": "Nodisplay", + "description": "Do not show this item in the menu. Useful to associate MIME types and other registrations, without having an actual clickable item. Not to be confused with 'Hidden'.", + "type": "boolean" + }, + "NotShowIn": { + "title": "Notshowin", + "description": "Desktop environments that should NOT display this item. It'll check against $XDG_CURRENT_DESKTOP.", + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string", + "pattern": "^.+;$" + } + ] + }, + "OnlyShowIn": { + "title": "Onlyshowin", + "description": "Desktop environments that should display this item. It'll check against $XDG_CURRENT_DESKTOP.", + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string", + "pattern": "^.+;$" + } + ] + }, + "PrefersNonDefaultGPU": { + "title": "Prefersnondefaultgpu", + "description": "Hint that the app prefers to be run on a more powerful discrete GPU if available", + "type": "boolean" + }, + "StartupNotify": { + "title": "Startupnotify", + "description": "Advanced. See https://www.freedesktop.org/wiki/Specifications/startup-notification-spec/", + "type": "boolean" + }, + "StartupWMClass": { + "title": "Startupwmclass", + "description": "Advanced. See https://www.freedesktop.org/wiki/Specifications/startup-notification-spec/", + "type": "string" + }, + "TryExec": { + "title": "Tryexec", + "description": "Filename or absolute path to an executable file on disk used to determine if the program is actually installed and can be run. If the test fails, the shortcut might be ignored / hidden.", + "type": "string" + } + }, + "additionalProperties": false + }, + "_CFBundleURLTypes": { + "title": "_CFBundleURLTypes", + "description": "Describes a URL scheme associated with the app.", + "type": "object", + "properties": { + "CFBundleTypeRole": { + "title": "Cfbundletyperole", + "description": "This key specifies the app's role with respect to the URL.", + "enum": [ + "Editor", + "Viewer", + "Shell", + "None" + ], + "type": "string" + }, + "CFBundleURLSchemes": { + "title": "Cfbundleurlschemes", + "description": "URL schemes / protocols handled by this type (e.g. 'mailto').", + "type": "array", + "items": { + "type": "string" + } + }, + "CFBundleURLName": { + "title": "Cfbundleurlname", + "description": "Abstract name for this URL type. Uniqueness recommended.", + "type": "string" + }, + "CFBundleURLIconFile": { + "title": "Cfbundleurliconfile", + "description": "Name of the icon image file (minus the .icns extension).", + "type": "string" + } + }, + "required": [ + "CFBundleTypeRole", + "CFBundleURLSchemes" + ], + "additionalProperties": false + }, + "_CFBundleDocumentTypes": { + "title": "_CFBundleDocumentTypes", + "description": "Describes a document type associated with the app.", + "type": "object", + "properties": { + "CFBundleTypeIconFile": { + "title": "Cfbundletypeiconfile", + "description": "Name of the icon image file (minus the .icns extension).", + "type": "string" + }, + "CFBundleTypeName": { + "title": "Cfbundletypename", + "description": "Abstract name for this document type. Uniqueness recommended.", + "type": "string" + }, + "CFBundleTypeRole": { + "title": "Cfbundletyperole", + "description": "This key specifies the app's role with respect to the type.", + "enum": [ + "Editor", + "Viewer", + "Shell", + "None" + ], + "type": "string" + }, + "LSItemContentTypes": { + "title": "Lsitemcontenttypes", + "description": "List of UTI strings defining a supported file type; e.g. for PNG files, use 'public.png'. Sync with 'NSExportableTypes' key with the appropriate entries", + "type": "array", + "items": { + "type": "string" + } + }, + "LSHandlerRank": { + "title": "Lshandlerrank", + "description": "Determines how Launch Services ranks this app among the apps that declare themselves editors or viewers of files of this type.", + "enum": [ + "Owner", + "Default", + "Alternate" + ], + "type": "string" + } + }, + "required": [ + "CFBundleTypeName", + "CFBundleTypeRole", + "LSItemContentTypes", + "LSHandlerRank" + ], + "additionalProperties": false + }, + "MacOS": { + "title": "MacOS", + "description": "Mac-specific instructions. Check these URLs for more info:\n- CF* keys: https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html\n- LS* keys: https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/LaunchServicesKeys.html\n- entitlements: list those which should be true for the shortcut signing\n See https://developer.apple.com/documentation/bundleresources/entitlements.\n\nYou can also override global keys here if needed.", + "type": "object", + "properties": { + "name": { + "title": "Name", + "description": "The name of the menu item", + "minLength": 1, + "type": "string" + }, + "description": { + "title": "Description", + "description": "A longer description of the menu item. Shown on popup messages.", + "type": "string" + }, + "icon": { + "title": "Icon", + "description": "Path to the file representing or containing the icon.", + "minLength": 1, + "type": "string" + }, + "precommand": { + "title": "Precommand", + "description": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the env is activated, if that applies.", + "minLength": 1, + "type": "string" + }, + "precreate": { + "title": "Precreate", + "description": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "minLength": 1, + "type": "string" + }, + "command": { + "title": "Command", + "description": "Command to run with the menu item, expressed as a list of strings where each string is an argument", + "minItems": 1, + "type": "array", + "items": { + "type": "string" + } + }, + "working_dir": { + "title": "Working Dir", + "description": "Working directory for the running process. Defaults to user directory on each platform.", + "minLength": 1, + "type": "string" + }, + "activate": { + "title": "Activate", + "description": "Whether to activate the target environment before running `command`.", + "type": "boolean" + }, + "terminal": { + "title": "Terminal", + "description": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if activate is true. On MacOS, arguments are ignored.", + "type": "boolean" + }, + "CFBundleDisplayName": { + "title": "Cfbundledisplayname", + "description": "Display name of the bundle, visible to users and used by Siri. If not provided, 'menuinst' will use the 'name' field.", + "type": "string" + }, + "CFBundleIdentifier": { + "title": "Cfbundleidentifier", + "type": "string" + }, + "CFBundleName": { + "title": "Cfbundlename", + "description": "Short name of the bundle. Maybe used if 'CFBundleDisplayName' is absent. If not provided, 'menuinst' will generate one from the 'name' field.", + "maxLength": 16, + "type": "string" + }, + "CFBundleSpokenName": { + "title": "Cfbundlespokenname", + "description": "Suitable replacement for text-to-speech operations on the app For example, 'my app one two three' instead of 'MyApp123'.", + "type": "string" + }, + "CFBundleVersion": { + "title": "Cfbundleversion", + "description": "Build version number for the bundle. In the context of 'menuinst' this can be used to signal a new version of the menu item for the same application version.", + "pattern": "^\\S+$", + "type": "string" + }, + "CFBundleURLTypes": { + "title": "Cfbundleurltypes", + "description": "URL types supported by this app.", + "type": "array", + "items": { + "$ref": "#/definitions/_CFBundleURLTypes" + } + }, + "CFBundleDocumentTypes": { + "title": "Cfbundledocumenttypes", + "description": "Document types supported by this app.", + "type": "array", + "items": { + "$ref": "#/definitions/_CFBundleDocumentTypes" + } + }, + "LSApplicationCategoryType": { + "title": "Lsapplicationcategorytype", + "description": "The App Store uses this string to determine the appropriate categorization for the app", + "pattern": "^public\\.app-category\\.\\S+$", + "type": "string" + }, + "LSBackgroundOnly": { + "title": "Lsbackgroundonly", + "description": "Specifies whether this app runs only in the background.", + "type": "boolean" + }, + "LSEnvironment": { + "title": "Lsenvironment", + "description": "List of key-value pairs used to define environment variables.", + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "LSMinimumSystemVersion": { + "title": "Lsminimumsystemversion", + "description": "Minimum version of macOS required for this app to run, as x.y.z. For example, for macOS v10.4 and later, use '10.4.0'.", + "pattern": "^\\d+\\.\\d+\\.\\d+$", + "type": "string" + }, + "LSMultipleInstancesProhibited": { + "title": "Lsmultipleinstancesprohibited", + "description": "Whether an app is prohibited from running simultaneously in multiple user sessions", + "type": "boolean" + }, + "LSRequiresNativeExecution": { + "title": "Lsrequiresnativeexecution", + "description": "If true, prevent a universal binary from being run under Rosetta emulation on an Intel-based Mac", + "type": "boolean" + }, + "entitlements": { + "title": "Entitlements", + "description": "List of permissions to request for the launched application. See https://developer.apple.com/documentation/bundleresources/entitlements for a full list of possible values.", + "type": "array", + "items": { + "type": "string", + "pattern": "[a-z0-9\\.\\-]+" + } + }, + "link_in_bundle": { + "title": "Link In Bundle", + "description": "Paths that should be symlinked into the shortcut app bundle. It takes a mapping of source to destination paths. Destination paths must be relative. Placeholder `{{ MENU_ITEM_LOCATION }}` can be useful.", + "type": "object", + "additionalProperties": { + "type": "string", + "pattern": "^(?!\\/)(?!\\.\\./).*" + } + } + }, + "additionalProperties": false + }, + "Platforms": { + "title": "Platforms", + "description": "Platform specific options. Presence of a platform enables menu items in that platform", + "type": "object", + "properties": { + "win": { + "$ref": "#/definitions/Windows" + }, + "linux": { + "$ref": "#/definitions/Linux" + }, + "osx": { + "$ref": "#/definitions/MacOS" + } + }, + "additionalProperties": false + }, + "MenuItem": { + "title": "MenuItem", + "description": "Instructions to create a menu item across operating systems.", + "type": "object", + "properties": { + "name": { + "title": "Name", + "description": "The name of the menu item", + "minLength": 1, + "type": "string" + }, + "description": { + "title": "Description", + "description": "A longer description of the menu item. Shown on popup messages.", + "type": "string" + }, + "icon": { + "title": "Icon", + "description": "Path to the file representing or containing the icon.", + "minLength": 1, + "type": "string" + }, + "precommand": { + "title": "Precommand", + "description": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the env is activated, if that applies.", + "minLength": 1, + "type": "string" + }, + "precreate": { + "title": "Precreate", + "description": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "minLength": 1, + "type": "string" + }, + "command": { + "title": "Command", + "description": "Command to run with the menu item, expressed as a list of strings where each string is an argument", + "minItems": 1, + "type": "array", + "items": { + "type": "string" + } + }, + "working_dir": { + "title": "Working Dir", + "description": "Working directory for the running process. Defaults to user directory on each platform.", + "minLength": 1, + "type": "string" + }, + "activate": { + "title": "Activate", + "description": "Whether to activate the target environment before running `command`.", + "default": true, + "type": "boolean" + }, + "terminal": { + "title": "Terminal", + "description": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if activate is true. On MacOS, arguments are ignored.", + "default": false, + "type": "boolean" + }, + "platforms": { + "$ref": "#/definitions/Platforms" + } + }, + "required": [ + "name", + "description", + "command", + "platforms" + ], + "additionalProperties": false + } + } +} \ No newline at end of file diff --git a/menuinst/data/osx_launcher_arm64 b/menuinst/data/osx_launcher_arm64 new file mode 100755 index 00000000..818c5fc1 Binary files /dev/null and b/menuinst/data/osx_launcher_arm64 differ diff --git a/menuinst/data/osx_launcher_x86_64 b/menuinst/data/osx_launcher_x86_64 new file mode 100755 index 00000000..ca03454c Binary files /dev/null and b/menuinst/data/osx_launcher_x86_64 differ diff --git a/menuinst/freedesktop.py b/menuinst/freedesktop.py deleted file mode 100644 index 8beacf7f..00000000 --- a/menuinst/freedesktop.py +++ /dev/null @@ -1,77 +0,0 @@ -# Copyright (c) 2008-2011 by Enthought, Inc. -# All rights reserved. - - -def make_desktop_entry(d): - """ - Create a desktop entry that conforms to the format of the Desktop Entry - Specification by freedesktop.org. See: - http://freedesktop.org/Standards/desktop-entry-spec - These should work for both KDE and Gnome2 - - An entry is a .desktop file that includes the application's type, - executable, name, etc. It will be placed in the location specified within - the passed dict. - """ - assert d['path'].endswith('.desktop') - - # default values - d.setdefault('comment', '') - d.setdefault('icon', '') - - # Format the command to a single string. - if isinstance(d['cmd'], list): - d['cmd'] = ' '.join(d['cmd']) - - assert isinstance(d['terminal'], bool) - d['terminal'] = {False: 'false', True: 'true'}[d['terminal']] - - fo = open(d['path'], "w") - fo.write("""\ -[Desktop Entry] -Type=Application -Encoding=UTF-8 -Name=%(name)s -Comment=%(comment)s -Exec=%(cmd)s -Terminal=%(terminal)s -Icon=%(icon)s -Categories=%(categories)s -""" % d) - - if d['tp'] == 'kde': - fo.write('OnlyShowIn=KDE\n') - else: - fo.write('NotShowIn=KDE\n') - - fo.close() - - -def make_directory_entry(d): - """ - Create a directory entry that conforms to the format of the Desktop Entry - Specification by freedesktop.org. See: - http://freedesktop.org/Standards/desktop-entry-spec - These should work for both KDE and Gnome2 - - An entry is a .directory file that includes the display name, icon, etc. - It will be placed in the location specified within the passed dict. The - filename can be explicitly specified, but if not provided, will default to - an escaped version of the name. - """ - assert d['path'].endswith('.directory') - - # default values - d.setdefault('comment', '') - d.setdefault('icon', '') - - fo = open(d['path'], "w") - fo.write("""\ -[Desktop Entry] -Type=Directory -Encoding=UTF-8 -Name=%(name)s -Comment=%(comment)s -Icon=%(icon)s -""" % d) - fo.close() diff --git a/menuinst/linux.py b/menuinst/linux.py deleted file mode 100644 index d645552b..00000000 --- a/menuinst/linux.py +++ /dev/null @@ -1,255 +0,0 @@ -# Copyright (c) 2008-2011 by Enthought, Inc. -# All rights reserved. -""" -The menu will be installed to both Gnome and KDE desktops if they are -available. -Note that the information required is sufficient to install application -menus on systems that follow the format of the Desktop Entry Specification -by freedesktop.org. See: - http://freedesktop.org/Standards/desktop-entry-spec -""" -import re -import os -import shutil -import sys -import time -import xml.etree.ElementTree as ET -from os.path import abspath, dirname, exists, expanduser, isdir, isfile, join - -from utils import rm_rf, get_executable -from freedesktop import make_desktop_entry, make_directory_entry - - -# datadir: contains the desktop and directory entries -# confdir: contains the XML menu files -sys_menu_file = '/etc/xdg/menus/applications.menu' -if os.getuid() == 0: - mode = 'system' - datadir = '/usr/share' - confdir = '/etc/xdg' -else: - mode = 'user' - datadir = os.environ.get('XDG_DATA_HOME', - abspath(expanduser('~/.local/share'))) - confdir = os.environ.get('XDG_CONFIG_HOME', - abspath(expanduser('~/.config'))) - -appdir = join(datadir, 'applications') -menu_file = join(confdir, 'menus/applications.menu') - - -def indent(elem, level=0): - """ - adds whitespace to the tree, so that it results in a pretty printed tree - """ - XMLindentation = " " # 4 spaces, just like in Python! - i = "\n" + level * XMLindentation - if len(elem): - if not elem.text or not elem.text.strip(): - elem.text = i + XMLindentation - for e in elem: - indent(e, level+1) - if not e.tail or not e.tail.strip(): - e.tail = i + XMLindentation - if not e.tail or not e.tail.strip(): - e.tail = i - else: - if level and (not elem.tail or not elem.tail.strip()): - elem.tail = i - - -def add_child(parent, tag, text=None): - """ - Add a child element of specified tag type to parent. - The new child element is returned. - """ - elem = ET.SubElement(parent, tag) - if text is not None: - elem.text = text - return elem - - -def is_valid_menu_file(): - try: - root = ET.parse(menu_file).getroot() - assert root is not None and root.tag == 'Menu' - return True - except: - return False - - -def write_menu_file(tree): - indent(tree.getroot()) - fo = open(menu_file, 'w') - fo.write("""\ - -""") - tree.write(fo) - fo.write('\n') - fo.close() - - -def ensure_menu_file(): - # ensure any existing version is a file - if exists(menu_file) and not isfile(menu_file): - rm_rf(menu_file) - - # ensure any existing file is actually a menu file - if isfile(menu_file): - # make a backup of the menu file to be edited - cur_time = time.strftime('%Y-%m-%d_%Hh%Mm%S') - backup_menu_file = "%s.%s" % (menu_file, cur_time) - shutil.copyfile(menu_file, backup_menu_file) - - if not is_valid_menu_file(): - os.remove(menu_file) - - # create a new menu file if one doesn't yet exist - if not isfile(menu_file): - fo = open(menu_file, 'w') - if mode == 'user': - merge = '%s' % sys_menu_file - else: - merge = '' - fo.write("Applications%s\n" % merge) - fo.close() - - -class Menu(object): - - def __init__(self, name, prefix, env_name, mode=None): - self.name = name - self.name_ = name + '_' - self.entry_fn = '%s.directory' % self.name - self.entry_path = join(datadir, 'desktop-directories', self.entry_fn) - self.prefix = prefix - self.env_name = env_name - - def create(self): - self._create_dirs() - self._create_directory_entry() - if is_valid_menu_file() and self._has_this_menu(): - return - ensure_menu_file() - self._add_this_menu() - - def remove(self): - rm_rf(self.entry_path) - for fn in os.listdir(appdir): - if fn.startswith(self.name_): - # found one shortcut, so don't remove the name from menu - return - self._remove_this_menu() - - def _remove_this_menu(self): - tree = ET.parse(menu_file) - root = tree.getroot() - for elt in root.findall('Menu'): - if elt.find('Name').text == self.name: - root.remove(elt) - write_menu_file(tree) - - def _has_this_menu(self): - root = ET.parse(menu_file).getroot() - return any(e.text == self.name for e in root.findall('Menu/Name')) - - def _add_this_menu(self): - tree = ET.parse(menu_file) - root = tree.getroot() - menu_elt = add_child(root, 'Menu') - add_child(menu_elt, 'Name', self.name) - add_child(menu_elt, 'Directory', self.entry_fn) - inc_elt = add_child(menu_elt, 'Include') - add_child(inc_elt, 'Category', self.name) - write_menu_file(tree) - - def _create_directory_entry(self): - # Create the menu resources. Note that the .directory files all go - # in the same directory. - d = dict(name=self.name, path=self.entry_path) - try: - import custom_tools - icon_path = join(dirname(custom_tools.__file__), 'menu.ico') - if isfile(icon_path): - d['icon'] = icon_path - except ImportError: - pass - make_directory_entry(d) - - def _create_dirs(self): - # Ensure the three directories we're going to write menu and shortcut - # resources to all exist. - for dir_path in [dirname(menu_file), - dirname(self.entry_path), - appdir]: - if not isdir(dir_path): - os.makedirs(dir_path) - - -class ShortCut(object): - - fn_pat = re.compile(r'[\w.-]+$') - - def __init__(self, menu, shortcut, env_setup_cmd): - # note that this is the path WITHOUT extension - fn = menu.name_ + shortcut['id'] - assert self.fn_pat.match(fn) - self.path = join(appdir, fn) - shortcut['categories'] = menu.name - self.shortcut = shortcut - for var_name in ('name', 'cmd'): - if var_name in shortcut: - setattr(self, var_name, shortcut[var_name]) - - self.prefix = menu.prefix if menu.prefix is not None else sys.prefix - self.env_name = menu.env_name - self.env_setup_cmd = env_setup_cmd - - - def create(self): - self._install_desktop_entry('gnome') - self._install_desktop_entry('kde') - - def remove(self): - for ext in ('.desktop', 'KDE.desktop'): - path = self.path + ext - rm_rf(path) - - def _install_desktop_entry(self, tp): - # Handle the special placeholders in the specified command. For a - # filebrowser request, we simply used the passed filebrowser. But - # for a webbrowser request, we invoke the Python standard lib's - # webbrowser script so we can force the url(s) to open in new tabs. - spec = self.shortcut.copy() - spec['tp'] = tp - - path = self.path - if tp == 'gnome': - filebrowser = 'gnome-open' - path += '.desktop' - elif tp == 'kde': - filebrowser = 'kfmclient openURL' - path += 'KDE.desktop' - - cmd = self.cmd - if cmd[0] == '{{FILEBROWSER}}': - cmd[0] = filebrowser - elif cmd[0] == '{{WEBBROWSER}}': - import webbrowser - executable = get_executable(self.prefix) - cmd[0:1] = [executable, webbrowser.__file__, '-t'] - - spec['cmd'] = cmd - spec['path'] = path - - # create the shortcuts - make_desktop_entry(spec) - - -if __name__ == '__main__': - rm_rf(menu_file) - Menu('Foo').create() - Menu('Bar').create() - Menu('Foo').remove() - Menu('Foo').remove() diff --git a/menuinst/platforms/__init__.py b/menuinst/platforms/__init__.py new file mode 100644 index 00000000..f561bce6 --- /dev/null +++ b/menuinst/platforms/__init__.py @@ -0,0 +1,23 @@ +import sys +from typing import Tuple + +from .base import Menu as BaseMenu, MenuItem as BaseMenuItem + + +def menu_api_for_platform(platform: str = sys.platform) -> Tuple[BaseMenu, BaseMenuItem]: + if platform == "win32": + from .win import WindowsMenu as Menu, WindowsMenuItem as MenuItem + + elif platform == "darwin": + from .osx import MacOSMenu as Menu, MacOSMenuItem as MenuItem + + elif platform.startswith("linux"): + from .linux import LinuxMenu as Menu, LinuxMenuItem as MenuItem + + else: + raise ValueError(f"platform {platform} is not supported") + + return Menu, MenuItem + + +Menu, MenuItem = menu_api_for_platform() diff --git a/menuinst/platforms/base.py b/menuinst/platforms/base.py new file mode 100644 index 00000000..a4b9b5c4 --- /dev/null +++ b/menuinst/platforms/base.py @@ -0,0 +1,249 @@ +""" +""" +import os +import sys +from typing import Union, List, Iterable, Literal, Dict, Any, Optional, Mapping +from pathlib import Path +from subprocess import check_output, run +from logging import getLogger +from copy import deepcopy +from tempfile import NamedTemporaryFile +import json + +from ..utils import slugify, data_path, deep_update, DEFAULT_PREFIX, DEFAULT_BASE_PREFIX + +log = getLogger(__name__) + + +class Menu: + def __init__( + self, + name: str, + prefix: str = DEFAULT_PREFIX, + base_prefix: str = DEFAULT_BASE_PREFIX, + mode: Union[Literal["user"], Literal["system"]] = "user", + ): + assert mode in ("user", "system"), f"mode={mode} must be `user` or `system`" + self.mode = mode + self.name = name + self.prefix = Path(prefix) + self.base_prefix = Path(base_prefix) + + self.env_name = None + + def create(self) -> List[Path]: + raise NotImplementedError + + def remove(self) -> List[Path]: + raise NotImplementedError + + def render(self, value: Any, slug: bool = False, extra: Dict = None) -> Any: + if not hasattr(value, "replace"): + return value + if extra: + placeholders = {**self.placeholders, **extra} + else: + placeholders = self.placeholders + for placeholder, replacement in placeholders.items(): + value = value.replace("{{ " + placeholder + " }}", replacement) + if slug: + value = slugify(value) + return value + + @property + def placeholders(self) -> Dict[str, str]: + """ + Additional placeholders added at runtime: + - MENU_ITEM_LOCATION -> *MenuItem().location + + Subclasses may extend this dictionary! + """ + return { + "BASE_PREFIX": str(self.base_prefix), + "DISTRIBUTION_NAME": self.base_prefix.name, + "BASE_PYTHON": str(self.base_prefix / "bin" / "python"), + "PREFIX": str(self.prefix), + "ENV_NAME": self.prefix.name, + "PYTHON": str(self.prefix / "bin" / "python"), + "MENU_DIR": str(self.prefix / "Menu"), + "BIN_DIR": str(self.prefix / "bin"), + "PY_VER": "N.A", + "HOME": os.path.expanduser("~"), + "ICON_EXT": "png", + } + + def _conda_exe_path_candidates(self) -> Dict[str, str]: + return ( + self.base_prefix / "_conda.exe", + self.base_prefix / "conda.exe", + Path(os.environ.get("CONDA_EXE", "/oops/a_file_that_does_not_exist")), + self.base_prefix / "condabin" / "conda", + self.base_prefix / "bin" / "conda", + Path(os.environ.get("MAMBA_EXE", "/oops/a_file_that_does_not_exist")), + self.base_prefix / "condabin" / "micromamba", + self.base_prefix / "bin" / "micromamba", + ) + + @property + def conda_exe(self) -> Path: + if sys.executable.endswith("conda.exe"): + # This is the case with `constructor` calls + return Path(sys.executable) + + for path in self._conda_exe_path_candidates(): + if path.is_file(): + return path + + return Path("conda") + + def _is_micromamba(self, exe: Path) -> bool: + if "micromamba" in exe.name: + return True + if exe.name in ("conda.exe", "_conda.exe"): + out = check_output([str(exe), "info"], universal_newlines=True) + return "micromamba version" in out + return False + + def _site_packages(self, prefix=None) -> Path: + """ + Locate the python site-packages location on unix systems + """ + if os.name == "nt": + raise NotImplementedError + if prefix is None: + prefix = self.prefix + lib = Path(prefix) / "lib" + lib_python = next((p for p in lib.glob("python*") if p.is_dir()), lib / "pythonN.A") + return lib_python / "site-packages" + + def _paths(self) -> Iterable[os.PathLike]: + """ + This method should return the paths created by the menu + so they can be removed upon uninstallation + """ + raise NotImplementedError + + +class MenuItem: + def __init__(self, menu: Menu, metadata: dict): + self.menu = menu + self._data = self._initialize_on_defaults(metadata) + self.metadata = self._flatten_for_platform(self._data) + + @property + def location(self) -> Path: + "Path to the main menu item artifact (file or directory, depends on the platform)" + raise NotImplementedError + + def create(self) -> List[Path]: + raise NotImplementedError + + def remove(self) -> List[Path]: + raise NotImplementedError + + @property + def placeholders(self) -> Dict[str, str]: + return { + "MENU_ITEM_LOCATION": str(self.location), + } + + def render_key(self, key: str, slug: bool = False, extra: Optional[Dict[str, str]] = None) -> Any: + value = self.metadata.get(key) + return self.render(value, slug=slug, extra=extra) + + def render(self, value: Any, slug: bool = False, extra: Optional[Dict[str, str]] = None) -> Any: + if value in (None, True, False): + return value + kwargs = { + "slug": slug, + "extra": extra if extra is not None else self.placeholders, + } + if isinstance(value, str): + return self.menu.render(value, **kwargs) + if hasattr(value, "items"): + return { + key: self.menu.render(value, **kwargs) + for key, value in value.items() + } + return [self.menu.render(item, **kwargs) for item in value] + + def _precreate(self): + """ + Logic to run before the shortcut files are created. + """ + if os.name == "nt": + raise NotImplementedError + + precreate_code = self.render_key("precreate") + if not precreate_code: + return + with NamedTemporaryFile(delete=False, mode="w") as tmp: + tmp.write(precreate_code) + if precreate_code.startswith("#!"): + os.chmod(tmp.name, 0o755) + cmd = [tmp.name] + else: + cmd = ["bash", tmp.name] + run(cmd, check=True) + os.unlink(tmp.name) + + def _paths(self) -> Iterable[os.PathLike]: + """ + This method should return the paths created by the item + so they can be removed upon uninstallation + """ + raise NotImplementedError + + @staticmethod + def _initialize_on_defaults(data) -> Dict: + with open(data_path("menuinst.menu_item.default.json")) as f: + defaults = json.load(f) + + return deep_update(defaults, data) + + @staticmethod + def _flatten_for_platform(data: Mapping, platform: str = sys.platform) -> Mapping: + """ + Merge platform keys with global keys, overwriting if needed. + """ + flattened = deepcopy(data) + all_platforms = flattened.pop("platforms", {}) + this_platform = all_platforms.pop(platform_key(platform), None) + if this_platform: + for key, value in this_platform.items(): + if key not in flattened: + # bring missing keys, since they are platform specific + flattened[key] = value + elif value is not None: + # if the key was in global, it was not platform specific + # this is an override and we only do so if is not None + log.debug("Platform value %s=%s overrides global value", key, value) + flattened[key] = value + else: # restore + flattened["platforms"] = all_platforms + + # in the merged metadata, platforms becomes a list of str stating which + # platforms are enabled for this item + flattened["platforms"] = [ + key for key, value in data["platforms"].items() if value is not None + ] + return flattened + + def enabled_for_platform(self, platform: str = sys.platform) -> bool: + return self._data["platforms"].get(platform_key(platform)) is not None + + +def platform_key(platform: str = sys.platform) -> str: + if platform == "win32": + return "win" + if platform == "darwin": + return "osx" + if platform.startswith("linux"): + return "linux" + + raise ValueError(f"Platform {platform} is not supported") + + +menuitem_defaults = json.loads( + (Path(__file__).parents[1] / "data" / "menuinst.menu_item.default.json").read_text() +) diff --git a/menuinst/platforms/linux.py b/menuinst/platforms/linux.py new file mode 100644 index 00000000..6c86ccd8 --- /dev/null +++ b/menuinst/platforms/linux.py @@ -0,0 +1,253 @@ +""" +""" +import os +from pathlib import Path +import shutil +import xml.etree.ElementTree as XMLTree +import time +from logging import getLogger +from typing import Tuple, Iterable, Dict + +from .base import Menu, MenuItem, menuitem_defaults +from ..utils import indent_xml_tree, add_xml_child, UnixLex, unlink + + +log = getLogger(__name__) + + +class LinuxMenu(Menu): + """ + Menus in Linux are governed by the freedesktop.org standards, + spec'd here https://specifications.freedesktop.org/menu-spec/menu-spec-latest.html + + menuinst will populate the relevant XML config and create a .directory entry + """ + _system_config_directory = Path("/etc/xdg/") + _system_data_directory = Path("/usr/share") + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + if self.mode == "system": + self.config_directory = self._system_config_directory + self.data_directory =self._system_data_directory + else: + self.config_directory = Path( + os.environ.get("XDG_CONFIG_HOME", "~/.config") + ).expanduser() + self.data_directory = Path( + os.environ.get("XDG_DATA_HOME", "~/.local/share") + ).expanduser() + + # XML Config paths + self.system_menu_config_location = self._system_config_directory / "menus" / "applications.menu" + self.menu_config_location = self.config_directory / "menus" / "applications.menu" + # .desktop / .directory paths + self.directory_entry_location = ( + self.data_directory + / "desktop-directories" + / f"{self.render(self.name, slug=True)}.directory" + ) + self.desktop_entries_location = self.data_directory / "applications" + + def create(self) -> Tuple[os.PathLike]: + self._ensure_directories_exist() + path = self._write_directory_entry() + if self._is_valid_menu_file() and self._has_this_menu(): + return (path,) + self._ensure_menu_file() + self._add_this_menu() + return (path,) + + def remove(self) -> Tuple[os.PathLike]: + unlink(self.directory_entry_location, missing_ok=True) + for fn in os.listdir(self.desktop_entries_location): + if fn.startswith(f"{self.render(self.name, slug=True)}_"): + # found one shortcut, so don't remove the name from menu + return (self.directory_entry_location,) + self._remove_this_menu() + return (self.directory_entry_location,) + + @property + def placeholders(self) -> Dict[str, str]: + placeholders = super().placeholders + placeholders["SP_DIR"] = str(self._site_packages()) + return placeholders + + def _ensure_directories_exist(self): + paths = [ + self.config_directory / "menus", + self.data_directory / "desktop-directories", + self.data_directory / "applications", + ] + for path in paths: + log.debug("Ensuring path %s exists", path) + path.mkdir(parents=True, exist_ok=True) + + # + # .directory stuff methods + # + + def _write_directory_entry(self) -> str: + lines = [ + "[Desktop Entry]", + "Type=Directory", + "Encoding=UTF-8", + f"Name={self.render(self.name)}", + ] + log.debug("Writing directory entry at %s", self.directory_entry_location) + with open(self.directory_entry_location, "w") as f: + f.write("\n".join(lines)) + + return self.directory_entry_location + + # + # XML config stuff methods + # + + def _remove_this_menu(self): + log.debug("Editing %s to remove %s config", self.menu_config_location, self.name) + tree = XMLTree.parse(self.menu_config_location) + root = tree.getroot() + for elt in root.findall("Menu"): + if elt.find("Name").text == self.name: + root.remove(elt) + self._write_menu_file(tree) + + def _has_this_menu(self) -> bool: + root = XMLTree.parse(self.menu_config_location).getroot() + return any(e.text == self.name for e in root.findall("Menu/Name")) + + def _add_this_menu(self): + log.debug("Editing %s to add %s config", self.menu_config_location, self.name) + tree = XMLTree.parse(self.menu_config_location) + root = tree.getroot() + menu_elt = add_xml_child(root, "Menu") + add_xml_child(menu_elt, "Name", self.name) + add_xml_child(menu_elt, "Directory", f"{self.render(self.name, slug=True)}.directory") + inc_elt = add_xml_child(menu_elt, "Include") + add_xml_child(inc_elt, "Category", self.name) + self._write_menu_file(tree) + + def _is_valid_menu_file(self) -> bool: + try: + root = XMLTree.parse(self.menu_config_location).getroot() + return root is not None and root.tag == "Menu" + except Exception: + return False + + def _write_menu_file(self, tree: XMLTree): + log.debug("Writing %s", self.menu_config_location) + indent_xml_tree(tree.getroot()) # inplace! + with open(self.menu_config_location, "wb") as f: + f.write(b'\n') + tree.write(f) + f.write(b"\n") + + def _ensure_menu_file(self): + # ensure any existing version is a file + if self.menu_config_location.exists() and not self.menu_config_location.is_file(): + raise RuntimeError(f"Menu config location {self.menu_config_location} is not a file!") + # shutil.rmtree(self.menu_config_location) + + # ensure any existing file is actually a menu file + if self.menu_config_location.is_file(): + # make a backup of the menu file to be edited + cur_time = time.strftime("%Y-%m-%d_%Hh%Mm%S") + backup_menu_file = f"{self.menu_config_location}.{cur_time}" + shutil.copyfile(self.menu_config_location, backup_menu_file) + + if not self._is_valid_menu_file(): + os.remove(self.menu_config_location) + else: + self._new_menu_file() + + def _new_menu_file(self): + log.debug("Creating %s", self.menu_config_location) + with open(self.menu_config_location, "w") as f: + f.write("Applications") + if self.mode == "user": + f.write(f'{self.system_menu_config_location}') + f.write("\n") + + def _paths(self) -> Tuple[str]: + return (self.directory_entry_location,) + + +class LinuxMenuItem(MenuItem): + @property + def location(self) -> Path: + menu_prefix = self.render(self.menu.name, slug=True, extra={}) + # TODO: filename should conform to D-Bus well known name conventions + # https://specifications.freedesktop.org/desktop-entry-spec/latest/ar01s02.html + filename = f"{menu_prefix}_{self.render_key('name', slug=True, extra={})}.desktop" + return self.menu.desktop_entries_location / filename + + def create(self) -> Iterable[os.PathLike]: + log.debug("Creating %s", self.location) + self._precreate() + self._write_desktop_file() + return self._paths() + + def remove(self) -> Iterable[os.PathLike]: + paths = self._paths() + for path in paths: + log.debug("Removing %s", path) + unlink(path, missing_ok=True) + return paths + + def _command(self) -> str: + parts = [] + precommand = self.render_key("precommand") + if precommand: + parts.append(precommand) + if self.metadata["activate"]: + conda_exe = self.menu.conda_exe + if self.menu._is_micromamba(conda_exe): + activate = "shell activate" + else: + activate = "shell.bash activate" + parts.append(f'eval "$("{conda_exe}" {activate} "{self.menu.prefix}")"') + parts.append(" ".join(UnixLex.quote_args(self.render_key("command")))) + return f"bash -c '{' && '.join(parts)}'" + + def _write_desktop_file(self): + lines = [ + "[Desktop Entry]", + "Type=Application", + "Encoding=UTF-8", + f'Name={self.render_key("name")}', + f"Exec={self._command()}", + f'Terminal={str(self.render_key("terminal")).lower()}', + ] + + icon = self.render_key("icon") + if icon: + lines.append(f'Icon={self.render_key("icon")}') + + description = self.render_key("description") + if description: + lines.append(f'Comment={self.render_key("description")}') + + working_dir = self.render_key("working_dir") + if working_dir: + Path(working_dir).mkdir(parents=True, exist_ok=True) + lines.append(f"Path={working_dir}") + + for key in menuitem_defaults["platforms"]["linux"]: + if key in menuitem_defaults: + continue + value = self.render_key(key) + if value is None: + continue + if isinstance(value, bool): + value = str(value).lower() + elif isinstance(value, (list, tuple)): + value = ";".join(value) + ";" + lines.append(f"{key}={value}") + + with open(self.location, "w") as f: + f.write("\n".join(lines)) + f.write("\n") + + def _paths(self) -> Iterable[os.PathLike]: + return (self.location,) diff --git a/menuinst/platforms/osx.py b/menuinst/platforms/osx.py new file mode 100644 index 00000000..642bb787 --- /dev/null +++ b/menuinst/platforms/osx.py @@ -0,0 +1,231 @@ +""" +""" +from hashlib import sha1 +from logging import getLogger +from pathlib import Path +from subprocess import check_call +from typing import Tuple, Optional, Dict +import os +import platform +import plistlib +import shutil + +from .base import Menu, MenuItem, menuitem_defaults +from ..utils import UnixLex +from .. import data as _menuinst_data + +log = getLogger(__name__) + + +class MacOSMenu(Menu): + def create(self) -> Tuple: + return self._paths() + + def remove(self) -> Tuple: + return self._paths() + + @property + def placeholders(self) -> Dict[str, str]: + placeholders = super().placeholders + placeholders.update( + { + "SP_DIR": str(self._site_packages()), + "ICON_EXT": "icns", + "PYTHONAPP": str(self.prefix / "python.app" / "Contents" / "MacOS" / "python"), + } + ) + return placeholders + + def _paths(self) -> Tuple: + return () + + +class MacOSMenuItem(MenuItem): + @property + def location(self) -> Path: + "Path to the .app directory defining the menu item" + name = f"{self.render_key('name', extra={})}.app" + return self._base_location() / "Applications" / name + + def _base_location(self) -> Path: + if self.menu.mode == "user": + return Path("~").expanduser() + return Path("/") + + def _precreate(self): + super()._precreate() + for src, dest in (self.metadata["link_in_bundle"] or {}).items(): + rendered_dest: Path = (self.location / self.render(dest)).resolve() + # if not rendered_dest.is_relative_to(self.location): # FUTURE: Only for 3.9+ + if not str(rendered_dest).startswith(str(self.location)): + raise ValueError( + "'link_in_bundle' destinations MUST be created " + f"inside the .app bundle ({self.location}), but it points to '{rendered_dest}." + ) + rendered_dest.parent.mkdir(parents=True, exist_ok=True) + os.symlink(self.render(src), rendered_dest) + + def create(self) -> Tuple[Path]: + log.debug("Creating %s", self.location) + self._create_application_tree() + self._precreate() + icon = self.render_key("icon") + if icon: + shutil.copy(self.render_key("icon"), self.location / "Contents" / "Resources") + self._write_pkginfo() + self._write_plistinfo() + self._write_launcher() + self._write_script() + self._sign_with_entitlements() + return (self.location,) + + def remove(self) -> Tuple[Path]: + log.debug("Removing %s", self.location) + shutil.rmtree(self.location, ignore_errors=True) + return (self.location,) + + def _create_application_tree(self) -> Tuple[Path]: + paths = [ + self.location / "Contents" / "Resources", + self.location / "Contents" / "MacOS", + ] + for path in paths: + path.mkdir(parents=True, exist_ok=False) + return tuple(paths) + + def _write_pkginfo(self): + with open(self.location / "Contents" / "PkgInfo", "w") as f: + f.write(f"APPL{self.render_key('name', slug=True)[:8]}") + + def _write_plistinfo(self): + name = self.render_key("name") + slugname = self.render_key("name", slug=True) + if len(slugname) > 16: + shortname = slugname[:10] + sha1(slugname.encode()).hexdigest()[:6] + else: + shortname = slugname + pl = { + "CFBundleName": shortname, + "CFBundleDisplayName": name, + "CFBundleExecutable": slugname, + "CFBundleGetInfoString": f"{slugname}-1.0.0", + "CFBundleIdentifier": f"com.{slugname}", + "CFBundlePackageType": "APPL", + "CFBundleVersion": "1.0.0", + "CFBundleShortVersionString": "1.0.0", + } + + # Override defaults with (potentially) user provided values + ignore_keys = (*menuitem_defaults, "entitlements", "link_in_bundle") + for key in menuitem_defaults["platforms"]["osx"]: + if key in ignore_keys: + continue + value = self.render_key(key) + if value is None: + continue + if key == "CFBundleVersion": + # setting the version also changes these two values + pl["CFBundleShortVersionString"] = value + pl["CFBundleGetInfoString"] = f"{slugname}-{value}" + pl[key] = value + + icon = self.render_key("icon") + if icon: + pl["CFBundleIconFile"] = Path(icon).name + + with open(self.location / "Contents" / "Info.plist", "wb") as f: + plistlib.dump(pl, f) + + def _command(self) -> str: + lines = ["#!/bin/sh"] + if self.render_key("terminal"): + # FIXME: Terminal launching will miss the arguments; + # there's no easy way to pass them! + lines.extend( + [ + 'if [ "${__CFBundleIdentifier:-}" != "com.apple.Terminal" ]; then', + ' open -b com.apple.terminal "$0"', + ' exit $?', + 'fi', + ] + ) + + working_dir = self.render_key("working_dir") + if working_dir: + Path(working_dir).mkdir(parents=True, exist_ok=True) + lines.append(f'cd "{working_dir}"') + + precommand = self.render_key("precommand") + if precommand: + lines.append(precommand) + + if self.metadata["activate"]: + conda_exe = self.menu.conda_exe + if self.menu._is_micromamba(conda_exe): + activate = "shell activate" + else: + activate = "shell.bash activate" + lines.append(f'eval "$("{conda_exe}" {activate} "{self.menu.prefix}")"') + + lines.append(" ".join(UnixLex.quote_args(self.render_key("command")))) + + return "\n".join(lines) + + def _write_launcher(self, launcher_path: Optional[os.PathLike] = None) -> os.PathLike: + if launcher_path is None: + launcher_path = self._default_launcher_path() + shutil.copy(self._find_launcher(), launcher_path) + os.chmod(launcher_path, 0o755) + return launcher_path + + def _write_script(self, script_path: Optional[os.PathLike] = None) -> os.PathLike: + if script_path is None: + script_path = self._default_launcher_path(suffix="-script") + with open(script_path, "w") as f: + f.write(self._command()) + os.chmod(script_path, 0o755) + return script_path + + def _paths(self) -> Tuple[os.PathLike]: + return (self.location,) + + def _find_launcher(self) -> Path: + launcher_name = f"osx_launcher_{platform.machine()}" + for datapath in _menuinst_data.__path__: + launcher_path = Path(datapath) / launcher_name + if launcher_path.is_file() and os.access(launcher_path, os.X_OK): + return launcher_path + raise ValueError(f"Could not find executable launcher for {platform.machine()}") + + def _default_launcher_path(self, suffix: str = "") -> Path: + name = self.render_key("name", slug=True) + return self.location / "Contents" / "MacOS" / f'{name}{suffix}' + + def _sign_with_entitlements(self): + "Self-sign shortcut to apply required entitlements" + entitlement_keys = self.render_key("entitlements") + if not entitlement_keys: + return + slugname = self.render_key("name", slug=True) + plist = {key: True for key in entitlement_keys} + entitlements_path = self.location / "Contents" / "Entitlements.plist" + with open(entitlements_path, "wb") as f: + plistlib.dump(plist, f) + check_call( + [ + # hardcode to system location to avoid accidental clobber in PATH + "/usr/bin/codesign", + "--verbose", + "--sign", + "-", + "--prefix", + f"com.{slugname}", + "--options", + "runtime", + "--force", + "--deep", + "--entitlements", + entitlements_path, + self.location + ] + ) diff --git a/menuinst/platforms/win.py b/menuinst/platforms/win.py new file mode 100644 index 00000000..1f9c5f27 --- /dev/null +++ b/menuinst/platforms/win.py @@ -0,0 +1,261 @@ +""" +""" +import os +import warnings +import shutil +from logging import getLogger +from pathlib import Path +from subprocess import run +from tempfile import NamedTemporaryFile +from typing import Tuple, Optional, Dict, Any + +from .base import Menu, MenuItem +from ..utils import WinLex, unlink + +from .win_utils.knownfolders import folder_path as windows_folder_path + +log = getLogger(__name__) + + +class WindowsMenu(Menu): + def create(self) -> Tuple[os.PathLike]: + log.debug("Creating %s", self.start_menu_location) + self.start_menu_location.mkdir(parents=True, exist_ok=True) + if self.quick_launch_location: + self.quick_launch_location.mkdir(parents=True, exist_ok=True) + if self.desktop_location: + self.desktop_location.mkdir(parents=True, exist_ok=True) + return (self.start_menu_location,) + + def remove(self) -> Tuple[os.PathLike]: + log.debug("Removing %s", self.start_menu_location) + shutil.rmtree(self.start_menu_location, ignore_errors=True) + return (self.start_menu_location,) + + @property + def start_menu_location(self) -> Path: + """ + On Windows we can create shortcuts in several places: + + - Start Menu + - Desktop + - Quick launch (only for user installs) + + In this property we only report the path to the Start menu. + For other menus, check their respective properties. + """ + return Path(windows_folder_path(self.mode, False, "start")) / self.name + + @property + def quick_launch_location(self) -> Path: + if self.mode == "system": + # TODO: Check if this is true? + warnings.warn("Quick launch menus are not available for system level installs") + return + return Path(windows_folder_path(self.mode, False, "quicklaunch")) + + @property + def desktop_location(self) -> Path: + return Path(windows_folder_path(self.mode, False, "desktop")) + + @property + def placeholders(self) -> Dict[str, str]: + placeholders = super().placeholders + placeholders.update( + { + "SCRIPTS_DIR": str(self.prefix / "Scripts"), + "PYTHON": str(self.prefix / "python.exe"), + "PYTHONW": str(self.prefix / "pythonw.exe"), + "BASE_PYTHON": str(self.base_prefix / "python.exe"), + "BASE_PYTHONW": str(self.base_prefix / "pythonw.exe"), + "BIN_DIR": str(self.prefix / "Library" / "bin"), + "SP_DIR": str(self._site_packages()), + "ICON_EXT": "ico", + } + ) + return placeholders + + def _conda_exe_path_candidates(self): + return ( + self.base_prefix / "_conda.exe", + Path(os.environ.get("CONDA_EXE", r"C:\oops\a_file_that_does_not_exist")), + self.base_prefix / "condabin" / "conda.bat", + self.base_prefix / "bin" / "conda.bat", + Path(os.environ.get("MAMBA_EXE", r"C:\oops\a_file_that_does_not_exist")), + self.base_prefix / "condabin" / "micromamba.exe", + self.base_prefix / "bin" / "micromamba.exe", + ) + + def render(self, value: Any, slug: bool = False, extra: Optional[Dict[str, str]] = None) -> Any: + """ + We extend the render method here to replace forward slashes with backslashes. + We ONLY do it if the string does not start with /, because it might + be just a windows-style command-line flag (e.g. cmd /K something). + + This will not escape strings such as `/flag:something`, common + in compiler stuff but we can assume such windows specific + constructs will have their platform override, which is always an option. + + This is just a convenience for things like icon paths or Unix-like paths + in the command key. + """ + value = super().render(value, slug=slug, extra=extra) + if hasattr(value, "replace") and "/" in value and value[0] != "/": + value = value.replace("/", "\\") + return value + + def _site_packages(self, prefix=None) -> Path: + if prefix is None: + prefix = self.prefix + return self.prefix / "Lib" / "site-packages" + + def _paths(self) -> Tuple[Path]: + return (self.start_menu_location,) + + +class WindowsMenuItem(MenuItem): + @property + def location(self) -> Path: + """ + Path to the .lnk file placed in the Start Menu + On Windows, menuinst can create up to three shortcuts (start menu, desktop, quick launch) + This property only lists the one for start menu + """ + return self.menu.start_menu_location / self._shortcut_filename() + + def create(self) -> Tuple[Path, ...]: + from .win_utils.winshortcut import create_shortcut + + self._precreate() + + activate = self.metadata["activate"] + if activate: + script = self._write_script() + paths = self._paths() + + for path in paths: + if not path.suffix == ".lnk": + continue + + if activate: + if self.metadata["terminal"]: + command = ["cmd", "/K", str(script)] + else: + system32 = Path(os.environ.get("SystemRoot", "C:\\Windows")) / "system32" + command = [ + str(system32 / "WindowsPowerShell" / "v1.0" / "powershell.exe"), + f"\"start '{script}' -WindowStyle hidden\"", + ] + else: + command = self.render_key("command") + + target_path, *arguments = WinLex.quote_args(command) + + working_dir = self.render_key("working_dir") + if working_dir: + Path(working_dir).mkdir(parents=True, exist_ok=True) + else: + working_dir = "%HOMEPATH%" + + icon = self.render_key("icon") or "" + + # winshortcut is a windows-only C extension! create_shortcut has this API + # Notice args must be passed as positional, no keywords allowed! + # winshortcut.create_shortcut(path, description, filename, arguments="", + # workdir=None, iconpath=None, iconindex=0) + create_shortcut( + target_path, + self._shortcut_filename(ext=""), + str(path), + " ".join(arguments), + working_dir, + icon, + ) + return paths + + def remove(self) -> Tuple[Path, ...]: + paths = self._paths() + for path in paths: + log.debug("Removing %s", path) + unlink(path, missing_ok=True) + return paths + + def _paths(self) -> Tuple[Path, ...]: + paths = [self.location] + extra_dirs = [] + if self.metadata["desktop"]: + extra_dirs.append(self.menu.desktop_location) + if self.metadata["quicklaunch"] and self.menu.quick_launch_location: + extra_dirs.append(self.menu.quick_launch_location) + + if extra_dirs: + paths += [directory / self._shortcut_filename() for directory in extra_dirs] + + if self.metadata["activate"]: + # This is the accessory launcher script for cmd + paths.append(self._path_for_script()) + + return tuple(paths) + + def _shortcut_filename(self, ext: str = "lnk"): + env_suffix = f" ({self.menu.env_name})" if self.menu.env_name else "" + ext = f".{ext}" if ext else "" + return f"{self.render_key('name', extra={})}{env_suffix}{ext}" + + def _path_for_script(self) -> Path: + return Path(self.menu.placeholders["MENU_DIR"]) / self._shortcut_filename("bat") + + def _precreate(self): + precreate_code = self.render_key("precreate") + if not precreate_code: + return + with NamedTemporaryFile(delete=False, mode="w") as tmp: + tmp.write(precreate_code) + system32 = Path(os.environ.get("SystemRoot", "C:\\Windows")) / "system32" + cmd = [ + str(system32 / "WindowsPowerShell" / "v1.0" / "powershell.exe"), + f"\"start '{tmp.name}' -WindowStyle hidden\"", + ] + run(cmd, check=True) + os.unlink(tmp.name) + + def _command(self) -> str: + lines = [ + "@ECHO OFF", + ":: Script generated by conda/menuinst", + ] + precommand = self.render_key("precommand") + if precommand: + lines.append(precommand) + if self.metadata["activate"]: + conda_exe = self.menu.conda_exe + if self.menu._is_micromamba(conda_exe): + activate = "shell activate" + else: + activate = "shell.cmd.exe activate" + activator = f'{self.menu.conda_exe} {activate} "{self.menu.prefix}"' + lines += [ + "@SETLOCAL ENABLEDELAYEDEXPANSION", + f'@FOR /F "usebackq tokens=*" %%i IN (`{activator}`) do set "ACTIVATOR=%%i"', + "@CALL %ACTIVATOR%", + ":: This below is the user command", + ] + + lines.append(" ".join(WinLex.quote_args(self.render_key("command")))) + + return "\r\n".join(lines) + + def _write_script(self, script_path: Optional[os.PathLike] = None) -> Path: + """ + This method generates the batch script that will be called by the shortcut + """ + if script_path is None: + script_path = self._path_for_script() + else: + script_path = Path(script_path) + + script_path.parent.mkdir(parents=True, exist_ok=True) + with open(script_path, "w") as f: + f.write(self._command()) + + return script_path diff --git a/menuinst/platforms/win_utils/__init__.py b/menuinst/platforms/win_utils/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/menuinst/knownfolders.py b/menuinst/platforms/win_utils/knownfolders.py similarity index 75% rename from menuinst/knownfolders.py rename to menuinst/platforms/win_utils/knownfolders.py index 8f4f1761..0b5157f5 100644 --- a/menuinst/knownfolders.py +++ b/menuinst/platforms/win_utils/knownfolders.py @@ -25,11 +25,14 @@ THE SOFTWARE. """ -from __future__ import print_function - -import ctypes, sys +import ctypes +import os from ctypes import windll, wintypes from uuid import UUID +from logging import getLogger + +logger = getLogger(__name__) + class GUID(ctypes.Structure): # [1] _fields_ = [ @@ -156,7 +159,7 @@ class UserHandle: # [3] ''' # Please keep this code around in-case we need to debug tricky installations -# http://stackoverflow.com/a/15016751/3257826 +# http://stackoverflow.com/a/15016751/3257826 - needs pywin32 import pythoncom from win32com.shell import shell, shellcon from win32com import storagecon @@ -208,28 +211,75 @@ def get_folder_path(folder_id, user=None): # New users created on the machine have their folders created by copying those of 'Default'. return get_path(folder_id, user) -if __name__ == '__main__': - if len(sys.argv) < 2 or sys.argv[1] in ['-?', '/?']: - print('python knownfolders.py FOLDERID {current|common}') - sys.exit(0) - - try: - folderid = getattr(FOLDERID, sys.argv[1]) - except AttributeError: - print('Unknown folder id "%s"' % sys.argv[1], file=sys.stderr) - sys.exit(1) - - try: - if len(sys.argv) == 2: - print(get_path(folderid)) - else: - print(get_path(folderid, getattr(UserHandle, sys.argv[2]))) - except PathNotFoundException: - print('Folder not found "%s"' % ' '.join(sys.argv[1:]), file=sys.stderr) - sys.exit(1) - # [1] http://msdn.microsoft.com/en-us/library/windows/desktop/aa373931.aspx # [2] http://msdn.microsoft.com/en-us/library/windows/desktop/dd378457.aspx # [3] http://msdn.microsoft.com/en-us/library/windows/desktop/bb762188.aspx # [4] http://msdn.microsoft.com/en-us/library/windows/desktop/ms680722.aspx # [5] http://www.themacaque.com/?p=954 + +# jaimergp: The code below was copied from menuinst.win32, 1.4.19 +# module: menuinst/win32.py - https://github.com/conda/menuinst/blob/e17afafd/menuinst/win32.py#L40-L102 +# ---- +# When running as 'nt authority/system' as sometimes people do via SCCM, +# various folders do not exist, such as QuickLaunch. This doesn't matter +# as we'll use the "system" key finally and check for the "quicklaunch" +# subkey before adding any Quick Launch menu items. + +# It can happen that some of the dirs[] entires refer to folders that do not +# exist, in which case, the 2nd entry of the value tuple is a sub-class of +# Exception. + +dirs_src = {"system": { "desktop": get_folder_path(FOLDERID.PublicDesktop), + "start": get_folder_path(FOLDERID.CommonPrograms), + "documents": get_folder_path(FOLDERID.PublicDocuments), + "profile": get_folder_path(FOLDERID.Profile)}, + + "user": { "desktop": get_folder_path(FOLDERID.Desktop), + "start": get_folder_path(FOLDERID.Programs), + "quicklaunch": get_folder_path(FOLDERID.QuickLaunch), + "documents": get_folder_path(FOLDERID.Documents), + "profile": get_folder_path(FOLDERID.Profile)}} + + +def folder_path(preferred_mode, check_other_mode, key): + ''' This function implements all heuristics and workarounds for messed up + KNOWNFOLDERID registry values. It's also verbose (OutputDebugStringW) + about whether fallbacks worked or whether they would have worked if + check_other_mode had been allowed. + ''' + other_mode = 'system' if preferred_mode == 'user' else 'user' + path, exception = dirs_src[preferred_mode][key] + if not exception: + return path + logger.info("WARNING: menuinst key: '%s'\n" + " path: '%s'\n" + " .. excepted with: '%s' in knownfolders.py, implementing workarounds .." + % (key, path, type(exception).__name__)) + # Since I have seen 'user', 'documents' set as '\\vmware-host\Shared Folders\Documents' + # when there's no such server, we check 'user', 'profile' + '\Documents' before maybe + # trying the other_mode (though I have chickened out on that idea). + if preferred_mode == 'user' and key == 'documents': + user_profile, exception = dirs_src['user']['profile'] + if not exception: + path = os.path.join(user_profile, 'Documents') + if os.access(path, os.W_OK): + logger.info(" .. worked-around to: '%s'" % (path)) + return path + path, exception = dirs_src[other_mode][key] + # Do not fall back to something we cannot write to. + if exception: + if check_other_mode: + logger.info(" .. despite 'check_other_mode'\n" + " and 'other_mode' 'path' of '%s'\n" + " it excepted with: '%s' in knownfolders.py" % (path, + type(exception).__name__)) + else: + logger.info(" .. 'check_other_mode' is False,\n" + " and 'other_mode' 'path' is '%s'\n" + " but it excepted anyway with: '%s' in knownfolders.py" % (path, type(exception).__name__)) + return None + if not check_other_mode: + logger.info(" .. due to lack of 'check_other_mode' not picking\n" + " non-excepting path of '%s'\n in knownfolders.py" % (path)) + return None + return path diff --git a/menuinst/win_elevate.py b/menuinst/platforms/win_utils/win_elevate.py similarity index 86% rename from menuinst/win_elevate.py rename to menuinst/platforms/win_utils/win_elevate.py index c9ff0dcc..2dea5789 100644 --- a/menuinst/win_elevate.py +++ b/menuinst/platforms/win_utils/win_elevate.py @@ -11,6 +11,7 @@ from __future__ import print_function import sys, os, traceback from enum import IntEnum +from subprocess import list2cmdline if sys.version_info < (3,): text_type = basestring @@ -19,21 +20,17 @@ def isUserAdmin(): + if os.name != 'nt': + raise RuntimeError("This function is only implemented on Windows.") - if os.name == 'nt': - import ctypes - # WARNING: requires Windows XP SP2 or higher! - try: - return ctypes.windll.shell32.IsUserAnAdmin() - except: - traceback.print_exc() - print("Admin check failed, assuming not an admin.") - return False - elif os.name == 'posix': - # Check for root on Posix - return os.getuid() == 0 - else: - raise RuntimeError("Unsupported operating system for this module: %s" % (os.name,)) + import ctypes + # Requires Windows XP SP2 or higher! + try: + return ctypes.windll.shell32.IsUserAnAdmin() + except: + traceback.print_exc() + print("Admin check failed, assuming not an admin.") + return False # Taken from conda/common/_os/windows.py @@ -128,8 +125,7 @@ def runAsAdmin(cmdLine=None, wait=True): raise ValueError("cmdLine is not a sequence.") cmd = '"%s"' % (cmdLine[0],) - # XXX TODO: isn't there a function or something we can call to massage command line params? - params = " ".join(['"%s"' % (x,) for x in cmdLine[1:]]) + params = list2cmdline(cmdLine[1:]) showCmd = SW.HIDE lpVerb = 'runas' # causes UAC elevation prompt. @@ -165,6 +161,7 @@ def runAsAdmin(cmdLine=None, wait=True): if __name__ == '__main__': userIsAdmin = isUserAdmin() - print('userIsAdmin = %d' % (userIsAdmin)) + with open("output.txt", "a") as f: + print('userIsAdmin = %d' % (userIsAdmin), file=f) if not userIsAdmin: runAsAdmin([sys.executable] + sys.argv, wait=True) diff --git a/menuinst/utils.py b/menuinst/utils.py index 7e09a644..9d254f12 100644 --- a/menuinst/utils.py +++ b/menuinst/utils.py @@ -1,22 +1,387 @@ import os -import shutil -from os.path import isdir, isfile, islink +import re +import shlex +import subprocess +import sys +import traceback +import xml.etree.ElementTree as XMLTree +from contextlib import suppress +from functools import wraps +from logging import getLogger +from pathlib import Path +from unicodedata import normalize +from typing import Union, Literal, Optional, Sequence, Iterable, Mapping, Callable +logger = getLogger(__name__) +_TargetOrBase = Union[Literal["target"], Literal["base"]] -def rm_empty_dir(path): - try: - os.rmdir(path) - except OSError: # directory might not exist or not be empty - pass + +def _default_prefix(which: _TargetOrBase = "target"): + """ + The prefixes in menuinst need to be handled with care. + + Conda installations that require superuser permissions need elevation for + the creation of shortcuts. Constructor will leave a sentinel file to signal + this. If a file `.nonadmin` is present in the 'base' environment (or root of + the installation directory if conda is not present), superuser access is not + needed. + + In order to check for this file, menuinst needs to track 'base_prefix'. For + a regular 'conda' process, this should be `conda.base.context.context.root_prefix'. + However, constructor also relies on a pyinstaller-frozen conda installation, + 'conda-standalone'. In these cases, 'sys.prefix' is set to temporary location + of the extracted contents of the executable -- that's NOT the base installation! + + For those reasons, we handle the default prefix with 'sys.prefix' (or 'sys.base_prefix') + as a last resort. The logic is: + + - If 'MENUINST_PREFIX' (or 'MENUINST_BASE_PREFIX') is an env var with a set value, use that. + - If are already using conda, we get the context object and use those values. + - If CONDA_PREFIX (or 'CONDA_ROOT_PREFIX') are available, use those + - Last resort: use sys.prefix and sys.base_prefix + + This helps us pass a lot of CLI arguments back and forth. + """ + base = which == "base" + context = None + if "conda" in sys.modules: + with suppress(ImportError): + from conda.base.context import context + + if base: + prefix = os.environ.get("MENUINST_BASE_PREFIX") + if prefix: + return prefix + if context: + return context.root_prefix + return os.environ.get("CONDA_ROOT_PREFIX", sys.base_prefix) + # else + prefix = os.environ.get("MENUINST_PREFIX") + if prefix: + return prefix + if context: + return context.target_prefix + return os.environ.get("CONDA_PREFIX", sys.prefix) + + +DEFAULT_PREFIX = _default_prefix("target") +DEFAULT_BASE_PREFIX = _default_prefix("base") + + +def slugify(text: str): + # Adapted from from django.utils.text.slugify + # Copyright (c) Django Software Foundation and individual contributors. + # All rights reserved. + # Redistribution and use in source and binary forms, with or without modification, + # are permitted provided that the following conditions are met: + # 1. Redistributions of source code must retain the above copyright notice, + # this list of conditions and the following disclaimer. + # 2. Redistributions in binary form must reproduce the above copyright + # notice, this list of conditions and the following disclaimer in the + # documentation and/or other materials provided with the distribution. + # 3. Neither the name of Django nor the names of its contributors may be used + # to endorse or promote products derived from this software without + # specific prior written permission. + # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + """ + Convert to ASCII, and spaces to hyphens. + Remove characters that aren't alphanumerics, underscores, or hyphens. + Convert to lowercase. Also strip leading and trailing whitespace. + """ + text = normalize('NFKD', text).encode('ascii', 'ignore').decode('ascii') + text = re.sub(r'[^\w\s-]', '', text).strip().lower() + return re.sub(r'[-\s]+', '-', text) + + +def indent_xml_tree(elem, level=0): + """ + adds whitespace to the tree, so that it results in a pretty printed tree + """ + indentation = " " # 4 spaces, just like in Python! + base_indentation = "\n" + level * indentation + if len(elem): + if not elem.text or not elem.text.strip(): + elem.text = base_indentation + indentation + for e in elem: + indent_xml_tree(e, level + 1) + if not e.tail or not e.tail.strip(): + e.tail = base_indentation + indentation + if not e.tail or not e.tail.strip(): + e.tail = base_indentation + else: + if level and (not elem.tail or not elem.tail.strip()): + elem.tail = base_indentation + + +def add_xml_child(parent: XMLTree.Element, tag: str, text: Optional[str] = None): + """ + Add a child element of specified tag type to parent. + The new child element is returned. + """ + elem = XMLTree.SubElement(parent, tag) + if text is not None: + elem.text = text + return elem + + +class WinLex: + @classmethod + def quote_args(cls, args: Sequence[str]): + # cmd.exe /K or /C expects a single string argument and requires + # doubled-up quotes when any sub-arguments have spaces: + # https://stackoverflow.com/a/6378038/3257826 + if ( + len(args) > 2 + and ("CMD.EXE" in args[0].upper() or "%COMSPEC%" in args[0].upper()) + and (args[1].upper() == "/K" or args[1].upper() == "/C") + and any(" " in arg for arg in args[2:]) + ): + args = [ + cls.ensure_pad(args[0], '"'), # cmd.exe + args[1], # /K or /C + '"%s"' % (" ".join(cls.ensure_pad(arg, '"') for arg in args[2:])), # double-quoted + ] + else: + args = [cls.quote_string(arg) for arg in args] + return args + + @classmethod + def quote_string(cls, s: Sequence[str]): + """ + quotes a string if necessary. + """ + # strip any existing quotes + s = s.strip('"') + # don't add quotes for minus or leading space + if s[0] in ("-", " "): + return s + if " " in s or "/" in s: + return '"%s"' % s + return s + + @classmethod + def ensure_pad(cls, name: str, pad: str ="_"): + """ + + Examples: + >>> ensure_pad('conda') + '_conda_' + + """ + if not name or name[0] == name[-1] == pad: + return name + else: + return "%s%s%s" % (pad, name, pad) + + +class UnixLex: + @classmethod + def quote_args(cls, args: Sequence[str]) -> Sequence[str]: + return [cls.quote_string(a) for a in args] + + @classmethod + def quote_string(cls, s: str) -> str: + quoted = shlex.quote(s) + if quoted.startswith("'") and not '"' in quoted: + quoted = f'"{quoted[1:-1]}"' + return quoted -def rm_rf(path): - if islink(path) or isfile(path): - # Note that we have to check if the destination is a link because - # exists('/path/to/dead-link') will return False, although - # islink('/path/to/dead-link') is True. +def unlink(path: os.PathLike, missing_ok: bool = False): + try: os.unlink(path) + except FileNotFoundError as exc: + if not missing_ok: + raise exc + + +def data_path(path: os.PathLike) -> Path: + here = Path(__file__).parent + return here / "data" / path + + +def deep_update(mapping: Mapping, *updating_mappings: Iterable[Mapping]) -> Mapping: + # Brought from pydantic.utils + # https://github.com/samuelcolvin/pydantic/blob/9d631a3429a66f30742c1a52c94ac18ec6ba848d/pydantic/utils.py#L198 + + # The MIT License (MIT) + # Copyright (c) 2017, 2018, 2019, 2020, 2021 Samuel Colvin and other contributors + # Permission is hereby granted, free of charge, to any person obtaining a copy + # of this software and associated documentation files (the "Software"), to deal + # in the Software without restriction, including without limitation the rights + # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + # copies of the Software, and to permit persons to whom the Software is + # furnished to do so, subject to the following conditions: + # The above copyright notice and this permission notice shall be included in all + # copies or substantial portions of the Software. + # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + # SOFTWARE. + + updated_mapping = mapping.copy() + for updating_mapping in updating_mappings: + for k, v in updating_mapping.items(): + if k in updated_mapping and isinstance(updated_mapping[k], dict) and isinstance(v, dict): + updated_mapping[k] = deep_update(updated_mapping[k], v) + else: + updated_mapping[k] = v + return updated_mapping + + +def user_is_admin() -> bool: + if os.name == 'nt': + from .platforms.win_utils.win_elevate import isUserAdmin + + return isUserAdmin() + elif os.name == 'posix': + # Check for root on Linux, macOS and other posix systems + return os.getuid() == 0 + else: + raise RuntimeError(f"Unsupported operating system: {os.name}") + + +def run_as_admin(argv: Sequence[str]) -> int: + """ + Rerun this command in a new process with admin permissions. + """ + if os.name == 'nt': + from .platforms.win_utils.win_elevate import runAsAdmin + + return runAsAdmin(argv) + elif os.name == 'posix': + return subprocess.call(["sudo", *argv]) + else: + raise RuntimeError(f"Unsupported operating system: {os.name}") + + +def python_executable(base_prefix: Optional[os.PathLike] = None) -> Sequence[str]: + base_prefix = Path(base_prefix or DEFAULT_BASE_PREFIX) + # menuinst might be called by a conda-standalone bundle + # these are pyinstaller-generated, and have sys.frozen=True + # in these cases, we prefer using the base env python to + # avoid a 2nd decompression + hacky console, so we try that + # first; otherwise, we use 'conda-standalone.exe python' + if getattr(sys, 'frozen', False): + if os.name == "nt": + base_prefix_python = base_prefix / "python.exe" + else: + base_prefix_python = base_prefix / "bin" / "python" + # If the base env (installation root) + # ships a usable Python, use that one + if base_prefix_python.is_file(): + return (str(base_prefix_python), ) + # the base env does not have python, + # use the conda-standalone wrapper + return (sys.executable, "python") + # in non-frozen executables: + return (sys.executable, ) + + +def elevate_as_needed(func: Callable) -> Callable: + """ + Multiplatform decorator to run a function as a superuser, if needed. + + This depends on the presence of a `.nonadmin` file in the installation root. + This is usually planted by the `constructor` installer if the installation + process didn't need superuser permissions. + + In the absence of this file, we assume that we will need superuser + permissions, so we try to run the decorated function as a superuser. + If that fails (the user rejects the request or doesn't have permissions + to accept it), we'll try to run it as a normal user. + + NOTE: Only functions that return None should be decorated. The function + will run in a separate process, so we won't be able to capture the return + value anyway. + """ + if os.name != "nt": + return func + + @wraps(func) + def wrapper_elevate( + *args, + base_prefix: os.PathLike = None, + **kwargs, + ): + kwargs.pop("_mode", None) + base_prefix = base_prefix or DEFAULT_BASE_PREFIX + if not (Path(base_prefix) / ".nonadmin").exists(): + if user_is_admin(): + return func( + base_prefix=base_prefix, + _mode="system", + *args, + **kwargs, + ) + if os.environ.get("_MENUINST_RECURSING") != "1": + # call the wrapped func with elevated prompt... + # from the command line; not pretty! + try: + if func.__module__ == "__main__": + import_func = ( + f"import runpy;" + f"{func.__name__} = runpy.run_path('{__file__}')" + f"['{func.__name__}'];" + ) + else: + import_func = f"from {func.__module__} import {func.__name__};" + cmd = [ + *python_executable(), + "-c", + f"import os;" + f"os.environ.setdefault('_MENUINST_RECURSING', '1');" + f"{import_func}" + f"{func.__name__}(" + f"*{args!r}," + f"base_prefix={base_prefix!r}," + f"**{kwargs!r}" + ")", + ] + logger.debug("Elevating command: %s", cmd) + return_code = run_as_admin(cmd) + except Exception: + logger.warn( + "Error occurred! Falling back to user mode. Exception:\n%s", + traceback.format_exc() + ) + else: + os.environ.pop("_MENUINST_RECURSING", None) + if return_code == 0: # success, no need to fallback + return + # We have not returned yet? Well, let's try as a normal user + return func( + base_prefix=base_prefix, + _mode="user", + *args, + **kwargs, + ) + + return wrapper_elevate + + +def _test(base_prefix: Optional[os.PathLike] = None, _mode: str = "user"): + if os.name == "nt": + out = open("output.txt", "a") + else: + out = sys.stdout + print(user_is_admin(), file=out) + - elif isdir(path): - shutil.rmtree(path) +if __name__ == "__main__": + _test() + _test = elevate_as_needed(_test) + _test() diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 00000000..69bac36d --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,43 @@ +[build-system] +requires = ["setuptools>=45", "setuptools_scm[toml]>=6.2"] +build-backend = "setuptools.build_meta" + +[project] +name = "menuinst" +description = "cross platform install of menu items" +readme = "README.rst" +license = {file = "LICENSE.txt"} +requires-python = ">=3.8" +dynamic = [ + "version" +] + +[project.urls] +repository = "https://github.com/conda/menuinst" + +[tool.setuptools_scm] +write_to = "menuinst/_version.py" + +[tool.setuptools] +include-package-data = true + +[tool.setuptools.packages.find] +where = ["."] +include = ["menuinst*"] +namespaces = true + +[tool.black] +line-length = 99 +target-version = ['py38', 'py39', 'py310', 'py311'] +include = '\.pyi?$' +exclude = ''' +^/( + ( + menuinst/_legacy + | tests/_legacy + )/ +) +''' + +[tool.pyright] +pythonPlatform = "All" diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index d0d6f2fb..00000000 --- a/setup.cfg +++ /dev/null @@ -1,10 +0,0 @@ -[versioneer] -VCS = git -versionfile_source = menuinst/_version.py -versionfile_build = menuinst/_version.py -tag_prefix = -parentdir_prefix = menuinst- - -[flake8] -max-line-length = 100 -ignore = E201 \ No newline at end of file diff --git a/setup.py b/setup.py index 1be79a97..d2dc0744 100644 --- a/setup.py +++ b/setup.py @@ -2,35 +2,32 @@ # Copyright (c) 2013 Continuum Analytics, Inc. # All rights reserved. import sys -from distutils.core import Extension, setup - -import versioneer - +from setuptools import Extension, setup +extensions = [] if sys.platform == "win32": - extensions = [Extension( - "menuinst.winshortcut", - sources=["menuinst/winshortcut.cpp"], - include_dirs=["menuinst"], - libraries=["comctl32", "kernel32", "user32", "gdi32", "winspool", - "comdlg32", "advapi32", "shell32", "ole32", "oleaut32", - "uuid", "odbc32", "odbccp32"] - )] -else: - extensions = [] + extensions.append( + Extension( + "menuinst.platforms.win_utils.winshortcut", + sources=["src/winshortcut.cpp"], + include_dirs=["src/"], + libraries=[ + "comctl32", + "kernel32", + "user32", + "gdi32", + "winspool", + "comdlg32", + "advapi32", + "shell32", + "ole32", + "oleaut32", + "uuid", + "odbc32", + "odbccp32", + ], + ) + ) -setup( - name = "menuinst", - url = "https://github.com/conda/menuinst", - version = versioneer.get_version(), - cmdclass=versioneer.get_cmdclass(), - description = "cross platform install of menu items", - long_description = open('README.rst').read(), - ext_modules = extensions, - include_package_data = True, - install_requires = [], - package_data = {"menuinst" : ["*.icns"]}, - license = "BSD", - packages = ['menuinst'], -) +setup(ext_modules=extensions) diff --git a/src/README.md b/src/README.md new file mode 100644 index 00000000..2fc5d187 --- /dev/null +++ b/src/README.md @@ -0,0 +1,26 @@ +This directory contains the non-Python code needed for menuinst. + +# Windows + +`winshortcut.cpp` and `resource.h` are needed to generate a C extension to interact with the Windows API and create the shortcuts. +Compilation happens via `setup.py`. + +# MacOS + +`osx_launcher.c` will build a script launcher on MacOS. +It will find a shell script next to itself (executable name + `-script`) and launch it with `/bin/sh`. +It only depends on the standard library. It is bundled as part of the `menuinst.data`. +If it changes, recompile using these steps: + +1. Install the conda-forger compilers: `conda create -n cf-compilers compilers`. +2. Get oldest 10.9 SDK (Intel) or 11.0 SDK (Apple Silicon) from https://github.com/phracker/MacOSX-SDKs + and install it to a known location (e.g. `~/opt/`). +3. Compile with: + +```bash +SDK_PATH=~/opt/MacOSX11.0.sdk # replace as appropriate +for target in "x86_64-apple-macos10.9" "arm64-apple-macos11.0"; do + arch_suffix="${target%%-*}" + clang src/osx_launcher.c -o menuinst/data/osx_launcher_${arch_suffix} -target $target -isysroot "$SDK_PATH" +done +``` \ No newline at end of file diff --git a/src/osx_launcher.c b/src/osx_launcher.c new file mode 100644 index 00000000..514b6cbc --- /dev/null +++ b/src/osx_launcher.c @@ -0,0 +1,77 @@ +/* + * Written by Jaime Rodriguez-Guerra, 2022 Nov + * + * A small C program to launch shell scripts on macOS. + * This allows us to work nicely with the permission system + * and other security issues in macOS. + * + * It expects an executable file next to itself, suffixed + * with `-script`. The file is execv'd and passed argv[1:]. + */ + +#include +#include +#include +#include +#include +#include +#include + +int main(int argc, char **argv) { + int status; + pid_t pid; + + // 1. Get path to shell script; should be next to the compiled binary + // Allocate the string buffer and ask _NSGetExecutablePath() + // to fill it with the executable path + uint32_t bufsize = PATH_MAX; + char scriptPath[PATH_MAX + 1]; + if (_NSGetExecutablePath(scriptPath, &bufsize) != 0) { + fprintf(stderr, "ERROR: Could not find executable path."); + return 127; + } + // the path to the script is the same path + "-script"; 7 characters + const char suffix[] = "-script"; + strcat(scriptPath, suffix); + + // 2. Build arguments vector from argv, skipping argv[0] + char* args[argc + 2]; + args[0] = scriptPath; + for(int i = 0; i <= argc; i++) { + if (i > 0) { + args[i] = argv[i]; + } + } + + // 3. Fork process + pid = fork(); + if (pid == 0) { + // This is the child process. Execute the shell command. + execv(scriptPath, args); + _exit(127); // This should never be reached. + } + else if (pid < 0) { + // The fork failed. Report failure. + status = EXIT_FAILURE; + } + else { + // This is the parent process. Wait for the child to complete. + if (waitpid(pid, &status, 0) != pid) { + // waitpid failed + status = EXIT_FAILURE; + } + else { + if (WIFEXITED(status)) { + // program terminated normally + status = WEXITSTATUS(status); + if (status == 127) { + fprintf(stderr, "ERROR: Could not run or find '%s'\n", scriptPath); + } + } + else { + status = EXIT_FAILURE; + } + } + } + return status; +} diff --git a/menuinst/resource.h b/src/resource.h similarity index 100% rename from menuinst/resource.h rename to src/resource.h diff --git a/menuinst/winshortcut.cpp b/src/winshortcut.cpp similarity index 98% rename from menuinst/winshortcut.cpp rename to src/winshortcut.cpp index 229f0634..72f00fdf 100644 --- a/menuinst/winshortcut.cpp +++ b/src/winshortcut.cpp @@ -118,7 +118,7 @@ static PyObject *CreateShortcut(PyObject *self, PyObject *args) hres = pPersistFile->Save(filename, TRUE); if (FAILED(hres)) { - PyObject *fn = PyUnicode_FromUnicode(filename, wcslen(filename)); + PyObject *fn = PyUnicode_FromWideChar(filename, wcslen(filename)); if (fn) { PyObject *msg = PyUnicode_FromFormat( "Failed to create shortcut '%U' - error 0x%x", diff --git a/tests/Iconleak-Atrous-Console.ico b/tests/_legacy/Iconleak-Atrous-Console.ico similarity index 100% rename from tests/Iconleak-Atrous-Console.ico rename to tests/_legacy/Iconleak-Atrous-Console.ico diff --git a/tests/menu-windows.json b/tests/_legacy/menu-windows.json similarity index 82% rename from tests/menu-windows.json rename to tests/_legacy/menu-windows.json index abd2a894..6810e066 100644 --- a/tests/menu-windows.json +++ b/tests/_legacy/menu-windows.json @@ -5,7 +5,7 @@ { "name": "Anaconda Prompt", "system": "%windir%\\system32\\cmd.exe", - "scriptarguments": ["/K", "${ROOT_PREFIX}\\Scripts\\activate.bat", "${PREFIX}"], + "scriptarguments": ["/C", "${ROOT_PREFIX}\\Scripts\\activate.bat", "${PREFIX}"], "icon": "${MENU_DIR}/Iconleak-Atrous-Console.ico" } ] diff --git a/tests/test_menu_creation.py b/tests/_legacy/test_menu_creation.py similarity index 95% rename from tests/test_menu_creation.py rename to tests/_legacy/test_menu_creation.py index b87c3faa..7b72a000 100644 --- a/tests/test_menu_creation.py +++ b/tests/_legacy/test_menu_creation.py @@ -4,8 +4,9 @@ from conda.cli.python_api import run_command import pytest -import menuinst -from menuinst.win32 import dirs_src +if sys.platform == "win32": + import menuinst._legacy as menuinst + from menuinst._legacy.win32 import dirs_src def file_exist(mode, name): diff --git a/tests/test_win32.py b/tests/_legacy/test_win32.py similarity index 77% rename from tests/test_win32.py rename to tests/_legacy/test_win32.py index db49cd15..db7cf896 100644 --- a/tests/test_win32.py +++ b/tests/_legacy/test_win32.py @@ -1,12 +1,17 @@ # -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from logging import getLogger +import sys -from menuinst.win32 import quote_args +import pytest -log = getLogger(__name__) +if sys.platform == "win32": + from menuinst._legacy.win32 import quote_args +log = getLogger(__name__) +@pytest.mark.skipif(sys.platform != "win32", + reason="Windows-only tests") def test_quote_args_1(): args = [ "%windir%\\System32\\cmd.exe", diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 00000000..e9fd401e --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,72 @@ +from pathlib import Path +import shutil +import os +import json +import logging +from subprocess import check_output +from tempfile import TemporaryDirectory + +import py +import pytest + +from menuinst.platforms.base import platform_key + +os.environ["PYTEST_IN_USE"] = "1" +DATA = Path(__file__).parent / "data" +PLATFORM = platform_key() + + +def base_prefix(): + prefix = os.environ.get("CONDA_ROOT", os.environ.get("MAMBA_ROOT_PREFIX")) + if not prefix: + prefix = json.loads(check_output(["conda", "info", "--json"]))["root_prefix"] + return prefix + + +BASE_PREFIX = base_prefix() + + +@pytest.fixture() +def delete_files(): + paths = [] + yield paths + for path in paths: + path = Path(path) + try: + if path.is_dir(): + shutil.rmtree(path) + else: + path.unlink() + except IOError: + logging.warning("Could not delete %s", path) + + +@pytest.fixture(scope="function") +def tmpdir(tmpdir, request): + Path(str(tmpdir)).mkdir(parents=True, exist_ok=True) + tmpdir = TemporaryDirectory(dir=str(tmpdir)) + request.addfinalizer(tmpdir.cleanup) + return py.path.local(tmpdir.name) + + +@pytest.fixture(autouse=True) +def mock_locations(monkeypatch, tmp_path): + from menuinst.platforms.linux import LinuxMenu + from menuinst.platforms.osx import MacOSMenuItem + + if os.name == "nt": + from menuinst.platforms.win_utils import knownfolders + + def windows_locations(preferred_mode, check_other_mode, key): + return tmp_path / key + monkeypatch.setattr(knownfolders, "folder_path", windows_locations) + + def osx_base_location(self): + return tmp_path + monkeypatch.setattr(MacOSMenuItem, "_base_location", osx_base_location) + + # For Linux + monkeypatch.setattr(LinuxMenu, "_system_config_directory", tmp_path / "config") + monkeypatch.setattr(LinuxMenu, "_system_data_directory", tmp_path / "data") + monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "config")) + monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path / "data")) diff --git a/tests/data/jsons/entitlements.json b/tests/data/jsons/entitlements.json new file mode 100644 index 00000000..1e9f7713 --- /dev/null +++ b/tests/data/jsons/entitlements.json @@ -0,0 +1,28 @@ +{ + "$schema": "https://json-schema.org/draft-07/schema", + "$id": "https://schemas.conda.io/menuinst-1.schema.json", + "menu_name": "Example with entitlements", + "menu_items": [ + { + "name": "Example with entitlements on macOS", + "description": "This examples include entitlements on macOS, which require code signing.", + "icon": null, + "command": [ + "echo", + "entitlements" + ], + "platforms": { + "osx": { + "CFBundleName": "Entitlements", + "CFBundleDisplayName": "My Example with entitlements on macOS", + "entitlements": [ + "com.apple.security.files.user-selected.read-write" + ], + "LSEnvironment": { + "example_var": "example_value" + } + } + } + } + ] +} \ No newline at end of file diff --git a/tests/data/jsons/example-3.invalid.json b/tests/data/jsons/example-3.invalid.json new file mode 100644 index 00000000..c674f47e --- /dev/null +++ b/tests/data/jsons/example-3.invalid.json @@ -0,0 +1,20 @@ +{ + "$schema": "https://json-schema.org/draft-07/schema", + "$id": "https://schemas.conda.io/menuinst-1.schema.json", + "menu_name": "Example 2", + "menu_items": [ + { + "name": "Example", + "description": "This is invalid because platforms. cannot be a boolean", + "icon": null, + "command": [ + "python", + "-m", + "this" + ], + "platforms": { + "win": false + } + } + ] +} \ No newline at end of file diff --git a/tests/data/jsons/no-platforms.json b/tests/data/jsons/no-platforms.json new file mode 100644 index 00000000..27ea2497 --- /dev/null +++ b/tests/data/jsons/no-platforms.json @@ -0,0 +1,18 @@ +{ + "$schema": "https://json-schema.org/draft-07/schema", + "$id": "https://schemas.conda.io/menuinst-1.schema.json", + "menu_name": "NoPlatforms", + "menu_items": [ + { + "name": "NoPlatforms", + "description": "This won't install to any platform because the 'platforms' key is empty.", + "icon": null, + "command": [ + "python", + "-m", + "this" + ], + "platforms": {} + } + ] +} \ No newline at end of file diff --git a/tests/data/jsons/osx_symlinks.json b/tests/data/jsons/osx_symlinks.json new file mode 100644 index 00000000..b3f76d83 --- /dev/null +++ b/tests/data/jsons/osx_symlinks.json @@ -0,0 +1,24 @@ +{ + "$schema": "https://json-schema.org/draft-07/schema", + "$id": "https://schemas.conda.io/menuinst-1.schema.json", + "menu_name": "Example with macOS symlinks", + "menu_items": [ + { + "name": "Example with symlinks on macOS", + "description": "This examples include symlinks on macOS, which require code signing.", + "icon": null, + "command": [ + "{{ MENU_ITEM_LOCATION }}/Contents/Resources/python", + "-c", + "import sys; print(sys.executable)" + ], + "platforms": { + "osx": { + "link_in_bundle": { + "{{ PREFIX }}/bin/python": "{{ MENU_ITEM_LOCATION }}/Contents/Resources/python" + } + } + } + } + ] +} \ No newline at end of file diff --git a/tests/data/jsons/precommands.json b/tests/data/jsons/precommands.json new file mode 100644 index 00000000..a42d4331 --- /dev/null +++ b/tests/data/jsons/precommands.json @@ -0,0 +1,30 @@ +{ + "$schema": "https://json-schema.org/draft-07/schema", + "$id": "https://schemas.conda.io/menuinst-1.schema.json", + "menu_name": "Example with precommands", + "menu_items": [ + { + "name": "Precommands", + "description": "This examples run some logic before activation.", + "icon": null, + "precommand": "export TEST_VAR=\"rhododendron and bees\"", + "command": [ + "echo", + "$TEST_VAR" + ], + "platforms": { + "win": { + "precommand": "set \"TEST_VAR=rhododendron and bees\"", + "command": [ + "echo", + "%TEST_VAR%>", + "__WIN_OUTPUT_FILE__" + ], + "description": "A space is needed after the > redirection, but if it's added in the same argument, it will trigger extra quoting that will break the syntax." + }, + "linux": {}, + "osx": {} + } + } + ] +} \ No newline at end of file diff --git a/tests/data/jsons/sys-prefix.json b/tests/data/jsons/sys-prefix.json new file mode 100644 index 00000000..2aa7ba81 --- /dev/null +++ b/tests/data/jsons/sys-prefix.json @@ -0,0 +1,31 @@ +{ + "$schema": "https://json-schema.org/draft-07/schema", + "$id": "https://schemas.conda.io/menuinst-1.schema.json", + "menu_name": "Sys.Prefix", + "menu_items": [ + { + "name": "Sys.Prefix", + "description": "This will install to Windows and Linux with default options. MacOS has a custom option.", + "icon": null, + "command": [ + "{{ PYTHON }}", + "-c", + "import sys; print(sys.prefix)" + ], + "platforms": { + "win": { + "command": [ + "{{ PYTHON }}", + "-c", + "import os, sys; f = open(r'__WIN_OUTPUT_FILE__', 'w'); f.write(sys.prefix); f.close()" + ], + "description": "Note how __WIN_OUTPUT_FILE__ is using raw-strings. Otherwise the backslashes are not properly escaped." + }, + "linux": {}, + "osx": { + "CFBundleName": "Sys Prefix" + } + } + } + ] +} \ No newline at end of file diff --git a/tests/data/pkgs/noarch/package_1-0.1-0.tar.bz2 b/tests/data/pkgs/noarch/package_1-0.1-0.tar.bz2 new file mode 100644 index 00000000..6b060fe2 Binary files /dev/null and b/tests/data/pkgs/noarch/package_1-0.1-0.tar.bz2 differ diff --git a/tests/data/pkgs/package_1/LICENSE b/tests/data/pkgs/package_1/LICENSE new file mode 100644 index 00000000..f178eaa4 --- /dev/null +++ b/tests/data/pkgs/package_1/LICENSE @@ -0,0 +1,26 @@ +Copyright 2021, Jaime Rodríguez-Guerra + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation and/or +other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors +may be used to endorse or promote products derived from this software without +specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tests/data/pkgs/package_1/menu.json b/tests/data/pkgs/package_1/menu.json new file mode 100644 index 00000000..dc35140c --- /dev/null +++ b/tests/data/pkgs/package_1/menu.json @@ -0,0 +1,53 @@ +{ + "$schema": "https://json-schema.org/draft-07/schema", + "$id": "https://schemas.conda.io/menuinst-1.schema.json", + "menu_name": "Package 1", + "menu_items": [ + { + "name": "A", + "description": "This will echo environment variables for test purposes", + "icon": null, + "command": [ + "echo", + "${CONDA_PREFIX:-N/A}" + ], + "platforms": { + "win": { + "terminal": true, + "command": [ + "cmd", + "/V:ON", + "/C", + "echo", + "!CONDA_PREFIX!" + ] + }, + "linux": {}, + "osx": {} + } + }, + { + "name": "B", + "description": "This one does not preactivate the environment", + "icon": null, + "command": [ + "echo", + "${CONDA_PREFIX:-N/A}" + ], + "activate": false, + "platforms": { + "win": { + "command": [ + "cmd", + "/V:ON", + "/C", + "echo", + "!CONDA_PREFIX!" + ] + }, + "linux": {}, + "osx": {} + } + } + ] +} \ No newline at end of file diff --git a/tests/data/pkgs/package_1/meta.yaml b/tests/data/pkgs/package_1/meta.yaml new file mode 100644 index 00000000..0b71d30d --- /dev/null +++ b/tests/data/pkgs/package_1/meta.yaml @@ -0,0 +1,27 @@ +package: + name: package_1 + version: "0.1" + +source: + path: "." + +build: + noarch: generic + number: 0 + script: + - mkdir {{ PREFIX }}/Menu # [unix] + - cp {{ RECIPE_DIR }}/menu.json {{ PREFIX }}/Menu/package_1.json # [unix] + +requirements: + host: + - xz +test: + commands: + - test -f ${CONDA_PREFIX}/Menu/package_1.json # [unix] + +about: + home: http://github.com/conda/menuinst + license: BSD-3-Clause + license_family: BSD + license_file: LICENSE + summary: a test package for menuinst diff --git a/tests/test_api.py b/tests/test_api.py new file mode 100644 index 00000000..57079401 --- /dev/null +++ b/tests/test_api.py @@ -0,0 +1,148 @@ +"""""" +import os +import plistlib +import sys +import subprocess +from pathlib import Path +from tempfile import NamedTemporaryFile +from time import sleep, time + +import pytest + +from menuinst.api import install +from menuinst.utils import DEFAULT_PREFIX + +from conftest import DATA, PLATFORM + + +def check_output_from_shortcut(delete_files, json_path, expected_output=None): + abs_json_path = DATA / "jsons" / json_path + if PLATFORM == "win": + with open(abs_json_path) as f: + contents = f.read() + with NamedTemporaryFile(suffix=json_path, mode="w", delete=False) as tmp: + win_output_file = tmp.name + ".out" + contents = contents.replace("__WIN_OUTPUT_FILE__", win_output_file.replace("\\", "\\\\")) + tmp.write(contents) + abs_json_path = tmp.name + delete_files.append(abs_json_path) + + paths = install(abs_json_path) + # delete_files += list(paths) + + if PLATFORM == 'linux': + desktop = next(p for p in paths if p.suffix == ".desktop") + with open(desktop) as f: + for line in f: + if line.startswith("Exec="): + cmd = line.split("=", 1)[1].strip() + break + else: + raise ValueError("Didn't find Exec line") + output = subprocess.check_output(cmd, shell=True, universal_newlines=True) + elif PLATFORM == 'osx': + app_location = paths[0] + executable = next(p for p in (app_location / "Contents" / "MacOS").iterdir() if not p.name.endswith('-script')) + process = subprocess.run([str(executable)], text=True, capture_output=True) + if process.returncode: + print(process.stdout, file=sys.stdout) + print(process.stderr, file=sys.stderr) + process.check_returncode() + output = process.stdout + elif PLATFORM == 'win': + lnk = next(p for p in paths if p.suffix == ".lnk") + assert lnk.is_file() + # os.startfile does not propagate custom env vars, + # so we need to hardcode it with templating + # (see block at the beginning of the function) + os.startfile(lnk) + # startfile returns immediately; poll for the output file + # powershell + cmd take a couple seconds to start + activate env + start = time() + while not os.path.isfile(win_output_file): + sleep(1) + if time() >= start + 10: + raise RuntimeError(f"Timeout. File '{win_output_file}' was not created!") + with open(win_output_file) as f: + output = f.read() + + if expected_output is not None: + assert output.strip() == expected_output + + return paths, output + + +def test_install_prefix(delete_files): + check_output_from_shortcut(delete_files, "sys-prefix.json", expected_output=sys.prefix) + + +def test_precommands(delete_files): + check_output_from_shortcut(delete_files, "precommands.json", expected_output="rhododendron and bees") + + +@pytest.mark.skipif(PLATFORM != "osx", reason="macOS only") +def test_entitlements(delete_files): + paths, _ = check_output_from_shortcut(delete_files, "entitlements.json", expected_output="entitlements") + # verify signature + app_dir = next(p for p in paths if p.name.endswith('.app')) + subprocess.check_call(["/usr/bin/codesign", "--verbose", "--verify", str(app_dir)]) + + launcher = next(p for p in (app_dir / "Contents" / "MacOS").iterdir() if not p.name.endswith('-script')) + subprocess.check_call(["/usr/bin/codesign", "--verbose", "--verify", str(launcher)]) + + for path in app_dir.rglob("Info.plist"): + plist = plistlib.loads(path.read_bytes()) + assert plist + assert "entitlements" not in plist + break + else: + raise AssertionError("Didn't find Info.plist") + + for path in app_dir.rglob("Entitlements.plist"): + plist = plistlib.loads(path.read_bytes()) + assert plist + break + else: + raise AssertionError("Didn't find Entitlements.plist") + + +@pytest.mark.skipif(PLATFORM != "osx", reason="macOS only") +def test_no_entitlements_no_signature(delete_files): + paths, _ = check_output_from_shortcut(delete_files, "sys-prefix.json", expected_output=sys.prefix) + app_dir = next(p for p in paths if p.name.endswith('.app')) + launcher = next(p for p in (app_dir / "Contents" / "MacOS").iterdir() if not p.name.endswith('-script')) + with pytest.raises(subprocess.CalledProcessError): + subprocess.check_call(["/usr/bin/codesign", "--verbose", "--verify", str(app_dir)]) + with pytest.raises(subprocess.CalledProcessError): + subprocess.check_call(["/usr/bin/codesign", "--verbose", "--verify", str(launcher)]) + + +@pytest.mark.skipif(PLATFORM != "osx", reason="macOS only") +def test_info_plist(delete_files): + paths, _ = check_output_from_shortcut( + delete_files, + "entitlements.json", + expected_output="entitlements" + ) + app_dir = next(p for p in paths if p.name.endswith('.app')) + + for path in app_dir.rglob("Info.plist"): + plist = plistlib.loads(path.read_bytes()) + assert plist + break + else: + raise AssertionError("Didn't find file") + + assert plist["LSEnvironment"]["example_var"] == "example_value" + + +@pytest.mark.skipif(PLATFORM != "osx", reason="macOS only") +def test_osx_symlinks(delete_files): + paths, output = check_output_from_shortcut( + delete_files, + "osx_symlinks.json", + ) + app_dir = next(p for p in paths if p.name.endswith('.app')) + symlinked_python = app_dir / "Contents" / "Resources" / "python" + assert output.strip() == str(symlinked_python) + assert symlinked_python.resolve() == (Path(DEFAULT_PREFIX) / "bin" / "python").resolve() diff --git a/tests/test_conda.py b/tests/test_conda.py new file mode 100644 index 00000000..ff9adbac --- /dev/null +++ b/tests/test_conda.py @@ -0,0 +1,169 @@ +""" +Integration tests with conda +""" +import os +import sys +from subprocess import check_output +from tempfile import NamedTemporaryFile +from pathlib import Path +from contextlib import contextmanager +import json + +import pytest +from conda.models.version import VersionOrder +from conda.testing.integration import run_command + +from menuinst.platforms import Menu, MenuItem +from menuinst._schema import validate + +from conftest import DATA, PLATFORM, BASE_PREFIX + + +ENV_VARS = { + k: v + for (k, v) in os.environ.copy().items() + if not k.startswith(("CONDA", "_CONDA", "MAMBA", "_MAMBA")) +} +ENV_VARS["CONDA_VERBOSITY"] = "3" + + +@contextmanager +def new_environment(tmpdir, *packages): + try: + prefix = str(tmpdir / "prefix") + print("--- CREATING", prefix, "---") + stdout, stderr, retcode = run_command("create", prefix, "-y", "--offline", *[str(p) for p in packages]) + assert not retcode + for stream in (stdout, stderr): + if "menuinst Exception" in stream: + raise RuntimeError( + f"Creation command exited with 0 but stdout contained exception:\n{stream}" + ) + + yield prefix + finally: + print("--- REMOVING", prefix, "---") + stdout, stderr, retcode = run_command("remove", prefix, "--offline", "--all") + assert not retcode + for stream in (stdout, stderr): + if "menuinst Exception" in stream: + raise RuntimeError( + f"Deletion Command exited with 0 but stdout contained exception:\n{stream}" + ) + + +@contextmanager +def install_package_1(tmpdir): + """ + This package is shipped with the test data and contains two menu items. + + Both will echo the `CONDA_PREFIX` environment variable. However, the + first one preactivates the environment, while the second does not. This + means that the first shortcut will successfully echo the prefix path, + while the second one will be empty (Windows) or "N/A" (Unix). + """ + with new_environment(tmpdir, DATA / "pkgs" / "noarch" / "package_1-0.1-0.tar.bz2") as prefix: + menu_file = Path(prefix) / "Menu" / "package_1.json" + with open(menu_file) as f: + meta = json.load(f) + assert len(meta["menu_items"]) == 2 + assert menu_file.is_file() + yield prefix, menu_file + assert not menu_file.is_file() + + +def test_conda_recent_enough(): + data = json.loads(check_output([sys.executable, "-I", "-m", "conda", "info", "--json"])) + assert VersionOrder(data["conda_version"]) >= VersionOrder("4.12a0") + + +@pytest.mark.skipif(PLATFORM != "linux", reason="Linux only") +def test_package_1_linux(tmpdir): + applications_menu = Path(tmpdir) / "config" / "menus" / "applications.menu" + if applications_menu.is_file(): + original_xml = applications_menu.read_text() + else: + original_xml = None + with install_package_1(tmpdir) as (prefix, menu_file): + meta = validate(menu_file) + menu = Menu(meta.menu_name, str(prefix), BASE_PREFIX) + menu_items = [item.dict() for item in meta.menu_items] + items = [menu] + + # First case, activation is on, output should be the prefix path + # Second case, activation is off, output should be N/A + for item, expected_output in zip(menu_items, (str(prefix), "N/A")): + item = MenuItem(menu, item) + items.append(item) + command = item._command() + print(command) + print("-----") + output = check_output(command, shell=True, universal_newlines=True, env=ENV_VARS) + assert output.strip() == expected_output + + assert not Path(prefix).exists() + for item in items: + for path in item._paths(): + assert not path.exists() + + if original_xml: + assert original_xml == applications_menu.read_text() + + +@pytest.mark.skipif(PLATFORM != "osx", reason="MacOS only") +def test_package_1_osx(tmpdir): + with install_package_1(tmpdir) as (prefix, menu_file): + meta = validate(menu_file) + menu_items = [item.dict() for item in meta.menu_items] + menu = Menu(meta.menu_name, str(prefix), BASE_PREFIX) + items = [menu] + # First case, activation is on, output should be the prefix path + # Second case, activation is off, output should be N/A + for item, expected_output in zip(menu_items, (str(prefix), "N/A")): + item = MenuItem(menu, item) + items.append(item) + script = item._write_script( + script_path=NamedTemporaryFile(suffix=".sh", delete=False).name + ) + print(item._command()) + print("-------------") + output = check_output(["bash", script], universal_newlines=True, env=ENV_VARS) + Path(script).unlink() + assert output.strip() == expected_output + + assert not Path(prefix).exists() + for item in items: + for path in item._paths(): + assert not path.exists() + + +@pytest.mark.skipif(PLATFORM != "win", reason="Windows only") +def test_package_1_windows(tmpdir): + with install_package_1(tmpdir) as (prefix, menu_file): + meta = validate(menu_file) + menu = Menu(meta.menu_name, str(prefix), BASE_PREFIX) + menu_items = [item.dict() for item in meta.menu_items] + items = [menu] + # First case, activation is on, output should be the prefix path + # Second case, activation is off, output should be empty + for item, expected_output in zip(menu_items, (str(prefix), "!CONDA_PREFIX!")): + item = MenuItem(menu, item) + items.append(item) + script = item._write_script( + script_path=NamedTemporaryFile(suffix=".bat", delete=False).name + ) + print(item._command()) + print("-------------") + output = check_output( + ["cmd.exe", "/C", f"conda deactivate && conda deactivate && {script}"], + universal_newlines=True, + env=ENV_VARS, + ) + Path(script).unlink() + output = output.replace("ECHO is off.", "") + assert output.splitlines()[0].strip() == expected_output + + assert not Path(prefix).exists() + for item in items: + for path in item._paths(): + assert not path.exists() diff --git a/tests/test_data.py b/tests/test_data.py new file mode 100644 index 00000000..b873fcf7 --- /dev/null +++ b/tests/test_data.py @@ -0,0 +1,20 @@ +"""Ensure JSON schemas are up-to-date with code""" + +import json + +from menuinst.utils import data_path +from menuinst._schema import dump_default_to_json, dump_schema_to_json + + +def test_schema_is_up_to_date(): + with open(data_path("menuinst.schema.json")) as f: + in_file = json.load(f) + in_code = dump_schema_to_json(write=False) + assert in_file == in_code + + +def test_defaults_are_up_to_date(): + with open(data_path("menuinst.menu_item.default.json")) as f: + in_file = json.load(f) + in_code = dump_default_to_json(write=False) + assert in_file == in_code diff --git a/tests/test_schema.py b/tests/test_schema.py new file mode 100644 index 00000000..87ca4ac6 --- /dev/null +++ b/tests/test_schema.py @@ -0,0 +1,30 @@ +import pytest + +# from hypothesis import given, settings, HealthCheck +# from hypothesis_jsonschema import from_schema +from pydantic import ValidationError + +from menuinst._schema import validate, MenuItemMetadata, OptionalMenuItemMetadata +from conftest import DATA + +# # suppress_health_check=3 --> too_slow +# @settings(max_examples=100, suppress_health_check=[HealthCheck.too_slow]) +# @given(from_schema(MenuInstSchema.schema())) +# def test_schema_can_be_loaded(value): +# assert value + + +@pytest.mark.parametrize("path", (DATA / "jsons").glob("*.json")) +def test_examples(path): + if "invalid" in path.name: + with pytest.raises(ValidationError): + assert validate(path) + else: + assert validate(path) + +def test_MenuItemMetadata_synced_with_OptionalMenuItemMetadata(): + fields_as_required = MenuItemMetadata.__fields__ + fields_as_optional = OptionalMenuItemMetadata.__fields__ + assert fields_as_required.keys() == fields_as_optional.keys() + for required, optional in zip(fields_as_required.values(), fields_as_optional.values()): + assert required.field_info.description == optional.field_info.description diff --git a/versioneer.py b/versioneer.py deleted file mode 100644 index c010f63e..00000000 --- a/versioneer.py +++ /dev/null @@ -1,1699 +0,0 @@ - -# Version: 0.15 - -""" -The Versioneer -============== - -* like a rocketeer, but for versions! -* https://github.com/warner/python-versioneer -* Brian Warner -* License: Public Domain -* Compatible With: python2.6, 2.7, 3.2, 3.3, 3.4, and pypy -* [![Latest Version] -(https://pypip.in/version/versioneer/badge.svg?style=flat) -](https://pypi.python.org/pypi/versioneer/) -* [![Build Status] -(https://travis-ci.org/warner/python-versioneer.png?branch=master) -](https://travis-ci.org/warner/python-versioneer) - -This is a tool for managing a recorded version number in distutils-based -python projects. The goal is to remove the tedious and error-prone "update -the embedded version string" step from your release process. Making a new -release should be as easy as recording a new tag in your version-control -system, and maybe making new tarballs. - - -## Quick Install - -* `pip install versioneer` to somewhere to your $PATH -* add a `[versioneer]` section to your setup.cfg (see below) -* run `versioneer install` in your source tree, commit the results - -## Version Identifiers - -Source trees come from a variety of places: - -* a version-control system checkout (mostly used by developers) -* a nightly tarball, produced by build automation -* a snapshot tarball, produced by a web-based VCS browser, like github's - "tarball from tag" feature -* a release tarball, produced by "setup.py sdist", distributed through PyPI - -Within each source tree, the version identifier (either a string or a number, -this tool is format-agnostic) can come from a variety of places: - -* ask the VCS tool itself, e.g. "git describe" (for checkouts), which knows - about recent "tags" and an absolute revision-id -* the name of the directory into which the tarball was unpacked -* an expanded VCS keyword ($Id$, etc) -* a `_version.py` created by some earlier build step - -For released software, the version identifier is closely related to a VCS -tag. Some projects use tag names that include more than just the version -string (e.g. "myproject-1.2" instead of just "1.2"), in which case the tool -needs to strip the tag prefix to extract the version identifier. For -unreleased software (between tags), the version identifier should provide -enough information to help developers recreate the same tree, while also -giving them an idea of roughly how old the tree is (after version 1.2, before -version 1.3). Many VCS systems can report a description that captures this, -for example `git describe --tags --dirty --always` reports things like -"0.7-1-g574ab98-dirty" to indicate that the checkout is one revision past the -0.7 tag, has a unique revision id of "574ab98", and is "dirty" (it has -uncommitted changes. - -The version identifier is used for multiple purposes: - -* to allow the module to self-identify its version: `myproject.__version__` -* to choose a name and prefix for a 'setup.py sdist' tarball - -## Theory of Operation - -Versioneer works by adding a special `_version.py` file into your source -tree, where your `__init__.py` can import it. This `_version.py` knows how to -dynamically ask the VCS tool for version information at import time. - -`_version.py` also contains `$Revision$` markers, and the installation -process marks `_version.py` to have this marker rewritten with a tag name -during the `git archive` command. As a result, generated tarballs will -contain enough information to get the proper version. - -To allow `setup.py` to compute a version too, a `versioneer.py` is added to -the top level of your source tree, next to `setup.py` and the `setup.cfg` -that configures it. This overrides several distutils/setuptools commands to -compute the version when invoked, and changes `setup.py build` and `setup.py -sdist` to replace `_version.py` with a small static file that contains just -the generated version data. - -## Installation - -First, decide on values for the following configuration variables: - -* `VCS`: the version control system you use. Currently accepts "git". - -* `style`: the style of version string to be produced. See "Styles" below for - details. Defaults to "pep440", which looks like - `TAG[+DISTANCE.gSHORTHASH[.dirty]]`. - -* `versionfile_source`: - - A project-relative pathname into which the generated version strings should - be written. This is usually a `_version.py` next to your project's main - `__init__.py` file, so it can be imported at runtime. If your project uses - `src/myproject/__init__.py`, this should be `src/myproject/_version.py`. - This file should be checked in to your VCS as usual: the copy created below - by `setup.py setup_versioneer` will include code that parses expanded VCS - keywords in generated tarballs. The 'build' and 'sdist' commands will - replace it with a copy that has just the calculated version string. - - This must be set even if your project does not have any modules (and will - therefore never import `_version.py`), since "setup.py sdist" -based trees - still need somewhere to record the pre-calculated version strings. Anywhere - in the source tree should do. If there is a `__init__.py` next to your - `_version.py`, the `setup.py setup_versioneer` command (described below) - will append some `__version__`-setting assignments, if they aren't already - present. - -* `versionfile_build`: - - Like `versionfile_source`, but relative to the build directory instead of - the source directory. These will differ when your setup.py uses - 'package_dir='. If you have `package_dir={'myproject': 'src/myproject'}`, - then you will probably have `versionfile_build='myproject/_version.py'` and - `versionfile_source='src/myproject/_version.py'`. - - If this is set to None, then `setup.py build` will not attempt to rewrite - any `_version.py` in the built tree. If your project does not have any - libraries (e.g. if it only builds a script), then you should use - `versionfile_build = None` and override `distutils.command.build_scripts` - to explicitly insert a copy of `versioneer.get_version()` into your - generated script. - -* `tag_prefix`: - - a string, like 'PROJECTNAME-', which appears at the start of all VCS tags. - If your tags look like 'myproject-1.2.0', then you should use - tag_prefix='myproject-'. If you use unprefixed tags like '1.2.0', this - should be an empty string. - -* `parentdir_prefix`: - - a optional string, frequently the same as tag_prefix, which appears at the - start of all unpacked tarball filenames. If your tarball unpacks into - 'myproject-1.2.0', this should be 'myproject-'. To disable this feature, - just omit the field from your `setup.cfg`. - -This tool provides one script, named `versioneer`. That script has one mode, -"install", which writes a copy of `versioneer.py` into the current directory -and runs `versioneer.py setup` to finish the installation. - -To versioneer-enable your project: - -* 1: Modify your `setup.cfg`, adding a section named `[versioneer]` and - populating it with the configuration values you decided earlier (note that - the option names are not case-sensitive): - - ```` - [versioneer] - VCS = git - style = pep440 - versionfile_source = src/myproject/_version.py - versionfile_build = myproject/_version.py - tag_prefix = "" - parentdir_prefix = myproject- - ```` - -* 2: Run `versioneer install`. This will do the following: - - * copy `versioneer.py` into the top of your source tree - * create `_version.py` in the right place (`versionfile_source`) - * modify your `__init__.py` (if one exists next to `_version.py`) to define - `__version__` (by calling a function from `_version.py`) - * modify your `MANIFEST.in` to include both `versioneer.py` and the - generated `_version.py` in sdist tarballs - - `versioneer install` will complain about any problems it finds with your - `setup.py` or `setup.cfg`. Run it multiple times until you have fixed all - the problems. - -* 3: add a `import versioneer` to your setup.py, and add the following - arguments to the setup() call: - - version=versioneer.get_version(), - cmdclass=versioneer.get_cmdclass(), - -* 4: commit these changes to your VCS. To make sure you won't forget, - `versioneer install` will mark everything it touched for addition using - `git add`. Don't forget to add `setup.py` and `setup.cfg` too. - -## Post-Installation Usage - -Once established, all uses of your tree from a VCS checkout should get the -current version string. All generated tarballs should include an embedded -version string (so users who unpack them will not need a VCS tool installed). - -If you distribute your project through PyPI, then the release process should -boil down to two steps: - -* 1: git tag 1.0 -* 2: python setup.py register sdist upload - -If you distribute it through github (i.e. users use github to generate -tarballs with `git archive`), the process is: - -* 1: git tag 1.0 -* 2: git push; git push --tags - -Versioneer will report "0+untagged.NUMCOMMITS.gHASH" until your tree has at -least one tag in its history. - -## Version-String Flavors - -Code which uses Versioneer can learn about its version string at runtime by -importing `_version` from your main `__init__.py` file and running the -`get_versions()` function. From the "outside" (e.g. in `setup.py`), you can -import the top-level `versioneer.py` and run `get_versions()`. - -Both functions return a dictionary with different flavors of version -information: - -* `['version']`: A condensed version string, rendered using the selected - style. This is the most commonly used value for the project's version - string. The default "pep440" style yields strings like `0.11`, - `0.11+2.g1076c97`, or `0.11+2.g1076c97.dirty`. See the "Styles" section - below for alternative styles. - -* `['full-revisionid']`: detailed revision identifier. For Git, this is the - full SHA1 commit id, e.g. "1076c978a8d3cfc70f408fe5974aa6c092c949ac". - -* `['dirty']`: a boolean, True if the tree has uncommitted changes. Note that - this is only accurate if run in a VCS checkout, otherwise it is likely to - be False or None - -* `['error']`: if the version string could not be computed, this will be set - to a string describing the problem, otherwise it will be None. It may be - useful to throw an exception in setup.py if this is set, to avoid e.g. - creating tarballs with a version string of "unknown". - -Some variants are more useful than others. Including `full-revisionid` in a -bug report should allow developers to reconstruct the exact code being tested -(or indicate the presence of local changes that should be shared with the -developers). `version` is suitable for display in an "about" box or a CLI -`--version` output: it can be easily compared against release notes and lists -of bugs fixed in various releases. - -The installer adds the following text to your `__init__.py` to place a basic -version in `YOURPROJECT.__version__`: - - from ._version import get_versions - __version__ = get_versions()['version'] - del get_versions - -## Styles - -The setup.cfg `style=` configuration controls how the VCS information is -rendered into a version string. - -The default style, "pep440", produces a PEP440-compliant string, equal to the -un-prefixed tag name for actual releases, and containing an additional "local -version" section with more detail for in-between builds. For Git, this is -TAG[+DISTANCE.gHEX[.dirty]] , using information from `git describe --tags ---dirty --always`. For example "0.11+2.g1076c97.dirty" indicates that the -tree is like the "1076c97" commit but has uncommitted changes (".dirty"), and -that this commit is two revisions ("+2") beyond the "0.11" tag. For released -software (exactly equal to a known tag), the identifier will only contain the -stripped tag, e.g. "0.11". - -Other styles are available. See details.md in the Versioneer source tree for -descriptions. - -## Debugging - -Versioneer tries to avoid fatal errors: if something goes wrong, it will tend -to return a version of "0+unknown". To investigate the problem, run `setup.py -version`, which will run the version-lookup code in a verbose mode, and will -display the full contents of `get_versions()` (including the `error` string, -which may help identify what went wrong). - -## Updating Versioneer - -To upgrade your project to a new release of Versioneer, do the following: - -* install the new Versioneer (`pip install -U versioneer` or equivalent) -* edit `setup.cfg`, if necessary, to include any new configuration settings - indicated by the release notes -* re-run `versioneer install` in your source tree, to replace - `SRC/_version.py` -* commit any changed files - -### Upgrading to 0.15 - -Starting with this version, Versioneer is configured with a `[versioneer]` -section in your `setup.cfg` file. Earlier versions required the `setup.py` to -set attributes on the `versioneer` module immediately after import. The new -version will refuse to run (raising an exception during import) until you -have provided the necessary `setup.cfg` section. - -In addition, the Versioneer package provides an executable named -`versioneer`, and the installation process is driven by running `versioneer -install`. In 0.14 and earlier, the executable was named -`versioneer-installer` and was run without an argument. - -### Upgrading to 0.14 - -0.14 changes the format of the version string. 0.13 and earlier used -hyphen-separated strings like "0.11-2-g1076c97-dirty". 0.14 and beyond use a -plus-separated "local version" section strings, with dot-separated -components, like "0.11+2.g1076c97". PEP440-strict tools did not like the old -format, but should be ok with the new one. - -### Upgrading from 0.11 to 0.12 - -Nothing special. - -### Upgrading from 0.10 to 0.11 - -You must add a `versioneer.VCS = "git"` to your `setup.py` before re-running -`setup.py setup_versioneer`. This will enable the use of additional -version-control systems (SVN, etc) in the future. - -## Future Directions - -This tool is designed to make it easily extended to other version-control -systems: all VCS-specific components are in separate directories like -src/git/ . The top-level `versioneer.py` script is assembled from these -components by running make-versioneer.py . In the future, make-versioneer.py -will take a VCS name as an argument, and will construct a version of -`versioneer.py` that is specific to the given VCS. It might also take the -configuration arguments that are currently provided manually during -installation by editing setup.py . Alternatively, it might go the other -direction and include code from all supported VCS systems, reducing the -number of intermediate scripts. - - -## License - -To make Versioneer easier to embed, all its code is hereby released into the -public domain. The `_version.py` that it creates is also in the public -domain. - -""" - -from __future__ import print_function -try: - import configparser -except ImportError: - import ConfigParser as configparser -import errno -import json -import os -import re -import subprocess -import sys - - -class VersioneerConfig: - pass - - -def get_root(): - # we require that all commands are run from the project root, i.e. the - # directory that contains setup.py, setup.cfg, and versioneer.py . - root = os.path.realpath(os.path.abspath(os.getcwd())) - setup_py = os.path.join(root, "setup.py") - versioneer_py = os.path.join(root, "versioneer.py") - if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): - # allow 'python path/to/setup.py COMMAND' - root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0]))) - setup_py = os.path.join(root, "setup.py") - versioneer_py = os.path.join(root, "versioneer.py") - if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): - err = ("Versioneer was unable to run the project root directory. " - "Versioneer requires setup.py to be executed from " - "its immediate directory (like 'python setup.py COMMAND'), " - "or in a way that lets it use sys.argv[0] to find the root " - "(like 'python path/to/setup.py COMMAND').") - raise VersioneerBadRootError(err) - try: - # Certain runtime workflows (setup.py install/develop in a setuptools - # tree) execute all dependencies in a single python process, so - # "versioneer" may be imported multiple times, and python's shared - # module-import table will cache the first one. So we can't use - # os.path.dirname(__file__), as that will find whichever - # versioneer.py was first imported, even in later projects. - me = os.path.realpath(os.path.abspath(__file__)) - if os.path.splitext(me)[0] != os.path.splitext(versioneer_py)[0]: - print("Warning: build in %s is using versioneer.py from %s" - % (os.path.dirname(me), versioneer_py)) - except NameError: - pass - return root - - -def get_config_from_root(root): - # This might raise EnvironmentError (if setup.cfg is missing), or - # configparser.NoSectionError (if it lacks a [versioneer] section), or - # configparser.NoOptionError (if it lacks "VCS="). See the docstring at - # the top of versioneer.py for instructions on writing your setup.cfg . - setup_cfg = os.path.join(root, "setup.cfg") - parser = configparser.SafeConfigParser() - with open(setup_cfg, "r") as f: - parser.readfp(f) - VCS = parser.get("versioneer", "VCS") # mandatory - - def get(parser, name): - if parser.has_option("versioneer", name): - return parser.get("versioneer", name) - return None - cfg = VersioneerConfig() - cfg.VCS = VCS - cfg.style = get(parser, "style") or "" - cfg.versionfile_source = get(parser, "versionfile_source") - cfg.versionfile_build = get(parser, "versionfile_build") - cfg.tag_prefix = get(parser, "tag_prefix") - cfg.parentdir_prefix = get(parser, "parentdir_prefix") - cfg.verbose = get(parser, "verbose") - return cfg - - -class NotThisMethod(Exception): - pass - -# these dictionaries contain VCS-specific tools -LONG_VERSION_PY = {} -HANDLERS = {} - - -def register_vcs_handler(vcs, method): # decorator - def decorate(f): - if vcs not in HANDLERS: - HANDLERS[vcs] = {} - HANDLERS[vcs][method] = f - return f - return decorate - - -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False): - assert isinstance(commands, list) - p = None - for c in commands: - try: - dispcmd = str([c] + args) - # remember shell=False, so use git.cmd on windows, not just git - p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None)) - break - except EnvironmentError: - e = sys.exc_info()[1] - if e.errno == errno.ENOENT: - continue - if verbose: - print("unable to run %s" % dispcmd) - print(e) - return None - else: - if verbose: - print("unable to find command, tried %s" % (commands,)) - return None - stdout = p.communicate()[0].strip() - if sys.version_info[0] >= 3: - stdout = stdout.decode() - if p.returncode != 0: - if verbose: - print("unable to run %s (error)" % dispcmd) - return None - return stdout -LONG_VERSION_PY['git'] = ''' -# This file helps to compute a version number in source trees obtained from -# git-archive tarball (such as those provided by githubs download-from-tag -# feature). Distribution tarballs (built by setup.py sdist) and build -# directories (produced by setup.py build) will contain a much shorter file -# that just contains the computed version number. - -# This file is released into the public domain. Generated by -# versioneer-0.15 (https://github.com/warner/python-versioneer) - -import errno -import os -import re -import subprocess -import sys - - -def get_keywords(): - # these strings will be replaced by git during git-archive. - # setup.py/versioneer.py will grep for the variable names, so they must - # each be defined on a line of their own. _version.py will just call - # get_keywords(). - git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s" - git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s" - keywords = {"refnames": git_refnames, "full": git_full} - return keywords - - -class VersioneerConfig: - pass - - -def get_config(): - # these strings are filled in when 'setup.py versioneer' creates - # _version.py - cfg = VersioneerConfig() - cfg.VCS = "git" - cfg.style = "%(STYLE)s" - cfg.tag_prefix = "%(TAG_PREFIX)s" - cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s" - cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s" - cfg.verbose = False - return cfg - - -class NotThisMethod(Exception): - pass - - -LONG_VERSION_PY = {} -HANDLERS = {} - - -def register_vcs_handler(vcs, method): # decorator - def decorate(f): - if vcs not in HANDLERS: - HANDLERS[vcs] = {} - HANDLERS[vcs][method] = f - return f - return decorate - - -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False): - assert isinstance(commands, list) - p = None - for c in commands: - try: - dispcmd = str([c] + args) - # remember shell=False, so use git.cmd on windows, not just git - p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None)) - break - except EnvironmentError: - e = sys.exc_info()[1] - if e.errno == errno.ENOENT: - continue - if verbose: - print("unable to run %%s" %% dispcmd) - print(e) - return None - else: - if verbose: - print("unable to find command, tried %%s" %% (commands,)) - return None - stdout = p.communicate()[0].strip() - if sys.version_info[0] >= 3: - stdout = stdout.decode() - if p.returncode != 0: - if verbose: - print("unable to run %%s (error)" %% dispcmd) - return None - return stdout - - -def versions_from_parentdir(parentdir_prefix, root, verbose): - # Source tarballs conventionally unpack into a directory that includes - # both the project name and a version string. - dirname = os.path.basename(root) - if not dirname.startswith(parentdir_prefix): - if verbose: - print("guessing rootdir is '%%s', but '%%s' doesn't start with " - "prefix '%%s'" %% (root, dirname, parentdir_prefix)) - raise NotThisMethod("rootdir doesn't start with parentdir_prefix") - return {"version": dirname[len(parentdir_prefix):], - "full-revisionid": None, - "dirty": False, "error": None} - - -@register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): - # the code embedded in _version.py can just fetch the value of these - # keywords. When used from setup.py, we don't want to import _version.py, - # so we do it with a regexp instead. This function is not used from - # _version.py. - keywords = {} - try: - f = open(versionfile_abs, "r") - for line in f.readlines(): - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - f.close() - except EnvironmentError: - pass - return keywords - - -@register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): - if not keywords: - raise NotThisMethod("no keywords at all, weird") - refnames = keywords["refnames"].strip() - if refnames.startswith("$Format"): - if verbose: - print("keywords are unexpanded, not using") - raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set([r.strip() for r in refnames.strip("()").split(",")]) - # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of - # just "foo-1.0". If we see a "tag: " prefix, prefer those. - TAG = "tag: " - tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) - if not tags: - # Either we're using git < 1.8.3, or there really are no tags. We use - # a heuristic: assume all version tags have a digit. The old git %%d - # expansion behaves like git log --decorate=short and strips out the - # refs/heads/ and refs/tags/ prefixes that would let us distinguish - # between branches and tags. By ignoring refnames without digits, we - # filter out many common branch names like "release" and - # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r'\d', r)]) - if verbose: - print("discarding '%%s', no digits" %% ",".join(refs-tags)) - if verbose: - print("likely tags: %%s" %% ",".join(sorted(tags))) - for ref in sorted(tags): - # sorting will prefer e.g. "2.0" over "2.0rc1" - if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] - if verbose: - print("picking %%s" %% r) - return {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None - } - # no suitable tags, so version is "0+unknown", but full hex is still there - if verbose: - print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags"} - - -@register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): - # this runs 'git' from the root of the source tree. This only gets called - # if the git-archive 'subst' keywords were *not* expanded, and - # _version.py hasn't already been rewritten with a short version string, - # meaning we're inside a checked out source tree. - - if not os.path.exists(os.path.join(root, ".git")): - if verbose: - print("no .git in %%s" %% root) - raise NotThisMethod("no .git directory") - - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - # if there is a tag, this yields TAG-NUM-gHEX[-dirty] - # if there are no tags, this yields HEX[-dirty] (no NUM) - describe_out = run_command(GITS, ["describe", "--tags", "--dirty", - "--always", "--long"], - cwd=root) - # --long was added in git-1.5.5 - if describe_out is None: - raise NotThisMethod("'git describe' failed") - describe_out = describe_out.strip() - full_out = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) - if full_out is None: - raise NotThisMethod("'git rev-parse' failed") - full_out = full_out.strip() - - pieces = {} - pieces["long"] = full_out - pieces["short"] = full_out[:7] # maybe improved later - pieces["error"] = None - - # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] - # TAG might have hyphens. - git_describe = describe_out - - # look for -dirty suffix - dirty = git_describe.endswith("-dirty") - pieces["dirty"] = dirty - if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] - - # now we have TAG-NUM-gHEX or HEX - - if "-" in git_describe: - # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) - if not mo: - # unparseable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%%s'" - %% describe_out) - return pieces - - # tag - full_tag = mo.group(1) - if not full_tag.startswith(tag_prefix): - if verbose: - fmt = "tag '%%s' doesn't start with prefix '%%s'" - print(fmt %% (full_tag, tag_prefix)) - pieces["error"] = ("tag '%%s' doesn't start with prefix '%%s'" - %% (full_tag, tag_prefix)) - return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] - - # distance: number of commits since tag - pieces["distance"] = int(mo.group(2)) - - # commit: short hex revision ID - pieces["short"] = mo.group(3) - - else: - # HEX: no tags - pieces["closest-tag"] = None - count_out = run_command(GITS, ["rev-list", "HEAD", "--count"], - cwd=root) - pieces["distance"] = int(count_out) # total number of commits - - return pieces - - -def plus_or_dot(pieces): - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces): - # now build up version string, with post-release "local version - # identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you - # get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty - - # exceptions: - # 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] - - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += plus_or_dot(pieces) - rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_pre(pieces): - # TAG[.post.devDISTANCE] . No -dirty - - # exceptions: - # 1: no tags. 0.post.devDISTANCE - - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += ".post.dev%%d" %% pieces["distance"] - else: - # exception #1 - rendered = "0.post.dev%%d" %% pieces["distance"] - return rendered - - -def render_pep440_post(pieces): - # TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that - # .dev0 sorts backwards (a dirty tree will appear "older" than the - # corresponding clean one), but you shouldn't be releasing software with - # -dirty anyways. - - # exceptions: - # 1: no tags. 0.postDISTANCE[.dev0] - - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%%s" %% pieces["short"] - else: - # exception #1 - rendered = "0.post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += "+g%%s" %% pieces["short"] - return rendered - - -def render_pep440_old(pieces): - # TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. - - # exceptions: - # 1: no tags. 0.postDISTANCE[.dev0] - - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - else: - # exception #1 - rendered = "0.post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - return rendered - - -def render_git_describe(pieces): - # TAG[-DISTANCE-gHEX][-dirty], like 'git describe --tags --dirty - # --always' - - # exceptions: - # 1: no tags. HEX[-dirty] (note: no 'g' prefix) - - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render_git_describe_long(pieces): - # TAG-DISTANCE-gHEX[-dirty], like 'git describe --tags --dirty - # --always -long'. The distance/hash is unconditional. - - # exceptions: - # 1: no tags. HEX[-dirty] (note: no 'g' prefix) - - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render(pieces, style): - if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"]} - - if not style or style == "default": - style = "pep440" # the default - - if style == "pep440": - rendered = render_pep440(pieces) - elif style == "pep440-pre": - rendered = render_pep440_pre(pieces) - elif style == "pep440-post": - rendered = render_pep440_post(pieces) - elif style == "pep440-old": - rendered = render_pep440_old(pieces) - elif style == "git-describe": - rendered = render_git_describe(pieces) - elif style == "git-describe-long": - rendered = render_git_describe_long(pieces) - else: - raise ValueError("unknown style '%%s'" %% style) - - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None} - - -def get_versions(): - # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have - # __file__, we can work backwards from there to the root. Some - # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which - # case we can only use expanded keywords. - - cfg = get_config() - verbose = cfg.verbose - - try: - return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, - verbose) - except NotThisMethod: - pass - - try: - root = os.path.realpath(__file__) - # versionfile_source is the relative path from the top of the source - # tree (where the .git directory might live) to this file. Invert - # this to find the root from __file__. - for i in cfg.versionfile_source.split('/'): - root = os.path.dirname(root) - except NameError: - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to find root of source tree"} - - try: - pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) - return render(pieces, cfg.style) - except NotThisMethod: - pass - - try: - if cfg.parentdir_prefix: - return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) - except NotThisMethod: - pass - - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to compute version"} -''' - - -@register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): - # the code embedded in _version.py can just fetch the value of these - # keywords. When used from setup.py, we don't want to import _version.py, - # so we do it with a regexp instead. This function is not used from - # _version.py. - keywords = {} - try: - f = open(versionfile_abs, "r") - for line in f.readlines(): - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - f.close() - except EnvironmentError: - pass - return keywords - - -@register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): - if not keywords: - raise NotThisMethod("no keywords at all, weird") - refnames = keywords["refnames"].strip() - if refnames.startswith("$Format"): - if verbose: - print("keywords are unexpanded, not using") - raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set([r.strip() for r in refnames.strip("()").split(",")]) - # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of - # just "foo-1.0". If we see a "tag: " prefix, prefer those. - TAG = "tag: " - tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) - if not tags: - # Either we're using git < 1.8.3, or there really are no tags. We use - # a heuristic: assume all version tags have a digit. The old git %d - # expansion behaves like git log --decorate=short and strips out the - # refs/heads/ and refs/tags/ prefixes that would let us distinguish - # between branches and tags. By ignoring refnames without digits, we - # filter out many common branch names like "release" and - # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r'\d', r)]) - if verbose: - print("discarding '%s', no digits" % ",".join(refs-tags)) - if verbose: - print("likely tags: %s" % ",".join(sorted(tags))) - for ref in sorted(tags): - # sorting will prefer e.g. "2.0" over "2.0rc1" - if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] - if verbose: - print("picking %s" % r) - return {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None - } - # no suitable tags, so version is "0+unknown", but full hex is still there - if verbose: - print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags"} - - -@register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): - # this runs 'git' from the root of the source tree. This only gets called - # if the git-archive 'subst' keywords were *not* expanded, and - # _version.py hasn't already been rewritten with a short version string, - # meaning we're inside a checked out source tree. - - if not os.path.exists(os.path.join(root, ".git")): - if verbose: - print("no .git in %s" % root) - raise NotThisMethod("no .git directory") - - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - # if there is a tag, this yields TAG-NUM-gHEX[-dirty] - # if there are no tags, this yields HEX[-dirty] (no NUM) - describe_out = run_command(GITS, ["describe", "--tags", "--dirty", - "--always", "--long"], - cwd=root) - # --long was added in git-1.5.5 - if describe_out is None: - raise NotThisMethod("'git describe' failed") - describe_out = describe_out.strip() - full_out = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) - if full_out is None: - raise NotThisMethod("'git rev-parse' failed") - full_out = full_out.strip() - - pieces = {} - pieces["long"] = full_out - pieces["short"] = full_out[:7] # maybe improved later - pieces["error"] = None - - # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] - # TAG might have hyphens. - git_describe = describe_out - - # look for -dirty suffix - dirty = git_describe.endswith("-dirty") - pieces["dirty"] = dirty - if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] - - # now we have TAG-NUM-gHEX or HEX - - if "-" in git_describe: - # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) - if not mo: - # unparseable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%s'" - % describe_out) - return pieces - - # tag - full_tag = mo.group(1) - if not full_tag.startswith(tag_prefix): - if verbose: - fmt = "tag '%s' doesn't start with prefix '%s'" - print(fmt % (full_tag, tag_prefix)) - pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" - % (full_tag, tag_prefix)) - return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] - - # distance: number of commits since tag - pieces["distance"] = int(mo.group(2)) - - # commit: short hex revision ID - pieces["short"] = mo.group(3) - - else: - # HEX: no tags - pieces["closest-tag"] = None - count_out = run_command(GITS, ["rev-list", "HEAD", "--count"], - cwd=root) - pieces["distance"] = int(count_out) # total number of commits - - return pieces - - -def do_vcs_install(manifest_in, versionfile_source, ipy): - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - files = [manifest_in, versionfile_source] - if ipy: - files.append(ipy) - try: - me = __file__ - if me.endswith(".pyc") or me.endswith(".pyo"): - me = os.path.splitext(me)[0] + ".py" - versioneer_file = os.path.relpath(me) - except NameError: - versioneer_file = "versioneer.py" - files.append(versioneer_file) - present = False - try: - f = open(".gitattributes", "r") - for line in f.readlines(): - if line.strip().startswith(versionfile_source): - if "export-subst" in line.strip().split()[1:]: - present = True - f.close() - except EnvironmentError: - pass - if not present: - f = open(".gitattributes", "a+") - f.write("%s export-subst\n" % versionfile_source) - f.close() - files.append(".gitattributes") - run_command(GITS, ["add", "--"] + files) - - -def versions_from_parentdir(parentdir_prefix, root, verbose): - # Source tarballs conventionally unpack into a directory that includes - # both the project name and a version string. - dirname = os.path.basename(root) - if not dirname.startswith(parentdir_prefix): - if verbose: - print("guessing rootdir is '%s', but '%s' doesn't start with " - "prefix '%s'" % (root, dirname, parentdir_prefix)) - raise NotThisMethod("rootdir doesn't start with parentdir_prefix") - return {"version": dirname[len(parentdir_prefix):], - "full-revisionid": None, - "dirty": False, "error": None} - -SHORT_VERSION_PY = """ -# This file was generated by 'versioneer.py' (0.15) from -# revision-control system data, or from the parent directory name of an -# unpacked source archive. Distribution tarballs contain a pre-generated copy -# of this file. - -import json -import sys - -version_json = ''' -%s -''' # END VERSION_JSON - - -def get_versions(): - return json.loads(version_json) -""" - - -def versions_from_file(filename): - try: - with open(filename) as f: - contents = f.read() - except EnvironmentError: - raise NotThisMethod("unable to read _version.py") - mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON", - contents, re.M | re.S) - if not mo: - raise NotThisMethod("no version_json in _version.py") - return json.loads(mo.group(1)) - - -def write_to_version_file(filename, versions): - os.unlink(filename) - contents = json.dumps(versions, sort_keys=True, - indent=1, separators=(",", ": ")) - with open(filename, "w") as f: - f.write(SHORT_VERSION_PY % contents) - - print("set %s to '%s'" % (filename, versions["version"])) - - -def plus_or_dot(pieces): - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces): - # now build up version string, with post-release "local version - # identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you - # get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty - - # exceptions: - # 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] - - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += plus_or_dot(pieces) - rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_pre(pieces): - # TAG[.post.devDISTANCE] . No -dirty - - # exceptions: - # 1: no tags. 0.post.devDISTANCE - - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += ".post.dev%d" % pieces["distance"] - else: - # exception #1 - rendered = "0.post.dev%d" % pieces["distance"] - return rendered - - -def render_pep440_post(pieces): - # TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that - # .dev0 sorts backwards (a dirty tree will appear "older" than the - # corresponding clean one), but you shouldn't be releasing software with - # -dirty anyways. - - # exceptions: - # 1: no tags. 0.postDISTANCE[.dev0] - - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%s" % pieces["short"] - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += "+g%s" % pieces["short"] - return rendered - - -def render_pep440_old(pieces): - # TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. - - # exceptions: - # 1: no tags. 0.postDISTANCE[.dev0] - - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - return rendered - - -def render_git_describe(pieces): - # TAG[-DISTANCE-gHEX][-dirty], like 'git describe --tags --dirty - # --always' - - # exceptions: - # 1: no tags. HEX[-dirty] (note: no 'g' prefix) - - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render_git_describe_long(pieces): - # TAG-DISTANCE-gHEX[-dirty], like 'git describe --tags --dirty - # --always -long'. The distance/hash is unconditional. - - # exceptions: - # 1: no tags. HEX[-dirty] (note: no 'g' prefix) - - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render(pieces, style): - if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"]} - - if not style or style == "default": - style = "pep440" # the default - - if style == "pep440": - rendered = render_pep440(pieces) - elif style == "pep440-pre": - rendered = render_pep440_pre(pieces) - elif style == "pep440-post": - rendered = render_pep440_post(pieces) - elif style == "pep440-old": - rendered = render_pep440_old(pieces) - elif style == "git-describe": - rendered = render_git_describe(pieces) - elif style == "git-describe-long": - rendered = render_git_describe_long(pieces) - else: - raise ValueError("unknown style '%s'" % style) - - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None} - - -class VersioneerBadRootError(Exception): - pass - - -def get_versions(verbose=False): - # returns dict with two keys: 'version' and 'full' - - if "versioneer" in sys.modules: - # see the discussion in cmdclass.py:get_cmdclass() - del sys.modules["versioneer"] - - root = get_root() - cfg = get_config_from_root(root) - - assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg" - handlers = HANDLERS.get(cfg.VCS) - assert handlers, "unrecognized VCS '%s'" % cfg.VCS - verbose = verbose or cfg.verbose - assert cfg.versionfile_source is not None, \ - "please set versioneer.versionfile_source" - assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" - - versionfile_abs = os.path.join(root, cfg.versionfile_source) - - # extract version from first of: _version.py, VCS command (e.g. 'git - # describe'), parentdir. This is meant to work for developers using a - # source checkout, for users of a tarball created by 'setup.py sdist', - # and for users of a tarball/zipball created by 'git archive' or github's - # download-from-tag feature or the equivalent in other VCSes. - - get_keywords_f = handlers.get("get_keywords") - from_keywords_f = handlers.get("keywords") - if get_keywords_f and from_keywords_f: - try: - keywords = get_keywords_f(versionfile_abs) - ver = from_keywords_f(keywords, cfg.tag_prefix, verbose) - if verbose: - print("got version from expanded keyword %s" % ver) - return ver - except NotThisMethod: - pass - - try: - ver = versions_from_file(versionfile_abs) - if verbose: - print("got version from file %s %s" % (versionfile_abs, ver)) - return ver - except NotThisMethod: - pass - - from_vcs_f = handlers.get("pieces_from_vcs") - if from_vcs_f: - try: - pieces = from_vcs_f(cfg.tag_prefix, root, verbose) - ver = render(pieces, cfg.style) - if verbose: - print("got version from VCS %s" % ver) - return ver - except NotThisMethod: - pass - - try: - if cfg.parentdir_prefix: - ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose) - if verbose: - print("got version from parentdir %s" % ver) - return ver - except NotThisMethod: - pass - - if verbose: - print("unable to compute version") - - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, "error": "unable to compute version"} - - -def get_version(): - return get_versions()["version"] - - -def get_cmdclass(): - if "versioneer" in sys.modules: - del sys.modules["versioneer"] - # this fixes the "python setup.py develop" case (also 'install' and - # 'easy_install .'), in which subdependencies of the main project are - # built (using setup.py bdist_egg) in the same python process. Assume - # a main project A and a dependency B, which use different versions - # of Versioneer. A's setup.py imports A's Versioneer, leaving it in - # sys.modules by the time B's setup.py is executed, causing B to run - # with the wrong versioneer. Setuptools wraps the sub-dep builds in a - # sandbox that restores sys.modules to it's pre-build state, so the - # parent is protected against the child's "import versioneer". By - # removing ourselves from sys.modules here, before the child build - # happens, we protect the child from the parent's versioneer too. - # Also see https://github.com/warner/python-versioneer/issues/52 - - cmds = {} - - # we add "version" to both distutils and setuptools - from distutils.core import Command - - class cmd_version(Command): - description = "report generated version string" - user_options = [] - boolean_options = [] - - def initialize_options(self): - pass - - def finalize_options(self): - pass - - def run(self): - vers = get_versions(verbose=True) - print("Version: %s" % vers["version"]) - print(" full-revisionid: %s" % vers.get("full-revisionid")) - print(" dirty: %s" % vers.get("dirty")) - if vers["error"]: - print(" error: %s" % vers["error"]) - cmds["version"] = cmd_version - - # we override "build_py" in both distutils and setuptools - # - # most invocation pathways end up running build_py: - # distutils/build -> build_py - # distutils/install -> distutils/build ->.. - # setuptools/bdist_wheel -> distutils/install ->.. - # setuptools/bdist_egg -> distutils/install_lib -> build_py - # setuptools/install -> bdist_egg ->.. - # setuptools/develop -> ? - - from distutils.command.build_py import build_py as _build_py - - class cmd_build_py(_build_py): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - _build_py.run(self) - # now locate _version.py in the new build/ directory and replace - # it with an updated value - if cfg.versionfile_build: - target_versionfile = os.path.join(self.build_lib, - cfg.versionfile_build) - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - cmds["build_py"] = cmd_build_py - - if "cx_Freeze" in sys.modules: # cx_freeze enabled? - from cx_Freeze.dist import build_exe as _build_exe - - class cmd_build_exe(_build_exe): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - target_versionfile = cfg.versionfile_source - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - - _build_exe.run(self) - os.unlink(target_versionfile) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % - {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) - cmds["build_exe"] = cmd_build_exe - del cmds["build_py"] - - # we override different "sdist" commands for both environments - if "setuptools" in sys.modules: - from setuptools.command.sdist import sdist as _sdist - else: - from distutils.command.sdist import sdist as _sdist - - class cmd_sdist(_sdist): - def run(self): - versions = get_versions() - self._versioneer_generated_versions = versions - # unless we update this, the command will keep using the old - # version - self.distribution.metadata.version = versions["version"] - return _sdist.run(self) - - def make_release_tree(self, base_dir, files): - root = get_root() - cfg = get_config_from_root(root) - _sdist.make_release_tree(self, base_dir, files) - # now locate _version.py in the new base_dir directory - # (remembering that it may be a hardlink) and replace it with an - # updated value - target_versionfile = os.path.join(base_dir, cfg.versionfile_source) - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, - self._versioneer_generated_versions) - cmds["sdist"] = cmd_sdist - - return cmds - - -CONFIG_ERROR = """ -setup.cfg is missing the necessary Versioneer configuration. You need -a section like: - - [versioneer] - VCS = git - style = pep440 - versionfile_source = src/myproject/_version.py - versionfile_build = myproject/_version.py - tag_prefix = "" - parentdir_prefix = myproject- - -You will also need to edit your setup.py to use the results: - - import versioneer - setup(version=versioneer.get_version(), - cmdclass=versioneer.get_cmdclass(), ...) - -Please read the docstring in ./versioneer.py for configuration instructions, -edit setup.cfg, and re-run the installer or 'python versioneer.py setup'. -""" - -SAMPLE_CONFIG = """ -# See the docstring in versioneer.py for instructions. Note that you must -# re-run 'versioneer.py setup' after changing this section, and commit the -# resulting files. - -[versioneer] -#VCS = git -#style = pep440 -#versionfile_source = -#versionfile_build = -#tag_prefix = -#parentdir_prefix = - -""" - -INIT_PY_SNIPPET = """ -from ._version import get_versions -__version__ = get_versions()['version'] -del get_versions -""" - - -def do_setup(): - root = get_root() - try: - cfg = get_config_from_root(root) - except (EnvironmentError, configparser.NoSectionError, - configparser.NoOptionError) as e: - if isinstance(e, (EnvironmentError, configparser.NoSectionError)): - print("Adding sample versioneer config to setup.cfg", - file=sys.stderr) - with open(os.path.join(root, "setup.cfg"), "a") as f: - f.write(SAMPLE_CONFIG) - print(CONFIG_ERROR, file=sys.stderr) - return 1 - - print(" creating %s" % cfg.versionfile_source) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) - - ipy = os.path.join(os.path.dirname(cfg.versionfile_source), - "__init__.py") - if os.path.exists(ipy): - try: - with open(ipy, "r") as f: - old = f.read() - except EnvironmentError: - old = "" - if INIT_PY_SNIPPET not in old: - print(" appending to %s" % ipy) - with open(ipy, "a") as f: - f.write(INIT_PY_SNIPPET) - else: - print(" %s unmodified" % ipy) - else: - print(" %s doesn't exist, ok" % ipy) - ipy = None - - # Make sure both the top-level "versioneer.py" and versionfile_source - # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so - # they'll be copied into source distributions. Pip won't be able to - # install the package without this. - manifest_in = os.path.join(root, "MANIFEST.in") - simple_includes = set() - try: - with open(manifest_in, "r") as f: - for line in f: - if line.startswith("include "): - for include in line.split()[1:]: - simple_includes.add(include) - except EnvironmentError: - pass - # That doesn't cover everything MANIFEST.in can do - # (http://docs.python.org/2/distutils/sourcedist.html#commands), so - # it might give some false negatives. Appending redundant 'include' - # lines is safe, though. - if "versioneer.py" not in simple_includes: - print(" appending 'versioneer.py' to MANIFEST.in") - with open(manifest_in, "a") as f: - f.write("include versioneer.py\n") - else: - print(" 'versioneer.py' already in MANIFEST.in") - if cfg.versionfile_source not in simple_includes: - print(" appending versionfile_source ('%s') to MANIFEST.in" % - cfg.versionfile_source) - with open(manifest_in, "a") as f: - f.write("include %s\n" % cfg.versionfile_source) - else: - print(" versionfile_source already in MANIFEST.in") - - # Make VCS-specific changes. For git, this means creating/changing - # .gitattributes to mark _version.py for export-time keyword - # substitution. - do_vcs_install(manifest_in, cfg.versionfile_source, ipy) - return 0 - - -def scan_setup_py(): - found = set() - setters = False - errors = 0 - with open("setup.py", "r") as f: - for line in f.readlines(): - if "import versioneer" in line: - found.add("import") - if "versioneer.get_cmdclass()" in line: - found.add("cmdclass") - if "versioneer.get_version()" in line: - found.add("get_version") - if "versioneer.VCS" in line: - setters = True - if "versioneer.versionfile_source" in line: - setters = True - if len(found) != 3: - print("") - print("Your setup.py appears to be missing some important items") - print("(but I might be wrong). Please make sure it has something") - print("roughly like the following:") - print("") - print(" import versioneer") - print(" setup( version=versioneer.get_version(),") - print(" cmdclass=versioneer.get_cmdclass(), ...)") - print("") - errors += 1 - if setters: - print("You should remove lines like 'versioneer.VCS = ' and") - print("'versioneer.versionfile_source = ' . This configuration") - print("now lives in setup.cfg, and should be removed from setup.py") - print("") - errors += 1 - return errors - -if __name__ == "__main__": - cmd = sys.argv[1] - if cmd == "setup": - errors = do_setup() - errors += scan_setup_py() - if errors: - sys.exit(1)