montage-wrapper-0.9.8/0000755000077000000240000000000012405342415014556 5ustar tomstaff00000000000000montage-wrapper-0.9.8/ah_bootstrap.py0000644000077000000240000006524412405341502017624 0ustar tomstaff00000000000000""" This bootstrap module contains code for ensuring that the astropy_helpers package will be importable by the time the setup.py script runs. It also includes some workarounds to ensure that a recent-enough version of setuptools is being used for the installation. This module should be the first thing imported in the setup.py of distributions that make use of the utilities in astropy_helpers. If the distribution ships with its own copy of astropy_helpers, this module will first attempt to import from the shipped copy. However, it will also check PyPI to see if there are any bug-fix releases on top of the current version that may be useful to get past platform-specific bugs that have been fixed. When running setup.py, use the ``--offline`` command-line option to disable the auto-upgrade checks. When this module is imported or otherwise executed it automatically calls a main function that attempts to read the project's setup.cfg file, which it checks for a configuration section called ``[ah_bootstrap]`` the presences of that section, and options therein, determine the next step taken: If it contains an option called ``auto_use`` with a value of ``True``, it will automatically call the main function of this module called `use_astropy_helpers` (see that function's docstring for full details). Otherwise no further action is taken (however, ``ah_bootstrap.use_astropy_helpers`` may be called manually from within the setup.py script). Additional options in the ``[ah_boostrap]`` section of setup.cfg have the same names as the arguments to `use_astropy_helpers`, and can be used to configure the bootstrap script when ``auto_use = True``. See https://github.com/astropy/astropy-helpers for more details, and for the latest version of this module. """ import contextlib import errno import imp import io import locale import os import re import subprocess as sp import sys try: from ConfigParser import ConfigParser, RawConfigParser except ImportError: from configparser import ConfigParser, RawConfigParser if sys.version_info[0] < 3: _str_types = (str, unicode) _text_type = unicode PY3 = False else: _str_types = (str, bytes) _text_type = str PY3 = True # Some pre-setuptools checks to ensure that either distribute or setuptools >= # 0.7 is used (over pre-distribute setuptools) if it is available on the path; # otherwise the latest setuptools will be downloaded and bootstrapped with # ``ez_setup.py``. This used to be included in a separate file called # setuptools_bootstrap.py; but it was combined into ah_bootstrap.py try: import pkg_resources _setuptools_req = pkg_resources.Requirement.parse('setuptools>=0.7') # This may raise a DistributionNotFound in which case no version of # setuptools or distribute is properly installed _setuptools = pkg_resources.get_distribution('setuptools') if _setuptools not in _setuptools_req: # Older version of setuptools; check if we have distribute; again if # this results in DistributionNotFound we want to give up _distribute = pkg_resources.get_distribution('distribute') if _setuptools != _distribute: # It's possible on some pathological systems to have an old version # of setuptools and distribute on sys.path simultaneously; make # sure distribute is the one that's used sys.path.insert(1, _distribute.location) _distribute.activate() imp.reload(pkg_resources) except: # There are several types of exceptions that can occur here; if all else # fails bootstrap and use the bootstrapped version from ez_setup import use_setuptools use_setuptools() from distutils import log from distutils.debug import DEBUG # In case it didn't successfully import before the ez_setup checks import pkg_resources from setuptools import Distribution from setuptools.package_index import PackageIndex from setuptools.sandbox import run_setup # TODO: Maybe enable checking for a specific version of astropy_helpers? DIST_NAME = 'astropy-helpers' PACKAGE_NAME = 'astropy_helpers' # Defaults for other options DOWNLOAD_IF_NEEDED = True INDEX_URL = 'https://pypi.python.org/simple' USE_GIT = True AUTO_UPGRADE = True def use_astropy_helpers(path=None, download_if_needed=None, index_url=None, use_git=None, auto_upgrade=None): """ Ensure that the `astropy_helpers` module is available and is importable. This supports automatic submodule initialization if astropy_helpers is included in a project as a git submodule, or will download it from PyPI if necessary. Parameters ---------- path : str or None, optional A filesystem path relative to the root of the project's source code that should be added to `sys.path` so that `astropy_helpers` can be imported from that path. If the path is a git submodule it will automatically be initialzed and/or updated. The path may also be to a ``.tar.gz`` archive of the astropy_helpers source distribution. In this case the archive is automatically unpacked and made temporarily available on `sys.path` as a ``.egg`` archive. If `None` skip straight to downloading. download_if_needed : bool, optional If the provided filesystem path is not found an attempt will be made to download astropy_helpers from PyPI. It will then be made temporarily available on `sys.path` as a ``.egg`` archive (using the ``setup_requires`` feature of setuptools. If the ``--offline`` option is given at the command line the value of this argument is overridden to `False`. index_url : str, optional If provided, use a different URL for the Python package index than the main PyPI server. use_git : bool, optional If `False` no git commands will be used--this effectively disables support for git submodules. If the ``--no-git`` option is given at the command line the value of this argument is overridden to `False`. auto_upgrade : bool, optional By default, when installing a package from a non-development source distribution ah_boostrap will try to automatically check for patch releases to astropy-helpers on PyPI and use the patched version over any bundled versions. Setting this to `False` will disable that functionality. If the ``--offline`` option is given at the command line the value of this argument is overridden to `False`. """ # True by default, unless the --offline option was provided on the command # line if '--offline' in sys.argv: download_if_needed = False auto_upgrade = False offline = True sys.argv.remove('--offline') else: offline = False if '--no-git' in sys.argv: use_git = False sys.argv.remove('--no-git') if path is None: path = PACKAGE_NAME if download_if_needed is None: download_if_needed = DOWNLOAD_IF_NEEDED if index_url is None: index_url = INDEX_URL if use_git is None: use_git = USE_GIT if auto_upgrade is None: auto_upgrade = AUTO_UPGRADE # Declared as False by default--later we check if astropy-helpers can be # upgraded from PyPI, but only if not using a source distribution (as in # the case of import from a git submodule) is_submodule = False if not isinstance(path, _str_types): if path is not None: raise TypeError('path must be a string or None') if not download_if_needed: log.debug('a path was not given and download from PyPI was not ' 'allowed so this is effectively a no-op') return elif not os.path.exists(path) or os.path.isdir(path): # Even if the given path does not exist on the filesystem, if it *is* a # submodule, `git submodule init` will create it is_submodule = _check_submodule(path, use_git=use_git, offline=offline) if is_submodule or os.path.isdir(path): log.info( 'Attempting to import astropy_helpers from {0} {1!r}'.format( 'submodule' if is_submodule else 'directory', path)) dist = _directory_import(path) else: dist = None if dist is None: msg = ( 'The requested path {0!r} for importing {1} does not ' 'exist, or does not contain a copy of the {1} package. ' 'Attempting download instead.'.format(path, PACKAGE_NAME)) if download_if_needed: log.warn(msg) else: raise _AHBootstrapSystemExit(msg) elif os.path.isfile(path): # Handle importing from a source archive; this also uses setup_requires # but points easy_install directly to the source archive try: dist = _do_download(find_links=[path]) except Exception as e: if download_if_needed: log.warn('{0}\nWill attempt to download astropy_helpers from ' 'PyPI instead.'.format(str(e))) dist = None else: raise _AHBootstrapSystemExit(e.args[0]) else: msg = ('{0!r} is not a valid file or directory (it could be a ' 'symlink?)'.format(path)) if download_if_needed: log.warn(msg) dist = None else: raise _AHBootstrapSystemExit(msg) if dist is not None and auto_upgrade and not is_submodule: # A version of astropy-helpers was found on the available path, but # check to see if a bugfix release is available on PyPI upgrade = _do_upgrade(dist, index_url) if upgrade is not None: dist = upgrade elif dist is None: # Last resort--go ahead and try to download the latest version from # PyPI try: if download_if_needed: log.warn( "Downloading astropy_helpers; run setup.py with the " "--offline option to force offline installation.") dist = _do_download(index_url=index_url) else: raise _AHBootstrapSystemExit( "No source for the astropy_helpers package; " "astropy_helpers must be available as a prerequisite to " "installing this package.") except Exception as e: if DEBUG: raise else: raise _AHBootstrapSystemExit(e.args[0]) if dist is not None: # Otherwise we found a version of astropy-helpers so we're done # Just activate the found distribibution on sys.path--if we did a # download this usually happens automatically but do it again just to # be sure # Note: Adding the dist to the global working set also activates it by # default pkg_resources.working_set.add(dist) def _do_download(version='', find_links=None, index_url=None): try: if find_links: allow_hosts = '' index_url = None else: allow_hosts = None # Annoyingly, setuptools will not handle other arguments to # Distribution (such as options) before handling setup_requires, so it # is not straightfoward to programmatically augment the arguments which # are passed to easy_install class _Distribution(Distribution): def get_option_dict(self, command_name): opts = Distribution.get_option_dict(self, command_name) if command_name == 'easy_install': if find_links is not None: opts['find_links'] = ('setup script', find_links) if index_url is not None: opts['index_url'] = ('setup script', index_url) if allow_hosts is not None: opts['allow_hosts'] = ('setup script', allow_hosts) return opts if version: req = '{0}=={1}'.format(DIST_NAME, version) else: req = DIST_NAME attrs = {'setup_requires': [req]} if DEBUG: dist = _Distribution(attrs=attrs) else: with _silence(): dist = _Distribution(attrs=attrs) # If the setup_requires succeeded it will have added the new dist to # the main working_set return pkg_resources.working_set.by_key.get(DIST_NAME) except Exception as e: if DEBUG: raise msg = 'Error retrieving astropy helpers from {0}:\n{1}' if find_links: source = find_links[0] elif index_url: source = index_url else: source = 'PyPI' raise Exception(msg.format(source, repr(e))) def _do_upgrade(dist, index_url): # Build up a requirement for a higher bugfix release but a lower minor # release (so API compatibility is guaranteed) # sketchy version parsing--maybe come up with something a bit more # robust for this major, minor = (int(part) for part in dist.parsed_version[:2]) next_minor = '.'.join([str(major), str(minor + 1), '0']) req = pkg_resources.Requirement.parse( '{0}>{1},<{2}'.format(DIST_NAME, dist.version, next_minor)) package_index = PackageIndex(index_url=index_url) upgrade = package_index.obtain(req) if upgrade is not None: return _do_download(version=upgrade.version, index_url=index_url) def _directory_import(path): """ Import astropy_helpers from the given path, which will be added to sys.path. Must return True if the import succeeded, and False otherwise. """ # Return True on success, False on failure but download is allowed, and # otherwise raise SystemExit path = os.path.abspath(path) # Use an empty WorkingSet rather than the man pkg_resources.working_set, # since on older versions of setuptools this will invoke a VersionConflict # when trying to install an upgrade ws = pkg_resources.WorkingSet([]) ws.add_entry(path) dist = ws.by_key.get(DIST_NAME) if dist is None: # We didn't find an egg-info/dist-info in the given path, but if a # setup.py exists we can generate it setup_py = os.path.join(path, 'setup.py') if os.path.isfile(setup_py): with _silence(): run_setup(os.path.join(path, 'setup.py'), ['egg_info']) for dist in pkg_resources.find_distributions(path, True): # There should be only one... return dist return dist def _check_submodule(path, use_git=True, offline=False): """ Check if the given path is a git submodule. See the docstrings for ``_check_submodule_using_git`` and ``_check_submodule_no_git`` for futher details. """ if use_git: return _check_submodule_using_git(path, offline) else: return _check_submodule_no_git(path) def _check_submodule_using_git(path, offline): """ Check if the given path is a git submodule. If so, attempt to initialize and/or update the submodule if needed. This function makes calls to the ``git`` command in subprocesses. The ``_check_submodule_no_git`` option uses pure Python to check if the given path looks like a git submodule, but it cannot perform updates. """ if PY3 and not isinstance(path, _text_type): fs_encoding = sys.getfilesystemencoding() path = path.decode(fs_encoding) try: p = sp.Popen(['git', 'submodule', 'status', '--', path], stdout=sp.PIPE, stderr=sp.PIPE) stdout, stderr = p.communicate() except OSError as e: if DEBUG: raise if e.errno == errno.ENOENT: # The git command simply wasn't found; this is most likely the # case on user systems that don't have git and are simply # trying to install the package from PyPI or a source # distribution. Silently ignore this case and simply don't try # to use submodules return False else: raise _AHBoostrapSystemExit( 'An unexpected error occurred when running the ' '`git submodule status` command:\n{0}'.format(str(e))) # Can fail of the default locale is not configured properly. See # https://github.com/astropy/astropy/issues/2749. For the purposes under # consideration 'latin1' is an acceptable fallback. try: stdio_encoding = locale.getdefaultlocale()[1] or 'latin1' except ValueError: # Due to an OSX oddity locale.getdefaultlocale() can also crash # depending on the user's locale/language settings. See: # http://bugs.python.org/issue18378 stdio_encoding = 'latin1' if p.returncode != 0 or stderr: # Unfortunately the return code alone cannot be relied on, as # earlier versions of git returned 0 even if the requested submodule # does not exist stderr = stderr.decode(stdio_encoding) # This is a warning that occurs in perl (from running git submodule) # which only occurs with a malformatted locale setting which can # happen sometimes on OSX. See again # https://github.com/astropy/astropy/issues/2749 perl_warning = ('perl: warning: Falling back to the standard locale ' '("C").') if not stderr.strip().endswith(perl_warning): # Some other uknown error condition occurred log.warn('git submodule command failed ' 'unexpectedly:\n{0}'.format(stderr)) return False stdout = stdout.decode(stdio_encoding) # The stdout should only contain one line--the status of the # requested submodule m = _git_submodule_status_re.match(stdout) if m: # Yes, the path *is* a git submodule _update_submodule(m.group('submodule'), m.group('status'), offline) return True else: log.warn( 'Unexpected output from `git submodule status`:\n{0}\n' 'Will attempt import from {1!r} regardless.'.format( stdout, path)) return False def _check_submodule_no_git(path): """ Like ``_check_submodule_using_git``, but simply parses the .gitmodules file to determine if the supplied path is a git submodule, and does not exec any subprocesses. This can only determine if a path is a submodule--it does not perform updates, etc. This function may need to be updated if the format of the .gitmodules file is changed between git versions. """ gitmodules_path = os.path.abspath('.gitmodules') if not os.path.isfile(gitmodules_path): return False # This is a minimal reader for gitconfig-style files. It handles a few of # the quirks that make gitconfig files incompatible with ConfigParser-style # files, but does not support the full gitconfig syntaix (just enough # needed to read a .gitmodules file). gitmodules_fileobj = io.StringIO() # Must use io.open for cross-Python-compatible behavior wrt unicode with io.open(gitmodules_path) as f: for line in f: # gitconfig files are more flexible with leading whitespace; just # go ahead and remove it line = line.lstrip() # comments can start with either # or ; if line and line[0] in (':', ';'): continue gitmodules_fileobj.write(line) gitmodules_fileobj.seek(0) cfg = RawConfigParser() try: cfg.readfp(gitmodules_fileobj) except Exception as exc: log.warn('Malformatted .gitmodules file: {0}\n' '{1} cannot be assumed to be a git submodule.'.format( exc, path)) return False for section in cfg.sections(): if not cfg.has_option(section, 'path'): continue submodule_path = cfg.get(section, 'path').rstrip(os.sep) if submodule_path == path.rstrip(os.sep): return True return False def _update_submodule(submodule, status, offline): if status == ' ': # The submodule is up to date; no action necessary return elif status == '-': if offline: raise _AHBootstrapSystemExit( "Cannot initialize the {0} submodule in --offline mode; this " "requires being able to clone the submodule from an online " "repository.".format(submodule)) cmd = ['update', '--init'] action = 'Initializing' elif status == '+': cmd = ['update'] action = 'Updating' if offline: cmd.append('--no-fetch') elif status == 'U': raise _AHBoostrapSystemExit( 'Error: Submodule {0} contains unresolved merge conflicts. ' 'Please complete or abandon any changes in the submodule so that ' 'it is in a usable state, then try again.'.format(submodule)) else: log.warn('Unknown status {0!r} for git submodule {1!r}. Will ' 'attempt to use the submodule as-is, but try to ensure ' 'that the submodule is in a clean state and contains no ' 'conflicts or errors.\n{2}'.format(status, submodule, _err_help_msg)) return err_msg = None cmd = ['git', 'submodule'] + cmd + ['--', submodule] log.warn('{0} {1} submodule with: `{2}`'.format( action, submodule, ' '.join(cmd))) try: p = sp.Popen(cmd, stdout=sp.PIPE, stderr=sp.PIPE) stdout, stderr = p.communicate() except OSError as e: err_msg = str(e) else: if p.returncode != 0: stderr_encoding = locale.getdefaultlocale()[1] err_msg = stderr.decode(stderr_encoding) if err_msg: log.warn('An unexpected error occurred updating the git submodule ' '{0!r}:\n{1}\n{2}'.format(submodule, err_msg, _err_help_msg)) class _DummyFile(object): """A noop writeable object.""" errors = '' # Required for Python 3.x encoding = 'utf-8' def write(self, s): pass def flush(self): pass @contextlib.contextmanager def _silence(): """A context manager that silences sys.stdout and sys.stderr.""" old_stdout = sys.stdout old_stderr = sys.stderr sys.stdout = _DummyFile() sys.stderr = _DummyFile() exception_occurred = False try: yield except: exception_occurred = True # Go ahead and clean up so that exception handling can work normally sys.stdout = old_stdout sys.stderr = old_stderr raise if not exception_occurred: sys.stdout = old_stdout sys.stderr = old_stderr _err_help_msg = """ If the problem persists consider installing astropy_helpers manually using pip (`pip install astropy_helpers`) or by manually downloading the source archive, extracting it, and installing by running `python setup.py install` from the root of the extracted source code. """ class _AHBootstrapSystemExit(SystemExit): def __init__(self, *args): if not args: msg = 'An unknown problem occurred bootstrapping astropy_helpers.' else: msg = args[0] msg += '\n' + _err_help_msg super(_AHBootstrapSystemExit, self).__init__(msg, *args[1:]) if sys.version_info[:2] < (2, 7): # In Python 2.6 the distutils log does not log warnings, errors, etc. to # stderr so we have to wrap it to ensure consistency at least in this # module import distutils class log(object): def __getattr__(self, attr): return getattr(distutils.log, attr) def warn(self, msg, *args): self._log_to_stderr(distutils.log.WARN, msg, *args) def error(self, msg): self._log_to_stderr(distutils.log.ERROR, msg, *args) def fatal(self, msg): self._log_to_stderr(distutils.log.FATAL, msg, *args) def log(self, level, msg, *args): if level in (distutils.log.WARN, distutils.log.ERROR, distutils.log.FATAL): self._log_to_stderr(level, msg, *args) else: distutils.log.log(level, msg, *args) def _log_to_stderr(self, level, msg, *args): # This is the only truly 'public' way to get the current threshold # of the log current_threshold = distutils.log.set_threshold(distutils.log.WARN) distutils.log.set_threshold(current_threshold) if level >= current_threshold: if args: msg = msg % args sys.stderr.write('%s\n' % msg) sys.stderr.flush() log = log() # Output of `git submodule status` is as follows: # # 1: Status indicator: '-' for submodule is uninitialized, '+' if submodule is # initialized but is not at the commit currently indicated in .gitmodules (and # thus needs to be updated), or 'U' if the submodule is in an unstable state # (i.e. has merge conflicts) # # 2. SHA-1 hash of the current commit of the submodule (we don't really need # this information but it's useful for checking that the output is correct) # # 3. The output of `git describe` for the submodule's current commit hash (this # includes for example what branches the commit is on) but only if the # submodule is initialized. We ignore this information for now _git_submodule_status_re = re.compile( '^(?P[+-U ])(?P[0-9a-f]{40}) (?P\S+)( .*)?$') # Implement the auto-use feature; this allows use_astropy_helpers() to be used # at import-time automatically so long as the correct options are specified in # setup.cfg _CFG_OPTIONS = [('auto_use', bool), ('path', str), ('download_if_needed', bool), ('index_url', str), ('use_git', bool), ('auto_upgrade', bool)] def _main(): if not os.path.exists('setup.cfg'): return cfg = ConfigParser() try: cfg.read('setup.cfg') except Exception as e: if DEBUG: raise log.error( "Error reading setup.cfg: {0!r}\nastropy_helpers will not be " "automatically bootstrapped and package installation may fail." "\n{1}".format(e, _err_help_msg)) return if not cfg.has_section('ah_bootstrap'): return kwargs = {} for option, type_ in _CFG_OPTIONS: if not cfg.has_option('ah_bootstrap', option): continue if type_ is bool: value = cfg.getboolean('ah_bootstrap', option) else: value = cfg.get('ah_bootstrap', option) kwargs[option] = value if kwargs.pop('auto_use', False): use_astropy_helpers(**kwargs) _main() montage-wrapper-0.9.8/astropy_helpers/0000755000077000000240000000000012405342415020001 5ustar tomstaff00000000000000montage-wrapper-0.9.8/astropy_helpers/.coveragerc0000644000077000000240000000063312333217235022125 0ustar tomstaff00000000000000[run] source = astropy_helpers ah_bootstrap omit = astropy_helpers/tests* [report] exclude_lines = # Have to re-enable the standard pragma pragma: no cover # Don't complain about packages we have installed except ImportError # Don't complain if tests don't hit assertions raise AssertionError raise NotImplementedError # Don't complain about script hooks def main\(.*\): montage-wrapper-0.9.8/astropy_helpers/.travis.yml0000644000077000000240000000167712405252770022131 0ustar tomstaff00000000000000language: python python: - 2.6 - 2.7 - 3.2 - 3.3 - 3.4 env: global: - PIP_WHEEL_COMMAND="pip install --use-wheel" before_install: # Use utf8 encoding. Should be default, but this is insurance against # future changes - export PYTHONIOENCODING=UTF8 # Install the pip that supports wheel - pip install setuptools --upgrade - pip install pip --upgrade - pip install wheel install: - $PIP_WHEEL_COMMAND "pytest<2.6" - $PIP_WHEEL_COMMAND "--upgrade" "py" - $PIP_WHEEL_COMMAND "Jinja2<2.7" - $PIP_WHEEL_COMMAND "Sphinx" - $PIP_WHEEL_COMMAND "pytest-cov" - $PIP_WHEEL_COMMAND "coveralls" - $PIP_WHEEL_COMMAND "Cython" before_script: # Some of the tests use git commands that require a user to be configured - git config --global user.name "A U Thor" - git config --global user.email "author@example.com" script: - py.test after_success: - coveralls montage-wrapper-0.9.8/astropy_helpers/ah_bootstrap.py0000644000077000000240000007617012405252770023057 0ustar tomstaff00000000000000""" This bootstrap module contains code for ensuring that the astropy_helpers package will be importable by the time the setup.py script runs. It also includes some workarounds to ensure that a recent-enough version of setuptools is being used for the installation. This module should be the first thing imported in the setup.py of distributions that make use of the utilities in astropy_helpers. If the distribution ships with its own copy of astropy_helpers, this module will first attempt to import from the shipped copy. However, it will also check PyPI to see if there are any bug-fix releases on top of the current version that may be useful to get past platform-specific bugs that have been fixed. When running setup.py, use the ``--offline`` command-line option to disable the auto-upgrade checks. When this module is imported or otherwise executed it automatically calls a main function that attempts to read the project's setup.cfg file, which it checks for a configuration section called ``[ah_bootstrap]`` the presences of that section, and options therein, determine the next step taken: If it contains an option called ``auto_use`` with a value of ``True``, it will automatically call the main function of this module called `use_astropy_helpers` (see that function's docstring for full details). Otherwise no further action is taken (however, ``ah_bootstrap.use_astropy_helpers`` may be called manually from within the setup.py script). Additional options in the ``[ah_boostrap]`` section of setup.cfg have the same names as the arguments to `use_astropy_helpers`, and can be used to configure the bootstrap script when ``auto_use = True``. See https://github.com/astropy/astropy-helpers for more details, and for the latest version of this module. """ import contextlib import errno import imp import io import locale import os import re import subprocess as sp import sys try: from ConfigParser import ConfigParser, RawConfigParser except ImportError: from configparser import ConfigParser, RawConfigParser if sys.version_info[0] < 3: _str_types = (str, unicode) _text_type = unicode PY3 = False else: _str_types = (str, bytes) _text_type = str PY3 = True # Some pre-setuptools checks to ensure that either distribute or setuptools >= # 0.7 is used (over pre-distribute setuptools) if it is available on the path; # otherwise the latest setuptools will be downloaded and bootstrapped with # ``ez_setup.py``. This used to be included in a separate file called # setuptools_bootstrap.py; but it was combined into ah_bootstrap.py try: import pkg_resources _setuptools_req = pkg_resources.Requirement.parse('setuptools>=0.7') # This may raise a DistributionNotFound in which case no version of # setuptools or distribute is properly installed _setuptools = pkg_resources.get_distribution('setuptools') if _setuptools not in _setuptools_req: # Older version of setuptools; check if we have distribute; again if # this results in DistributionNotFound we want to give up _distribute = pkg_resources.get_distribution('distribute') if _setuptools != _distribute: # It's possible on some pathological systems to have an old version # of setuptools and distribute on sys.path simultaneously; make # sure distribute is the one that's used sys.path.insert(1, _distribute.location) _distribute.activate() imp.reload(pkg_resources) except: # There are several types of exceptions that can occur here; if all else # fails bootstrap and use the bootstrapped version from ez_setup import use_setuptools use_setuptools() from distutils import log from distutils.debug import DEBUG # In case it didn't successfully import before the ez_setup checks import pkg_resources from setuptools import Distribution from setuptools.package_index import PackageIndex from setuptools.sandbox import run_setup # TODO: Maybe enable checking for a specific version of astropy_helpers? DIST_NAME = 'astropy-helpers' PACKAGE_NAME = 'astropy_helpers' # Defaults for other options DOWNLOAD_IF_NEEDED = True INDEX_URL = 'https://pypi.python.org/simple' USE_GIT = True OFFLINE = False AUTO_UPGRADE = True class _Bootstrapper(object): """ Bootstrapper implementation. See ``use_astropy_helpers`` for parameter documentation. """ def __init__(self, path=None, index_url=None, use_git=None, offline=None, download_if_needed=None, auto_upgrade=None): if path is None: path = PACKAGE_NAME if not (isinstance(path, _str_types) or path is False): raise TypeError('path must be a string or False') if PY3 and not isinstance(path, _text_type): fs_encoding = sys.getfilesystemencoding() path = path.decode(fs_encoding) # path to unicode self.path = path # Set other option attirbutes, using defaults where necessary self.index_url = index_url if index_url is not None else INDEX_URL self.offline = offline if offline is not None else OFFLINE # If offline=True, override download and auto-upgrade if self.offline: download_if_needed = False auto_upgrade = False self.download = (download_if_needed if download_if_needed is not None else DOWNLOAD_IF_NEEDED) self.auto_upgrade = (auto_upgrade if auto_upgrade is not None else AUTO_UPGRADE) self.use_git = use_git if use_git is not None else USE_GIT # Declared as False by default--later we check if astropy-helpers can be # upgraded from PyPI, but only if not using a source distribution (as in # the case of import from a git submodule) self.is_submodule = False @classmethod def main(cls, args=None): if args is None: args = sys.argv[1:] config = cls.parse_config() config.update(cls.parse_command_line(args)) auto_use = config.pop('auto_use', False) if auto_use: bootstrapper = cls(**config) bootstrapper.run() return config @classmethod def parse_config(cls): cfg_options = [('auto_use', bool), ('path', str), ('download_if_needed', bool), ('index_url', str), ('use_git', bool), ('auto_upgrade', bool)] if not os.path.exists('setup.cfg'): return {} cfg = ConfigParser() try: cfg.read('setup.cfg') except Exception as e: if DEBUG: raise log.error( "Error reading setup.cfg: {0!r}\n{1} will not be " "automatically bootstrapped and package installation may fail." "\n{2}".format(e, PACKAGE_NAME, _err_help_msg)) return {} if not cfg.has_section('ah_bootstrap'): return {} config = {} for option, type_ in cfg_options: if not cfg.has_option('ah_bootstrap', option): continue if type_ is bool: value = cfg.getboolean('ah_bootstrap', option) else: value = cfg.get('ah_bootstrap', option) config[option] = value return config @classmethod def parse_command_line(cls, args=None): if args is None: args = sys.argv[1:] config = {} # For now we just pop recognized ah_bootstrap options out of the # arg list. This is imperfect; in the unlikely case that a setup.py # custom command or even custom Distribution class defines an argument # of the same name then we will break that. However there's a catch22 # here that we can't just do full argument parsing right here, because # we don't yet know *how* to parse all possible command-line arguments. if '--no-git' in args: config['use_git'] = False args.remove('--no-git') if '--offline' in args: config['offline'] = True args.remove('--offline') return config def run(self): strategies = ['local_directory', 'local_file', 'index'] dist = None # Check to see if the path is a submodule self.is_submodule = self._check_submodule() for strategy in strategies: method = getattr(self, 'get_{0}_dist'.format(strategy)) dist = method() if dist is not None: break else: raise _AHBootstrapSystemExit( "No source found for the {0!r} package; {0} must be " "available and importable as a prerequisite to building " "or installing this package.".format(PACKAGE_NAME)) # Otherwise we found a version of astropy-helpers, so we're done # Just active the found distribution on sys.path--if we did a # download this usually happens automatically but it doesn't hurt to # do it again # Note: Adding the dist to the global working set also activates it # (makes it importable on sys.path) by default pkg_resources.working_set.add(dist) def get_local_directory_dist(self): """ Handle importing a vendored package from a subdirectory of the source distribution. """ if not os.path.isdir(self.path): return log.info('Attempting to import astropy_helpers from {0} {1!r}'.format( 'submodule' if self.is_submodule else 'directory', self.path)) dist = self._directory_import() if dist is None: log.warn( 'The requested path {0!r} for importing {1} does not ' 'exist, or does not contain a copy of the {1} ' 'package.'.format(self.path, PACKAGE_NAME)) elif self.auto_upgrade and not self.is_submodule: # A version of astropy-helpers was found on the available path, but # check to see if a bugfix release is available on PyPI upgrade = self._do_upgrade(dist) if upgrade is not None: dist = upgrade return dist def get_local_file_dist(self): """ Handle importing from a source archive; this also uses setup_requires but points easy_install directly to the source archive. """ if not os.path.isfile(self.path): return log.info('Attempting to unpack and import astropy_helpers from ' '{0!r}'.format(self.path)) try: dist = self._do_download(find_links=[self.path]) except Exception as e: if DEBUG: raise log.warn( 'Failed to import {0} from the specified archive {1!r}: ' '{2}'.format(PACKAGE_NAME, self.path, str(e))) dist = None if dist is not None and self.auto_upgrade: # A version of astropy-helpers was found on the available path, but # check to see if a bugfix release is available on PyPI upgrade = self._do_upgrade(dist) if upgrade is not None: dist = upgrade return dist def get_index_dist(self): if not self.download: log.warn('Downloading {0!r} disabled.'.format(DIST_NAME)) return False log.warn( "Downloading {0!r}; run setup.py with the --offline option to " "force offline installation.".format(DIST_NAME)) try: dist = self._do_download() except Exception as e: if DEBUG: raise log.warn( 'Failed to download and/or install {0!r} from {1!r}:\n' '{2}'.format(DIST_NAME, self.index_url, str(e))) dist = None # No need to run auto-upgrade here since we've already presumably # gotten the most up-to-date version from the package index return dist def _directory_import(self): """ Import astropy_helpers from the given path, which will be added to sys.path. Must return True if the import succeeded, and False otherwise. """ # Return True on success, False on failure but download is allowed, and # otherwise raise SystemExit path = os.path.abspath(self.path) # Use an empty WorkingSet rather than the man # pkg_resources.working_set, since on older versions of setuptools this # will invoke a VersionConflict when trying to install an upgrade ws = pkg_resources.WorkingSet([]) ws.add_entry(path) dist = ws.by_key.get(DIST_NAME) if dist is None: # We didn't find an egg-info/dist-info in the given path, but if a # setup.py exists we can generate it setup_py = os.path.join(path, 'setup.py') if os.path.isfile(setup_py): with _silence(): run_setup(os.path.join(path, 'setup.py'), ['egg_info']) for dist in pkg_resources.find_distributions(path, True): # There should be only one... return dist return dist def _do_download(self, version='', find_links=None): if find_links: allow_hosts = '' index_url = None else: allow_hosts = None index_url = self.index_url # Annoyingly, setuptools will not handle other arguments to # Distribution (such as options) before handling setup_requires, so it # is not straightfoward to programmatically augment the arguments which # are passed to easy_install class _Distribution(Distribution): def get_option_dict(self, command_name): opts = Distribution.get_option_dict(self, command_name) if command_name == 'easy_install': if find_links is not None: opts['find_links'] = ('setup script', find_links) if index_url is not None: opts['index_url'] = ('setup script', index_url) if allow_hosts is not None: opts['allow_hosts'] = ('setup script', allow_hosts) return opts if version: req = '{0}=={1}'.format(DIST_NAME, version) else: req = DIST_NAME attrs = {'setup_requires': [req]} try: if DEBUG: _Distribution(attrs=attrs) else: with _silence(): _Distribution(attrs=attrs) # If the setup_requires succeeded it will have added the new dist to # the main working_set return pkg_resources.working_set.by_key.get(DIST_NAME) except Exception as e: if DEBUG: raise msg = 'Error retrieving {0} from {1}:\n{2}' if find_links: source = find_links[0] elif index_url != INDEX_URL: source = index_url else: source = 'PyPI' raise Exception(msg.format(DIST_NAME, source, repr(e))) def _do_upgrade(self, dist): # Build up a requirement for a higher bugfix release but a lower minor # release (so API compatibility is guaranteed) # sketchy version parsing--maybe come up with something a bit more # robust for this major, minor = (int(part) for part in dist.parsed_version[:2]) next_minor = '.'.join([str(major), str(minor + 1), '0']) req = pkg_resources.Requirement.parse( '{0}>{1},<{2}'.format(DIST_NAME, dist.version, next_minor)) package_index = PackageIndex(index_url=self.index_url) upgrade = package_index.obtain(req) if upgrade is not None: return self._do_download(version=upgrade.version) def _check_submodule(self): """ Check if the given path is a git submodule. See the docstrings for ``_check_submodule_using_git`` and ``_check_submodule_no_git`` for futher details. """ if (self.path is None or (os.path.exists(self.path) and not os.path.isdir(self.path))): return False if self.use_git: return self._check_submodule_using_git() else: return self._check_submodule_no_git() def _check_submodule_using_git(self): """ Check if the given path is a git submodule. If so, attempt to initialize and/or update the submodule if needed. This function makes calls to the ``git`` command in subprocesses. The ``_check_submodule_no_git`` option uses pure Python to check if the given path looks like a git submodule, but it cannot perform updates. """ cmd = ['git', 'submodule', 'status', '--', self.path] try: log.info('Running `{0}`; use the --no-git option to disable git ' 'commands'.format(' '.join(cmd))) returncode, stdout, stderr = run_cmd(cmd) except _CommandNotFound: # The git command simply wasn't found; this is most likely the # case on user systems that don't have git and are simply # trying to install the package from PyPI or a source # distribution. Silently ignore this case and simply don't try # to use submodules return False stderr = stderr.strip() if returncode != 0 and stderr: # Unfortunately the return code alone cannot be relied on, as # earlier versions of git returned 0 even if the requested submodule # does not exist # This is a warning that occurs in perl (from running git submodule) # which only occurs with a malformatted locale setting which can # happen sometimes on OSX. See again # https://github.com/astropy/astropy/issues/2749 perl_warning = ('perl: warning: Falling back to the standard locale ' '("C").') if not stderr.strip().endswith(perl_warning): # Some other uknown error condition occurred log.warn('git submodule command failed ' 'unexpectedly:\n{0}'.format(stderr)) return False # Output of `git submodule status` is as follows: # # 1: Status indicator: '-' for submodule is uninitialized, '+' if # submodule is initialized but is not at the commit currently indicated # in .gitmodules (and thus needs to be updated), or 'U' if the # submodule is in an unstable state (i.e. has merge conflicts) # # 2. SHA-1 hash of the current commit of the submodule (we don't really # need this information but it's useful for checking that the output is # correct) # # 3. The output of `git describe` for the submodule's current commit # hash (this includes for example what branches the commit is on) but # only if the submodule is initialized. We ignore this information for # now _git_submodule_status_re = re.compile( '^(?P[+-U ])(?P[0-9a-f]{40}) ' '(?P\S+)( .*)?$') # The stdout should only contain one line--the status of the # requested submodule m = _git_submodule_status_re.match(stdout) if m: # Yes, the path *is* a git submodule self._update_submodule(m.group('submodule'), m.group('status')) return True else: log.warn( 'Unexpected output from `git submodule status`:\n{0}\n' 'Will attempt import from {1!r} regardless.'.format( stdout, self.path)) return False def _check_submodule_no_git(self): """ Like ``_check_submodule_using_git``, but simply parses the .gitmodules file to determine if the supplied path is a git submodule, and does not exec any subprocesses. This can only determine if a path is a submodule--it does not perform updates, etc. This function may need to be updated if the format of the .gitmodules file is changed between git versions. """ gitmodules_path = os.path.abspath('.gitmodules') if not os.path.isfile(gitmodules_path): return False # This is a minimal reader for gitconfig-style files. It handles a few of # the quirks that make gitconfig files incompatible with ConfigParser-style # files, but does not support the full gitconfig syntaix (just enough # needed to read a .gitmodules file). gitmodules_fileobj = io.StringIO() # Must use io.open for cross-Python-compatible behavior wrt unicode with io.open(gitmodules_path) as f: for line in f: # gitconfig files are more flexible with leading whitespace; just # go ahead and remove it line = line.lstrip() # comments can start with either # or ; if line and line[0] in (':', ';'): continue gitmodules_fileobj.write(line) gitmodules_fileobj.seek(0) cfg = RawConfigParser() try: cfg.readfp(gitmodules_fileobj) except Exception as exc: log.warn('Malformatted .gitmodules file: {0}\n' '{1} cannot be assumed to be a git submodule.'.format( exc, self.path)) return False for section in cfg.sections(): if not cfg.has_option(section, 'path'): continue submodule_path = cfg.get(section, 'path').rstrip(os.sep) if submodule_path == self.path.rstrip(os.sep): return True return False def _update_submodule(self, submodule, status): if status == ' ': # The submodule is up to date; no action necessary return elif status == '-': if self.offline: raise _AHBootstrapSystemExit( "Cannot initialize the {0} submodule in --offline mode; " "this requires being able to clone the submodule from an " "online repository.".format(submodule)) cmd = ['update', '--init'] action = 'Initializing' elif status == '+': cmd = ['update'] action = 'Updating' if self.offline: cmd.append('--no-fetch') elif status == 'U': raise _AHBoostrapSystemExit( 'Error: Submodule {0} contains unresolved merge conflicts. ' 'Please complete or abandon any changes in the submodule so that ' 'it is in a usable state, then try again.'.format(submodule)) else: log.warn('Unknown status {0!r} for git submodule {1!r}. Will ' 'attempt to use the submodule as-is, but try to ensure ' 'that the submodule is in a clean state and contains no ' 'conflicts or errors.\n{2}'.format(status, submodule, _err_help_msg)) return err_msg = None cmd = ['git', 'submodule'] + cmd + ['--', submodule] log.warn('{0} {1} submodule with: `{2}`'.format( action, submodule, ' '.join(cmd))) try: log.info('Running `{0}`; use the --no-git option to disable git ' 'commands'.format(' '.join(cmd))) returncode, stdout, stderr = run_cmd(cmd) except OSError as e: err_msg = str(e) else: if returncode != 0: err_msg = stderr if err_msg is not None: log.warn('An unexpected error occurred updating the git submodule ' '{0!r}:\n{1}\n{2}'.format(submodule, err_msg, _err_help_msg)) class _CommandNotFound(OSError): """ An exception raised when a command run with run_cmd is not found on the system. """ def run_cmd(cmd): """ Run a command in a subprocess, given as a list of command-line arguments. Returns a ``(returncode, stdout, stderr)`` tuple. """ try: p = sp.Popen(cmd, stdout=sp.PIPE, stderr=sp.PIPE) # XXX: May block if either stdout or stderr fill their buffers; # however for the commands this is currently used for that is # unlikely (they should have very brief output) stdout, stderr = p.communicate() except OSError as e: if DEBUG: raise if e.errno == errno.ENOENT: msg = 'Command not found: `{0}`'.format(' '.join(cmd)) raise _CommandNotFound(msg, cmd) else: raise _AHBoostrapSystemExit( 'An unexpected error occurred when running the ' '`{0}` command:\n{1}'.format(' '.join(cmd), str(e))) # Can fail of the default locale is not configured properly. See # https://github.com/astropy/astropy/issues/2749. For the purposes under # consideration 'latin1' is an acceptable fallback. try: stdio_encoding = locale.getdefaultlocale()[1] or 'latin1' except ValueError: # Due to an OSX oddity locale.getdefaultlocale() can also crash # depending on the user's locale/language settings. See: # http://bugs.python.org/issue18378 stdio_encoding = 'latin1' # Unlikely to fail at this point but even then let's be flexible if not isinstance(stdout, _text_type): stdout = stdout.decode(stdio_encoding, 'replace') if not isinstance(stderr, _text_type): stderr = stderr.decode(stdio_encoding, 'replace') return (p.returncode, stdout, stderr) class _DummyFile(object): """A noop writeable object.""" errors = '' # Required for Python 3.x encoding = 'utf-8' def write(self, s): pass def flush(self): pass @contextlib.contextmanager def _silence(): """A context manager that silences sys.stdout and sys.stderr.""" old_stdout = sys.stdout old_stderr = sys.stderr sys.stdout = _DummyFile() sys.stderr = _DummyFile() exception_occurred = False try: yield except: exception_occurred = True # Go ahead and clean up so that exception handling can work normally sys.stdout = old_stdout sys.stderr = old_stderr raise if not exception_occurred: sys.stdout = old_stdout sys.stderr = old_stderr _err_help_msg = """ If the problem persists consider installing astropy_helpers manually using pip (`pip install astropy_helpers`) or by manually downloading the source archive, extracting it, and installing by running `python setup.py install` from the root of the extracted source code. """ class _AHBootstrapSystemExit(SystemExit): def __init__(self, *args): if not args: msg = 'An unknown problem occurred bootstrapping astropy_helpers.' else: msg = args[0] msg += '\n' + _err_help_msg super(_AHBootstrapSystemExit, self).__init__(msg, *args[1:]) if sys.version_info[:2] < (2, 7): # In Python 2.6 the distutils log does not log warnings, errors, etc. to # stderr so we have to wrap it to ensure consistency at least in this # module import distutils class log(object): def __getattr__(self, attr): return getattr(distutils.log, attr) def warn(self, msg, *args): self._log_to_stderr(distutils.log.WARN, msg, *args) def error(self, msg): self._log_to_stderr(distutils.log.ERROR, msg, *args) def fatal(self, msg): self._log_to_stderr(distutils.log.FATAL, msg, *args) def log(self, level, msg, *args): if level in (distutils.log.WARN, distutils.log.ERROR, distutils.log.FATAL): self._log_to_stderr(level, msg, *args) else: distutils.log.log(level, msg, *args) def _log_to_stderr(self, level, msg, *args): # This is the only truly 'public' way to get the current threshold # of the log current_threshold = distutils.log.set_threshold(distutils.log.WARN) distutils.log.set_threshold(current_threshold) if level >= current_threshold: if args: msg = msg % args sys.stderr.write('%s\n' % msg) sys.stderr.flush() log = log() _config = _Bootstrapper.main() def use_astropy_helpers(**kwargs): """ Ensure that the `astropy_helpers` module is available and is importable. This supports automatic submodule initialization if astropy_helpers is included in a project as a git submodule, or will download it from PyPI if necessary. Parameters ---------- path : str or None, optional A filesystem path relative to the root of the project's source code that should be added to `sys.path` so that `astropy_helpers` can be imported from that path. If the path is a git submodule it will automatically be initialzed and/or updated. The path may also be to a ``.tar.gz`` archive of the astropy_helpers source distribution. In this case the archive is automatically unpacked and made temporarily available on `sys.path` as a ``.egg`` archive. If `None` skip straight to downloading. download_if_needed : bool, optional If the provided filesystem path is not found an attempt will be made to download astropy_helpers from PyPI. It will then be made temporarily available on `sys.path` as a ``.egg`` archive (using the ``setup_requires`` feature of setuptools. If the ``--offline`` option is given at the command line the value of this argument is overridden to `False`. index_url : str, optional If provided, use a different URL for the Python package index than the main PyPI server. use_git : bool, optional If `False` no git commands will be used--this effectively disables support for git submodules. If the ``--no-git`` option is given at the command line the value of this argument is overridden to `False`. auto_upgrade : bool, optional By default, when installing a package from a non-development source distribution ah_boostrap will try to automatically check for patch releases to astropy-helpers on PyPI and use the patched version over any bundled versions. Setting this to `False` will disable that functionality. If the ``--offline`` option is given at the command line the value of this argument is overridden to `False`. offline : bool, optional If `False` disable all actions that require an internet connection, including downloading packages from the package index and fetching updates to any git submodule. Defaults to `True`. """ global _config config = _config.copy() config.update(**kwargs) bootstrapper = _Bootstrapper(**config) bootstrapper.run() montage-wrapper-0.9.8/astropy_helpers/astropy_helpers/0000755000077000000240000000000012405342415023224 5ustar tomstaff00000000000000montage-wrapper-0.9.8/astropy_helpers/astropy_helpers/__init__.py0000644000077000000240000000013612333217235025336 0ustar tomstaff00000000000000try: from .version import version as __version__ except ImportError: __version__ = '' montage-wrapper-0.9.8/astropy_helpers/astropy_helpers/__init__.pyc0000644000077000000240000000045212333217235025502 0ustar tomstaff00000000000000ó mSc@s2yddlmZWnek r-dZnXdS(i(tversiontN(Rt __version__t ImportError(((s_/Users/tom/Dropbox/Code/development/montage-wrapper/astropy_helpers/astropy_helpers/__init__.pyts montage-wrapper-0.9.8/astropy_helpers/astropy_helpers/__pycache__/0000755000077000000240000000000012405342415025434 5ustar tomstaff00000000000000montage-wrapper-0.9.8/astropy_helpers/astropy_helpers/__pycache__/__init__.cpython-34.pyc0000644000077000000240000000042512405250261031615 0ustar tomstaff00000000000000î mS^ã @s3yddlmZWnek r.dZYnXdS)é)ÚversionÚN)rÚ __version__Ú ImportError©rrú_/Users/tom/Dropbox/Code/development/montage-wrapper/astropy_helpers/astropy_helpers/__init__.pyÚs montage-wrapper-0.9.8/astropy_helpers/astropy_helpers/__pycache__/git_helpers.cpython-34.pyc0000644000077000000240000000732212405253027032371 0ustar tomstaff00000000000000î øUTÕã@sjdZddlZddlZddlZddlZdd„Zddd„Zdddd d „ZdS) zP Utilities for retrieving revision information from a project's git repository. éNcCspytjƒdpd}Wntk r4d}YnXy|j|ƒ}Wn!tk rk|jdƒ}YnX|S)Nézutf-8Úlatin1)ÚlocaleÚgetdefaultlocaleÚ ValueErrorÚdecodeÚUnicodeDecodeError)ÚstreamÚstdio_encodingÚtext©r úb/Users/tom/Dropbox/Code/development/montage-wrapper/astropy_helpers/astropy_helpers/git_helpers.pyÚ _decode_stdios   rcCs“ytddddd|ƒ}Wntk r7|SYnX|sB|Sd|kr‹|jddƒd }tddddd|ƒ}|d|S|Sd S) zÇ Updates the git revision string if and only if the path is being imported directly from a git working copy. This ensures that the revision number in the version string is accurate. ÚshaTÚ show_warningFÚpathÚdevz.devrrN)Úget_git_devstrÚOSErrorÚsplit)ÚversionrÚdevstrÚ version_baser r r Úupdate_git_devstr"s    rFTcsOˆdkrtjƒ‰ntjjˆƒsNtjjtjjˆƒƒ‰ntjjtjjˆdƒƒssdS|rˆddg}ndddg}‡‡fdd †}||ƒ\}}}| r!|d kr!dd d dg}||ƒ\}}}|d krt|j dƒƒSdSn*|r;t |ƒdd…St |ƒj ƒSdS)a| Determines the number of revisions in this repository. Parameters ---------- sha : bool If True, the full SHA1 hash will be returned. Otherwise, the total count of commits in the repository will be used as a "revision number". show_warning : bool If True, issue a warning if git returns an error code, otherwise errors pass silently. path : str or None If a string, specifies the directory to look in to find the git repository. If `None`, the current working directory is used. If given a filename it uses the directory containing that file. Returns ------- devversion : str Either a string with the revsion number (if `sha` is False), the SHA1 hash of the current commit (if `sha` is True), or an empty string if git version info could not be identified. Nz.gitÚz rev-parseÚHEADzrev-listz--countcsmyMtjdg|dˆdtjdtjdtjƒ}|jƒ\}}WnItk r˜}z)ˆr‚tjdt|ƒƒndSWYdd}~XnX|jdkr׈rÇtjd j ˆƒƒn|jddfS|jd krˆr tjd j |d ƒƒn|j||fS|jd kr]ˆrMtjd j t |ƒƒƒn|j||fS|j||fS)NÚgitÚcwdÚstdoutÚstderrÚstdinzError running git: ré€z>No git repository present at {0!r}! Using default dev version.ézQYour git looks old (does it support {0}?); consider upgrading to v1.7.2 or later.rz0Git failed while determining revision count: {0})Nrr) Ú subprocessÚPopenÚPIPEÚ communicaterÚwarningsÚwarnÚstrÚ returncodeÚformatr)ÚcmdÚprrÚe)rrr r Úrun_gitis4   zget_git_devstr..run_gitr"z--abbrev-commitz --abbrev=0rs é() ÚosÚgetcwdrÚisdirÚabspathÚdirnameÚexistsÚjoinr)ÚcountrÚstrip)rrrr,r/r*rrr )rrr r=s( !! r)Ú__doc__rr1r#r'rrrr r r r Ús     montage-wrapper-0.9.8/astropy_helpers/astropy_helpers/__pycache__/setup_helpers.cpython-34.pyc0000644000077000000240000012044412405253027032747 0ustar tomstaff00000000000000î øUT„Ýã@sïdZddlmZmZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddlmZmZmZddlmZddlmZddlmZmZddlmZdd lmZdd lmZ dd l!m"Z#dd l$m%Z&dd l'm(Z)ddl*m+Z,ddl-m.Z/ddl0m1Z1ddl2m3Z3ddl4m5Z5m6Z6m7Z7idd6dd6dd6dd6Z8yddl9Z9de8dde8dd?„d?e&ƒZWdd@dA„ZXGdBdC„dCe/ƒZYe8dróGdDdE„dEe>ƒZZndFdG„Z[dHdI„Z\dJdK„Z]dLfdMdN„Z^dOdP„Z_dQdR„Z`ddSdT„ZaebƒddUdV„ZcdWdX„ZddYdZ„Zed[d\„ZfGd]d^„d^ejgƒZhd_d`da„Zidbdc„Zjddde„Zkdfdg„ZlGdhdi„dieƒZmdS)jzx This module contains a number of utilities for use during setup/build/packaging that are useful to astropy as a whole. é)Úabsolute_importÚprint_functionN)ÚlogÚ ccompilerÚ sysconfig)ÚDistutilsOptionError)Ú Distribution)ÚDistutilsErrorÚDistutilsFileError)Ú Extension)ÚCommand)Úsdist)Ú build_ext)Úbuild_py)Úinstall)Ú install_lib)Úregister)Ú find_packagesé)Ú AstropyTest)ÚsilenceÚinvalidate_cachesÚwalk_skip_hiddenFÚadjusted_compilerÚregistered_commandsÚ have_cythonÚ have_sphinxT)ÚBuildDoczunknown localeaPossible misconfiguration of one of the environment variables LC_ALL, LC_CTYPES, LANG, or LANGUAGE. For an example of how to configure your system's language environment on OSX see http://blog.remibergsma.com/2012/07/10/setting-locales-correctly-on-mac-osx-terminal-application/écCsàdg}tdrdSdtd where is the command you ran. ÚversionÚpkgÚfixedÚunixaú The C compiler used to compile Python {compiler:s}, and which is normally used to compile C extensions, is not available. You can explicitly specify which compiler to use by setting the CC environment variable, for example: CC=gcc python setup.py or if you are using MacOS X, you can try: CC=clang python setup.py )rzclang)Ú _module_stateÚosÚenvironÚget_compiler_versionÚOSErrorÚtextwrapÚdedentÚformatrÚwarnÚsysÚexitÚreÚmatchÚget_distutils_build_optionrÚget_default_compilerrÚget_config_var)ÚpackageZcompiler_mappingZ c_compilerr#ÚmsgÚbrokenr%Ú compiler_type©r;úd/Users/tom/Dropbox/Code/development/montage-wrapper/astropy_helpers/astropy_helpers/setup_helpers.pyÚadjust_compilerRsJ                r=c Csotjtj|ƒdgdtjƒ}|jƒdjƒ}y|jƒd}Wntk rjdSYnX|S)Nz --versionÚstdoutrÚunknown)Ú subprocessÚPopenÚshlexÚsplitÚPIPEÚ communicateÚstripÚ IndexError)r"ÚprocessÚoutputr#r;r;r<r*Âs"  r*cCs·tddkrtdƒ‚ntitjjtjdƒd6tjdd…d6ƒ}|jj tdƒt ƒ;y|j ƒ|j ƒWnt ttfk r¬YnXWdQX|S)z…Returns a distutils Distribution object used to instrument the setup environment before calling the actual setup() function. rNz„astropy_helpers.setup_helpers.register_commands() must be called before using astropy_helpers.setup_helpers.get_dummy_distribution()rÚ script_namerÚ script_args)r'Ú RuntimeErrorrr(ÚpathÚbasenamer0ÚargvÚcmdclassÚupdaterÚparse_config_filesÚparse_command_liner ÚAttributeErrorÚ SystemExit)Údistr;r;r<Úget_dummy_distributionÐs     rWcCsXtƒ}xH|D]<}|jj|ƒ}|dk r||kr||dSqWdSdS)ap Returns the value of the given distutils option. Parameters ---------- option : str The name of the option commands : list of str The list of commands on which this option is available Returns ------- val : str or None the value of the given distutils option. If the option is not set, returns None. Nr)rWÚcommand_optionsÚget)ÚoptionÚcommandsrVÚcmdZcmd_optsr;r;r<Úget_distutils_optionîs   r]cCst|dddgƒS)a! Returns the value of the given distutils build option. Parameters ---------- option : str The name of the option Returns ------- val : str or None The value of the given distutils build option. If the option is not set, returns None. ÚbuildrÚ build_clib)r])rZr;r;r<r4 sr4cCst|dgƒS)a# Returns the value of the given distutils install option. Parameters ---------- option : str The name of the option Returns ------- val : str or None The value of the given distutils build option. If the option is not set, returns None. r)r])rZr;r;r<Úget_distutils_install_optionsr`cCst|ddddgƒS)a7 Returns the value of the given distutils build or install option. Parameters ---------- option : str The name of the option Returns ------- val : str or None The value of the given distutils build or install option. If the option is not set, returns None. r^rr_r)r])rZr;r;r<Ú%get_distutils_build_or_install_option,sracCs&tdƒ}|dkr"tjƒS|S)a! Determines the compiler that will be used to build extension modules. Returns ------- compiler : str The compiler option specificied for the build, build_ext, or build_clib command; or the default compiler for the platform if none was specified. r"N)r4rr5)r"r;r;r<Úget_compiler_option>s   rbc sÄyt|ddgƒd}Wnttfk r=d}YnXtƒ‰t‡fdd†ddgDƒƒrttdƒƒ}n t|ƒ}|dk rÀ||krÀˆjdƒ}d |_n|S) z¸ Determines if the build is in debug mode. Returns ------- debug : bool True if the current build was started with the debug option, False otherwise. ÚfromlistÚdebugrNc3s|]}|ˆjkVqdS)N)r[)Ú.0r\)rVr;r<ú esz#get_debug_option..r^rT) Úget_pkg_version_moduleÚ ImportErrorrTrWÚanyÚboolr4Úget_command_classÚ force_rebuild)Ú packagenameZ current_debugrdZ build_ext_cmdr;)rVr<Úget_debug_optionQs   %  rncsT|st|dddgƒSt|dd|ƒ‰t‡fdd†|DƒƒSdS)a”Returns the package's .version module generated by `astropy_helpers.version_helpers.generate_version_py`. Raises an ImportError if the version module is not found. If ``fromlist`` is an iterable, return a tuple of the members of the version module corresponding to the member names given in ``fromlist``. Raises an `AttributeError` if any of these module members are not found. z.versionrcÚc3s|]}tˆ|ƒVqdS)N)Úgetattr)reÚmember)Úmodr;r<rf‡sz)get_pkg_version_module..N)Ú __import__Útuple)rmrcr;)rrr<rgts rgcCsßtddk rtdSit|ƒd6td6t||ƒd6td6td6td6td6td<}td r}t|d .finalize_optionsc s~tƒ}xP|jD]E}d|jkr`|jjdƒ}|jj||ƒ|jjdƒnxõt|jƒD]ä\}}|jdƒr¨|}|dd…d}n,|jdƒrÔ|dd…d}|}nt j j |ƒsìqpn|j r||j|.runFrlr—rˆÚ user_optionsÚboolean_optionsr) Úshould_build_with_cythonZCython.DistutilsrÚSetuptoolsBuildExtÚdictÚ__dict__rpr»r¼r‰Úobject)rmr„r—ZbaseclsÚattrsrŒr‹r;)rrºrmr<rzÊs" #>     rzcCs<dj|jtjdd…ƒ}tjj|jd|ƒS)Nz.{0}-{1}rrÚlib)r.Z plat_namer0r#r(rMr‘Z build_base)r\Zplat_specifierr;r;r<Ú_get_platlib_dirLs"rÄc@sBeZdZejdd…Zejdd…Zdd„ZdS)r|NcCs5|jdƒ}t|ƒ}||_tj|ƒdS)Nr^)Úget_finalized_commandrÄr³ÚSetuptoolsInstallrŒ)ršÚ build_cmdÚ platlib_dirr;r;r<rŒUs  zAstropyInstall.finalize_options)r‚Ú __module__Ú __qualname__rÆr»r¼rŒr;r;r;r<r|Qs r|c@sBeZdZejdd…Zejdd…Zdd„ZdS)r}NcCs5|jdƒ}t|ƒ}||_tj|ƒdS)Nr^)rÅrÄÚ build_dirÚSetuptoolsInstallLibrŒ)ršrÇrÈr;r;r<rŒ`s  z"AstropyInstallLib.finalize_options)r‚rÉrÊrÌr»r¼rŒr;r;r;r<r}\s r}c@s]eZdZejdd…Zejdd…Zdd„Zddd„Zdd„ZdS) r{NcCsG|jdƒ}t|ƒ}||_||_||_tj|ƒdS)Nr^)rÅrÄZ build_purelibr³ÚSetuptoolsBuildPyrŒ)ršrÇrÈr;r;r<rŒks     zAstropyBuildPy.finalize_optionsFcCs‚|jj}g}xV|D]N}xE|D]0}|t|jƒdd…j|ƒr&Pq&q&W|j|ƒqWtj|||ƒdS)Nr)Ú distributionÚ skip_2to3Úlenr³Ú startswithÚappendrÍÚrun_2to3)ršÚfilesZdoctestsrÏZfiltered_filesÚfiler7r;r;r<rÓys   &zAstropyBuildPy.run_2to3cCstj|ƒdS)N)rÍr‹)ršr;r;r<r‹†szAstropyBuildPy.run) r‚rÉrÊrÍr»r¼rŒrÓr‹r;r;r;r<r{gs   r{c Csltƒ}|j|ƒ}t|dƒr:||jkr:dS|jddƒ}t||ƒrytdj|||ƒƒ‚nxvt|jƒD]e\}}|d|kr‰t j dj||ƒƒ|j|=||j krê|j j |ƒnPq‰q‰W|jj |d|fƒ|r$|j j |ƒnt||dƒt|dƒsXt|gƒ|_n|jj|ƒdS)aî Add a custom option to a setup command. Issues a warning if the option already exists on that command. Parameters ---------- command : str The name of the command as given on the command line name : str The name of the build option doc : str A short description of the option, for the `--help` message is_bool : bool, optional When `True`, the option is a boolean option and doesn't require an associated value. Ú_astropy_helpers_optionsNú-Ú_zc{0!r} already has a {1!r} class attribute, barring {2!r} from being usable as a custom option name.rz&Overriding existing {0!r} option {1!r})rWrkÚhasattrrÖÚreplacerLr.r©r»rr/r¼r¨rÒÚsetattrÚsetÚadd) Úcommandr…ÚdocÚis_boolrVZcmdclsÚattrr¶r\r;r;r<rƒ‹s0  rƒc@sZeZdZdZejd gZejdgZdd„Zdd„Zd d „Z dS) r~aéExtends the built in 'register' command to support a ``--hidden`` option to make the registered version hidden on PyPI by default. The result of this is that when a version is registered as "hidden" it can still be downloaded from PyPI, but it does not show up in the list of actively supported versions under http://pypi.python.org/pypi/astropy, and is not set as the most recent version. Although this can always be set through the web interface it may be more convenient to be able to specify via the 'register' command. Hidden may also be considered a safer default when running the 'register' command, though this command uses distutils' normal behavior if the ``--hidden`` option is omitted. ÚhiddenNú.mark this release as hidden on PyPI by defaultcCstj|ƒd|_dS)NF)ÚSetuptoolsRegisterÚinitialize_optionsrâ)ršr;r;r<råás z"AstropyRegister.initialize_optionscCs8tj||ƒ}|dkr4|jr4d|dÚstderrÚ zbuild succeeded.ZTRAVISÚtruezrThe build_sphinx travis build FAILED because sphinx issued documentation warnings (scroll up to see the warnings).zYbuild_sphinx returning a non-zero exit code because sphinx issued documentation warnings.zutf-8Úhtmlz index.htmlzfile://zNopen-docs-in-browser option was given, but the builder is not html! Ignogring.z8Sphinx Documentation subprocess failed with return code r¤)<Ú webbrowserÚPY3Úurllib.requestrÚurllibrËr(rMrCr‘r¬rÚmkpathÚreinitialize_commandZinplaceÚ run_commandrÅÚabspathr³ÚpkgutilÚ get_importerÚinspectZgetsourcelinesrýr‹r,r-r.rrÚ_self_iden_rexÚrangerÐrpr«ÚreprrÿrÚrrdr0Ú executablerr@rArDÚSTDOUTrEÚprintr)rYr/ÚencodeÚ returncoderZbuilderZbuilder_target_dirr°Ústrr1)ršrrÚretcodeZbasedirÚsubdirZ staticdirrÇrZ ah_importerr ZrunlinesZ runlinenoZ subproccodeÚiZidenÚvalÚprocZstdoZstdeZ stdolinesr8ZabsdirZ index_pathZfileurlr;r;r<r‹Csˆ     &               zAstropyBuildSphinx.run)ròr¡ró)rôrõrö)r÷rørù)rúrûrü)r‚rÉrÊrñÚ descriptionrýr»rÒr¼r2ÚcompileÚUNICODErrårŒr‹r;r;r;r<rs(       rcCs†tdd„tjDƒƒ}tdd„tjDƒƒ}|jdƒ|jdƒtdddd d d gƒ}|j|j|ƒƒS) aG Returns a set of all the distutils display options in their long and short forms. These are the setup.py arguments such as --name or --version which print the project's metadata and then exit. Returns ------- opts : set The long and short form display option arguments, including the - or -- css'|]}|drd|dVqdS)rr×Nr;)rerûr;r;r<rf×sz0get_distutils_display_options..css|]}d|dVqdS)z--rNr;)rerûr;r;r<rfÙsz-hz--helpZcleanrZsetoptZsaveoptsÚegg_infoÚalias)rÜrÚdisplay_optionsrÝÚunion)Zshort_display_optsZlong_display_optsZdisplay_commandsr;r;r<Úget_distutils_display_optionsÌs    r0cCs/tƒ}tttjdd…ƒj|ƒƒS)zm Returns True if sys.argv contains any of the distutils display options such as --version or --name. rN)r0rjrÜr0rOÚ intersection)r.r;r;r<Úis_distutils_display_optionës r2cCs]t|ƒ}|j|dƒ|j|dƒtt||dƒƒ}|j|dƒdS)zÆ This function is deprecated and maintained for backward compatibility with affiliated packages. Affiliated packages should update their setup.py to use `get_package_info` instead. Ú ext_modulesÚ package_dataÚpackagesr¸N)Úget_package_infoÚextendrQÚlistrÜ)r rr4Ú packagenamesZ package_dirsrr;r;r<Úupdate_package_filesôs  r:Ú.cCs-g}g}i}i}g}tt|d|ƒƒ}xÕt||ƒD]Ä}t|dƒrˆ|jƒ}x|D]} td| ŒqnWnt|dƒrÁ|jƒ} x| D]} t| ƒqªWnt|dƒrß|jƒ} nd} | sF|j t j j |j ƒƒqFqFWxat||ƒD]P}t|dƒrI|j|jƒƒnt|dƒr|j|jƒƒqqW|jt|||d gƒƒx?ttt|ƒƒƒD]%\} }|jd krª|| =qªqªWtƒd krx!|D]}|jj d ƒqéWni|d 6|d6|d6|d6|d6S)a! Collates all of the information for building all subpackages subpackages and returns a dictionary of keyword arguments that can be passed directly to `distutils.setup`. The purpose of this function is to allow subpackages to update the arguments to the package's ``setup()`` function in its setup.py script, rather than having to specify all extensions/package data directly in the ``setup.py``. See Astropy's own ``setup.py`` for example usage and the Astropy development docs for more details. This function obtains that information by iterating through all packages in ``srcdir`` and locating a ``setup_package.py`` module. This module can contain the following functions: ``get_extensions()``, ``get_package_data()``, ``get_build_options()``, ``get_external_libraries()``, and ``requires_2to3()``. Each of those functions take no arguments. - ``get_extensions`` returns a list of `distutils.extension.Extension` objects. - ``get_package_data()`` returns a dict formatted as required by the ``package_data`` argument to ``setup()``. - ``get_build_options()`` returns a list of tuples describing the extra build options to add. - ``get_external_libraries()`` returns a list of libraries that can optionally be built using external dependencies. - ``requires_2to3()`` should return `True` when the source code requires `2to3` processing to run on Python 3.x. If ``requires_2to3()`` is missing, it is assumed to return `True`. ÚexcludeÚget_build_optionsr^Úget_external_librariesÚ requires_2to3TÚget_extensionsÚget_package_dataržZ skip_cythonZmsvcz /MANIFESTr3r5r¸r4rÏ)Úfilter_packagesrÚiter_setup_packagesrÙr=rƒr>Úadd_external_libraryr?rÒr(rMr’r“r7r@rQrAÚget_cython_extensionsÚreversedr8r©r…rbÚextra_link_args)r r<r3r5r4r¸rÏZsetuppkgrîrZÚ librariesÚlibraryr?r&r›r;r;r<r6sP(     % r6ccs€xy|D]q}|jdƒ}tjj||Œ}tjjtjj|dƒƒ}tjj|ƒrt|ƒ}|VqqWdS)a6 A generator that finds and imports all of the ``setup_package.py`` modules in the source packages. Returns ------- modgen : generator A generator that yields (modname, mod), where `mod` is the module and `modname` is the module name for the ``setup_package.py`` modules. r;zsetup_package.pyN)rCr(rMr‘rr¬Ú import_file)r r5rmÚ package_partsÚ package_pathZ setup_packageÚmoduler;r;r<rCms   rCccs“xŒt|ƒD]~\}}}xk|D]c}|jdƒr#tjjtjj||ƒƒ}dj||dd…gƒ}||fVq#q#WPq WdS)a€ A generator that yields Cython source files (ending in '.pyx') in the source packages. Returns ------- pyxgen : generator A generator that yields (extmod, fullfn) where `extmod` is the full name of the module that the .pyx file would live in based on the source directory structure, and `fullfn` is the path to the .pyx file. z.pyxr;NrŸr£)rr«r(rMrr‘)r¸rˆÚdirpathÚdirnamesÚ filenamesÚfnZfullfnÚextmodr;r;r<Úiter_pyx_files„s  !rScCsÉy t|ddddgƒ}Wntk r:d}YnX|dkrx|dk rxy |j}Wqxtk rtYqxXny |j}Wntk rŸd}YnXtdrÁ| s½|dkrÁ|SdSdS) aReturns the previously used Cython version (or 'unknown' if not previously built) if Cython should be used to build extension modules from pyx files. If the ``release`` parameter is not specified an attempt is made to determine the release flag from `astropy.version`. z.cython_versionrcr„rœNr?rF)rsrhr„rTrœr')r7r„Zversion_modulerœr;r;r<r½œs$         r½cCsg}g}xc|D][}xR|jD]G}|jdƒr#tjjtjj|ƒdƒ}|j|ƒq#q#WqWx¢|D]š} | jdƒ} tjj|| Œ} xmt | | ƒD]\\} } tjjtjj| ƒdƒ}||kr³|jt | | gd|ƒƒq³q³WqyW|S)aÎ Looks for Cython files and generates Extensions if needed. Parameters ---------- srcdir : str Path to the root of the source directory to search. prevextensions : list of `~distutils.core.Extension` objects The extensions that are already defined. Any .pyx files already here will be ignored. extincludedirs : list of str or None Directories to include as the `include_dirs` argument to the generated `~distutils.core.Extension` objects. Returns ------- exts : list of `~distutils.core.Extension` objects The new extensions that are needed to compile all .pyx files (does not include any already in `prevextensions`). ú.pyxú.crr;r¦)rTrU) rªr«r(rMÚrealpathÚsplitextrÒrCr‘rSr )r r5ZprevextensionsZextincludedirsZprevsourcepathsr3r›ÚsZ sourcepathrˆrKrLrRr·r;r;r<rEÀs  " " rEcCsŒt|tƒst‚tjj|ƒrNt|dƒ}|jƒ}WdQXnd}||krˆt|dƒ}|j|ƒWdQXndS)zã Write `data` to `filename`, if the content of the file is different. Parameters ---------- filename : str The file name to be written to. data : bytes The data to be written to `filename`. ÚrbNÚwb) Ú isinstanceÚbytesÚAssertionErrorr(rMÚexistsr°Úreadr±)ÚfilenameréÚfdZ original_datar;r;r<Úwrite_if_differentòs  rbc CsÎtjddkr_ddl}t|dƒr7|`nddl}ddl}|j|ƒn:ddl}t|dƒrƒ|`nddl}t|ƒy|j ƒ}Wnt k rÉ|j ƒ}YnX|S)z- Gets the path to the numpy headers. rrNÚ__NUMPY_SETUP__) r0Ú version_infoÚbuiltinsrÙrcÚimpržÚreloadÚ __builtin__Z get_includerTZget_numpy_include)rerfržrhZ numpy_includer;r;r<r¥ s"          r¥cCsst|dƒ^}djtjjtjj|ƒdƒjtjƒdd…ƒ}tj |||dƒSWdQXdS)zb Imports a module from a single file as if it doesn't belong to a particular package. ÚUrØrrNú.py)rjrir) r°r‘r(rMrrWrCÚseprfÚ load_module)r`rar…r;r;r<rJ's ;rJcs4eZdZdZ‡fdd†Zdd„Z‡S)ÚDistutilsExtensionArgsz× A special dictionary whose default values are the empty list. This is useful for building up a set of arguments for `distutils.Extension` without worrying whether the entry is already present. cs,dd„}tt|ƒj|||ŽdS)NcSsgS)Nr;r;r;r;r<Údefault_factoryBsz8DistutilsExtensionArgs.__init__..default_factory)ÚsuperrmÚ__init__)ršÚargsÚkwargsrn)Ú __class__r;r<rpAs zDistutilsExtensionArgs.__init__cCs2x+|jƒD]\}}||j|ƒq WdS)N)rr7)ršÚotherÚkeyr'r;r;r<rQHszDistutilsExtensionArgs.update)r‚rÉrÊrñrprQr;r;)rsr<rm9s rmz pkg-configc Csidd6dd6dd6dd6d d 6}d j|d j|ƒƒf}tƒ}y8tj|d ddtjƒ}|jƒdjƒ}WnŽtjk r}zkdj|ƒdj|j ƒdj|j ƒdj|j ƒg} t j dj| ƒƒ|dj|ƒWYdd}~XnX|j dkrpdjdj|ƒƒdg} t j dj| ƒƒ|dj|ƒn«x¨|jƒD]š} | dd…jdƒ} | dd…jtjƒƒ} | |kr| dkrît| jddƒƒ} n||| j| ƒq}|dj| ƒq}W|S)a Uses pkg-config to update a set of distutils Extension arguments to include the flags necessary to link against the given packages. If the pkg-config lookup fails, default_libraries is applied to libraries. Parameters ---------- packages : list of str A list of pkg-config packages to look up. default_libraries : list of str A list of library names to use if the pkg-config lookup fails. Returns ------- config : dict A dictionary containing keyword arguments to `distutils.Extension`. These entries include: - ``include_dirs``: A list of include directories - ``library_dirs``: A list of library directories - ``libraries``: A list of libraries - ``define_macros``: A list of macro defines - ``undef_macros``: A list of macros to undefine - ``extra_compile_args``: A list of extra arguments to pass to the compiler r¦z-IÚ library_dirsz-LrHz-lÚ define_macrosz-DÚ undef_macrosz-Uz{0} --libs --cflags {1}ú ÚshellTr>rz4{0} failed. This may cause the build to fail below.z command: {0}z returncode: {0}z output: {0}r Nz.pkg-config could not lookup up package(s) {0}.z, z'This may cause the build to fail below.r Úasciiú=rÚextra_compile_args)r.r‘rmr@rArDrErFÚCalledProcessErrorr\r"rIrr/r7rCÚdecoder0ÚgetfilesystemencodingrtrÒ) r5Zdefault_librariesrZflag_maprÞÚresultÚpiperIÚeÚlinesÚtokenÚargrðr;r;r<Ú pkg_configMs:  $   r‡cCsGx@dddgD]/}t|td|ƒdj|ƒddƒqWdS) zü Add a build option for selecting the internal or system copy of a library. Parameters ---------- library : str The name of the library. If the library is `foo`, the build option will be called `--use-system-foo`. r^rrz use-system-zUse the system {0} libraryràTN)rƒr#r.)rIrÞr;r;r<rDœs rDcCstdj|ƒƒptdƒS)a Returns `True` if the build configuration indicates that the given library should use the system copy of the library rather than the internal one. For the given library `foo`, this will be `True` if `--use-system-foo` or `--use-system-libraries` was provided at the commandline or in `setup.cfg`. Parameters ---------- library : str The name of the library Returns ------- use_system : bool `True` if the build should use the system copy of the library. zuse_system_{0}Zuse_system_libraries)rar.)rIr;r;r<Úuse_system_library­srˆcs,trd‰nd‰‡fdd†|DƒS)zw Removes some packages from the package list that shouldn't be installed on the current version of Python. Z_py2Z_py3cs%g|]}|jˆƒs|‘qSr;)r«)reÚx)r<r;r<ú Ñs z#filter_packages..)r)r9r;)r<r<rBÆs rBc @s}eZdZdZdd d!d"d#d$d%d&d'd(d)g Zejd*ƒejd+ƒejd,ƒejd-ƒdd„Zd S).r€zz A dummy build_sphinx command that is called if Sphinx is not installed and displays a relevant error message ú fresh-envÚEroú all-filesÚaú source-dir=rXú build-dir=Nú config-dir=Úcúbuilder=Úbúproject=úversion=úrelease=útoday=ú link-indexr&úwarnings-returncoder¡ú clean-docsrõúno-intersphinxrøúopen-docs-in-browserrûc Cs9ytdƒ‚Wn"tjdƒtjdƒYnXdS)Nz)Sphinx must be installed for build_sphinxz1error : Sphinx must be installed for build_sphinxr)rLrÚerrorr0r1)ršr;r;r<råñs  z"FakeBuildSphinx.initialize_options)r‹rŒro)rrŽro)rrXro)rNro)r‘r’ro)r“r”ro)r•Nro)r–Nro)r—Nro)r˜Nro)r™r&ro)ršr¡ro)r›rõro)rœrøro)rrûro)r‚rÉrÊrñr»rÒrår;r;r;r<r€Ôs"      r€)nrñZ __future__rrÚ collectionsr®rfrr(rr2rBr”r@r0r,Ú distutilsrrrÚ distutils.cmdrÚdistutils.distrÚdistutils.errorsr r Údistutils.corer r Zdistutils.command.sdistr ryZsetuptools.command.build_extrr¾Zsetuptools.command.build_pyrrÍZsetuptools.command.installrrÆZsetuptools.command.install_librrÌZsetuptools.command.registerrräÚ setuptoolsrZ test_helpersrÚutilsrrrr'r˜rhZsphinxZsphinx.setup_commandrrýÚ ValueErrorrƒrqr/Ú SyntaxErrorrdrrÏr=r*rWr]r4r`rarbrnrgr‡rxrzrÄr|r}r{rƒr~rr0r2r:r6rCrSr½rtrErbr¥rJÚ defaultdictrmr‡rDrˆrBr€r;r;r;r<Ús¶                    p        # 5 ‚   $A4 Ë  j  $1   O   montage-wrapper-0.9.8/astropy_helpers/astropy_helpers/__pycache__/test_helpers.cpython-34.pyc0000644000077000000240000001563112405253027032567 0ustar tomstaff00000000000000î øUTž$ã@s®ddlmZmZmZmZddlZddlZddlZddlZddl Z ddl m Z ddl m Z ejddkZGdd„de eƒZdS) é)Úabsolute_importÚdivisionÚprint_functionÚunicode_literalsN)ÚCommandé)Ú_fix_user_optionséc@s¬eZdZdZd:d;d<d=d>d?d@dAdBdCdDdEdFdGgZeeƒZd+Zd,d-„Zd.d/„Zd0d1„Z d2d3„Z d4d5„Z d6d7„Z d8d9„Z d'S)HÚ AstropyTestzRun the tests for this packageúpackage=ÚPúwThe name of a specific package to test, e.g. 'io.fits' or 'utils'. If nothing is specified, all default tests are run.ú test-path=ÚtáHSpecify a test location by path. If a relative path to a .py file, it is relative to the built package, so e.g., a leading "astropy/" is necessary. If a relative path to a .rst file, it is relative to the directory *below* the --docs-path directory, so a leading "docs/" is usually necessary. May also be an absolute path.úverbose-resultsÚVú#Turn on verbose output from pytest.úplugins=Úpú&Plugins to enable when running pytest.ú pastebin=Úbú8Enable pytest pastebin output. Either 'all' or 'failed'.úargs=Úaú,Additional arguments to be passed to pytest.ú remote-dataÚRú$Run tests that download remote data.Úpep8Ú8úPEnable PEP8 checking and disable regular tests. Requires the pytest-pep8 plugin.ÚpdbÚdú0Start the interactive Python debugger on errors.ÚcoverageÚcú8Create a coverage report. Requires the coverage package.ú open-filesÚoú#Fail if any tests leave files open.ú parallel=Újú–Run the tests in parallel on the specified number of CPUs. If negative, all the cores on the machine will be used. Requires the pytest-xdist plugin.ú docs-path=NúŒThe path to the documentation .rst files. If not provided, and the current directory contains a directory called "docs", that will be used.ú skip-docsú(Don't test the documentation .rst files.ÚcCs‚d|_d|_d|_d|_d|_d|_d|_d|_d|_d|_ d|_ d|_ d|_ d|_ dS)NFr)ÚpackageZ test_pathZverbose_resultsZpluginsZpastebinÚargsZ remote_datar r#r&Z open_filesÚparallelÚ docs_pathZ skip_docs)Úself©r9úc/Users/tom/Dropbox/Code/development/montage-wrapper/astropy_helpers/astropy_helpers/test_helpers.pyÚinitialize_options?s             zAstropyTest.initialize_optionscCsdS)Nr9)r8r9r9r:Úfinalize_optionsOszAstropyTest.finalize_optionscCsud}d}|jr>|jƒ\}}||7}||7}ntrMd}nd}d}|j||d|d|ƒS)z9 Build a Python script to run the tests. r3z/import builtins; builtins._ASTROPY_TEST_ = Truez5import __builtin__; __builtin__._ASTROPY_TEST_ = Truea¥{cmd_pre}{0}; import {1.package_name}, sys; result = ({1.package_name}.test(package={1.package!r}, test_path={1.test_path!r}, args={1.args!r}, plugins={1.plugins!r}, verbose={1.verbose_results!r}, pastebin={1.pastebin!r}, remote_data={1.remote_data!r}, pep8={1.pep8!r}, pdb={1.pdb!r}, open_files={1.open_files!r}, parallel={1.parallel!r}, docs_path={1.docs_path!r}, skip_docs={1.skip_docs!r})); {cmd_post}sys.exit(result)Úcmd_preÚcmd_post)r&Ú_generate_coverage_commandsÚPY3Úformat)r8r=r>ÚpreÚpostZset_flagÚcmdr9r9r:Úgenerate_testing_commandTs    z$AstropyTest.generate_testing_commandc Cs5yddl}Wntk r0tdƒ‚YnXdS)zn This method checks that any required modules are installed before running the tests. rNzOThe 'test' command requires the astropy package to be installed and importable.)ÚastropyÚ ImportError)r8rFr9r9r:Ú_validate_required_depsys  z#AstropyTest._validate_required_depsc Cs±|jƒ|jƒ|jdkrPtjjdƒrPtjjdƒ|_qPnz=|jƒ}tj t j dd|gd|j ddƒ}Wdt j|jƒXt|ƒ‚dS)z Run the tests! NZdocsz-Bz-cÚcwdÚ close_fdsF)Ú_build_temp_installrHr7ÚosÚpathÚexistsÚabspathrEÚ subprocessÚcallÚsysÚ executableÚ testing_pathÚshutilÚrmtreeÚtmp_dirÚ SystemExit)r8rDÚretcoder9r9r:Úrun…s   zAstropyTest.runcCs±|jdddƒ|jdƒ|jdƒ}tjj|jƒ}tjd|j dƒ|_ tjj |j tjj |ƒƒ|_ tj||j ƒtjd|j ƒdS)zË Build the package and copy the build to a temporary directory for the purposes of testing this avoids creating pyc and __pycache__ directories inside the build directory ÚbuildÚinplaceTÚprefixz-test-z setup.cfgN)Úreinitialize_commandÚ run_commandÚget_finalized_commandrLrMrOÚ build_libÚtempfileÚmkdtempÚ package_namerWÚjoinÚbasenamerTrUÚcopytreeÚcopy)r8Ú build_cmdÚnew_pathr9r9r:rK³s 'zAstropyTest._build_temp_installc CsY|jdkrtdƒ‚nyddl}Wntk rNtdƒ‚YnXtjj|j|jddƒ}t |dƒ}|j ƒ}WdQXt r£d}nd }|j d |ƒj d |jƒ}tjj|j dƒ}t |d ƒ}|j|jd ƒƒWdQXdjtjjdƒ|ƒ}djtjjdƒ|jƒ} || fS)zf This method creates the post and pre commands if coverage is to be generated rz*--coverage can not be used with --parallelNz;--coverage requires that the coverage package is installed.ZtestsÚ coveragercÚrÚ2Ú3z{ignore_python_version}z {packagename}Úwbzutf-8zZimport coverage; cov = coverage.coverage(data_file="{0}", config_file="{1}"); cov.start();z .coveragezgcov.stop(); from astropy.tests.helper import _save_coverage; _save_coverage(cov, result, "{0}", "{1}");Ú.)r6Ú ValueErrorr&rGrLrMrerTrdÚopenÚreadr@ÚreplacerWÚwriteÚencoderArO) r8r&rkÚfdZcoveragerc_contentZignore_python_versionZtmp_coveragercÚtmpr=r>r9r9r:r?Ãs2    z'AstropyTest._generate_coverage_commands)r r r )rrr)rrr)rrr)rrr)rrr)rrr)zpep8r!r")zpdbr$r%)zcoverager'r()r)r*r+)r,r-r.)r/Nr0)r1Nr2)Ú__name__Ú __module__Ú __qualname__Ú descriptionÚ user_optionsrrdr;r<rErHrZrKr?r9r9r9r:r sH      % . r )Ú __future__rrrrrLrUrPrRrbÚ setuptoolsrÚcompatrÚ version_infor@Úobjectr r9r9r9r:Ús"     montage-wrapper-0.9.8/astropy_helpers/astropy_helpers/__pycache__/utils.cpython-34.pyc0000644000077000000240000001075612405250262031227 0ustar tomstaff00000000000000î mS"ã@sddlZddlZddlZddlZejdd…dkr\ddlmZn dd„ZGdd„deƒZej d d „ƒZ ej d kr½ddl Z d d „Z n dd „Z dd„Zdddd„Zdd„Zdd„ZdS)éNéé)Úinvalidate_cachescCsdS)N©rrrú\/Users/tom/Dropbox/Code/development/montage-wrapper/astropy_helpers/astropy_helpers/utils.pyÚsrc@s4eZdZdZdZdd„Zdd„ZdS)Ú _DummyFilezA noop writeable object.ÚcCsdS)Nr)ÚselfÚsrrrÚwritesz_DummyFile.writecCsdS)Nr)r rrrÚflushsz_DummyFile.flushN)Ú__name__Ú __module__Ú __qualname__Ú__doc__Úerrorsr r rrrrrs  rc cs~tj}tj}tƒt_tƒt_d}y dVWn#d}|t_|t_‚YnX|sz|t_|t_ndS)z:A context manager that silences sys.stdout and sys.stderr.FNT)ÚsysÚstdoutÚstderrr)Ú old_stdoutÚ old_stderrÚexception_occurredrrrÚsilences        rÚwin32c Cs‡t|tƒr'|jtjƒƒ}ny;tjjj|ƒ}|dksQt ‚t |d@ƒ}Wnt t fk r‚d}YnX|S)zÒ Returns True if the given filepath has the hidden attribute on MS-Windows. Based on a post here: http://stackoverflow.com/questions/284115/cross-platform-hidden-file-detection érFéÿÿÿÿ) Ú isinstanceÚbytesÚdecoderÚgetfilesystemencodingÚctypesZwindllZkernel32ZGetFileAttributesWÚAssertionErrorÚboolÚAttributeError)ÚfilepathÚattrsÚresultrrrÚ_has_hidden_attribute9s r(cCsdS)NFr)r%rrrr(IscCs^tjjtjj|ƒƒ}t|tƒr?|jdƒ}n|jdƒ}|p]t|ƒS)zî Determines if a given file or directory is hidden. Parameters ---------- filepath : str The path to a file or directory Returns ------- hidden : bool Returns `True` if the file is hidden ó.Ú.)ÚosÚpathÚbasenameÚabspathrrÚ startswithr()r%ÚnameZ is_dottedrrrÚis_path_hiddenMs r1Fccsxztj|ddd|d|ƒD]W\}}}dd„|Dƒ|dd…