sunpy-0.6.3/0000755000175000017500000000000012675276746013612 5ustar stuartstuart00000000000000sunpy-0.6.3/RELEASE.md0000644000175000017500000000376012622602451015174 0ustar stuartstuart00000000000000The SunPy project is happy to announce the release of SunPy 0.6.0. This is a major SunPy release with lots of changes that will make SunPy even better than it was before. This release consists of 1,341 commits from 29 different people and 13 new contributors! The major changes in this release are: * Most functions throughout the SunPy code base expect Astropy Quantity objects, and return Astropy Quantity objects. * Python 2.6 support has ended, we do not expect this release to work under Python 2.6. * Sample data has been removed from SunPy but helpers for downloading sample data have been added to sunpy.data. * TimeRange has a new property based API, e.g. start and end are now properties. * Map.rotate() now pads arrays to prevent loss of data under rotation. * Map.rotate() now defaults to the slower but more accurate bi-quartic interpolation method (order=4). * SunPy colormaps are now registered with matplotlib, allowing their use from imshow and similar functions after the import of sunpy.cm. * JSOC client export calls now checks for an email address. * Solar rotation calculation functionality has been added, along with functionality to de-rotate MapCubes. * Files downloaded through the VSO now keep their file extension. The people who have contributed to this release are: Stuart Mumford Daniel Ryan Steven Christe Jack Ireland Brigitta Sipocz * Asish Panda Andrew Inglis Albert Y. Shih Rishabh Sharma David Perez-Suarez Rajul Srivastava Andrew Leonard Ruben De Visscher * Dumindu Buddhika * Goran Cetusic * Jongyeob Park * ChloĆ© Guennou * Ishtyaq Habib * Nabil Freij Simon Liedtke Abigail Stevens * Alex Hamilton * Ambar Mehrotra * Erik M. Bray * Jaylen Wimbish * Juan Camilo Buitrago-Casas * Larry Manley Norbert Gyenge Rishabh Mishra * Where an * indicates their first contribution. sunpy-0.6.3/setup.py0000644000175000017500000001075412675272112015312 0ustar stuartstuart00000000000000#!/usr/bin/env python # This file is based havily on the astropy version here: # https://github.com/astropy/package-template/blob/master/setup.py # Which is licensed under the astropy license. import glob import os import sys import ah_bootstrap from setuptools import setup # A dirty hack to get around some early import/configurations ambiguities if sys.version_info[0] >= 3: import builtins else: import __builtin__ as builtins builtins._ASTROPY_SETUP_ = True # -- Read the Docs Setup ----------------------------------------------------- on_rtd = os.environ.get('READTHEDOCS', None) == 'True' if on_rtd: os.environ['HOME'] = '/home/docs/' os.environ['SUNPY_CONFIGDIR'] = '/home/docs/' from astropy_helpers.setup_helpers import ( register_commands, get_debug_option, get_package_info) from astropy_helpers.git_helpers import get_git_devstr from astropy_helpers.version_helpers import generate_version_py # Get some values from the setup.cfg from distutils import config conf = config.ConfigParser() conf.read(['setup.cfg']) metadata = dict(conf.items('metadata')) PACKAGENAME = metadata.get('package_name', 'packagename') DESCRIPTION = metadata.get('description', 'SunPy: Python for Solar Physics') AUTHOR = metadata.get('author', 'The SunPy Community') AUTHOR_EMAIL = metadata.get('author_email', 'sunpy@googlegroups.com') LICENSE = metadata.get('license', 'BSD 2-Clause') URL = metadata.get('url', 'http://sunpy.org') LONG_DESCRIPTION = "SunPy is a Python library for solar physics data analysis." # Store the package name in a built-in variable so it's easy # to get from other parts of the setup infrastructure builtins._ASTROPY_PACKAGE_NAME_ = PACKAGENAME # VERSION should be PEP386 compatible (http://www.python.org/dev/peps/pep-0386) VERSION = '0.6.3' # Indicates if this version is a release version RELEASE = 'dev' not in VERSION if not RELEASE: VERSION += get_git_devstr(False) # Populate the dict of setup command overrides; this should be done before # invoking any other functionality from distutils since it can potentially # modify distutils' behavior. cmdclassd = register_commands(PACKAGENAME, VERSION, RELEASE) try: from sunpy.tests.setup_command import SunPyTest # Overwrite the Astropy Testing framework cmdclassd['test'] = type('SunPyTest', (SunPyTest,), {'package_name': 'sunpy'}) except Exception: # Get everything, if it dosen't work, we still want SunPy to install. pass # Freeze build information in version.py generate_version_py(PACKAGENAME, VERSION, RELEASE, get_debug_option(PACKAGENAME)) # Treat everything in scripts except README.rst as a script to be installed scripts = [fname for fname in glob.glob(os.path.join('scripts', '*')) if os.path.basename(fname) != 'README.rst'] # Get configuration information from all of the various subpackages. # See the docstring for setup_helpers.update_package_files for more # details. package_info = get_package_info() # Add the project-global data package_info['package_data'].setdefault(PACKAGENAME, []) # Include all .c files, recursively, including those generated by # Cython, since we can not do this in MANIFEST.in with a "dynamic" # directory name. c_files = [] for root, dirs, files in os.walk(PACKAGENAME): for filename in files: if filename.endswith('.c'): c_files.append( os.path.join( os.path.relpath(root, PACKAGENAME), filename)) package_info['package_data'][PACKAGENAME].extend(c_files) extras_require = {'database': ["sqlalchemy"], 'image': ["scikit-image"], 'jpeg2000': ["glymur"], 'net': ["suds-jurko", "beautifulsoup4", "requests"]} extras_require['all'] = extras_require['database'] + extras_require['image'] + \ extras_require['net'] + ["wcsaxes>=0.6"] setup(name=PACKAGENAME, version=VERSION, description=DESCRIPTION, scripts=scripts, setup_requires=['numpy>1.7.1'], install_requires=['numpy>1.7.1', 'astropy>=1.0.0', 'scipy', 'pandas>=0.12.0', 'matplotlib>=1.1'], extras_require=extras_require, provides=[PACKAGENAME], author=AUTHOR, author_email=AUTHOR_EMAIL, license=LICENSE, url=URL, long_description=LONG_DESCRIPTION, cmdclass=cmdclassd, zip_safe=False, use_2to3=False, include_package_data=True, **package_info ) sunpy-0.6.3/ez_setup.py0000644000175000017500000002757312622602451016012 0ustar stuartstuart00000000000000#!python """Bootstrap setuptools installation If you want to use setuptools in your package's setup.py, just include this file in the same directory with it, and add this to the top of your setup.py:: from ez_setup import use_setuptools use_setuptools() If you want to require a specific version of setuptools, set a download mirror, or use an alternate download directory, you can do so by supplying the appropriate options to ``use_setuptools()``. This file can also be run as a script to install or upgrade setuptools. """ import os import shutil import sys import tempfile import tarfile import optparse import subprocess import platform from distutils import log try: from site import USER_SITE except ImportError: USER_SITE = None DEFAULT_VERSION = "1.4.2" DEFAULT_URL = "https://pypi.python.org/packages/source/s/setuptools/" def _python_cmd(*args): args = (sys.executable,) + args return subprocess.call(args) == 0 def _check_call_py24(cmd, *args, **kwargs): res = subprocess.call(cmd, *args, **kwargs) class CalledProcessError(Exception): pass if not res == 0: msg = "Command '%s' return non-zero exit status %d" % (cmd, res) raise CalledProcessError(msg) vars(subprocess).setdefault('check_call', _check_call_py24) def _install(tarball, install_args=()): # extracting the tarball tmpdir = tempfile.mkdtemp() log.warn('Extracting in %s', tmpdir) old_wd = os.getcwd() try: os.chdir(tmpdir) tar = tarfile.open(tarball) _extractall(tar) tar.close() # going in the directory subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0]) os.chdir(subdir) log.warn('Now working in %s', subdir) # installing log.warn('Installing Setuptools') if not _python_cmd('setup.py', 'install', *install_args): log.warn('Something went wrong during the installation.') log.warn('See the error message above.') # exitcode will be 2 return 2 finally: os.chdir(old_wd) shutil.rmtree(tmpdir) def _build_egg(egg, tarball, to_dir): # extracting the tarball tmpdir = tempfile.mkdtemp() log.warn('Extracting in %s', tmpdir) old_wd = os.getcwd() try: os.chdir(tmpdir) tar = tarfile.open(tarball) _extractall(tar) tar.close() # going in the directory subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0]) os.chdir(subdir) log.warn('Now working in %s', subdir) # building an egg log.warn('Building a Setuptools egg in %s', to_dir) _python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir) finally: os.chdir(old_wd) shutil.rmtree(tmpdir) # returning the result log.warn(egg) if not os.path.exists(egg): raise IOError('Could not build the egg.') def _do_download(version, download_base, to_dir, download_delay): egg = os.path.join(to_dir, 'setuptools-%s-py%d.%d.egg' % (version, sys.version_info[0], sys.version_info[1])) if not os.path.exists(egg): tarball = download_setuptools(version, download_base, to_dir, download_delay) _build_egg(egg, tarball, to_dir) sys.path.insert(0, egg) # Remove previously-imported pkg_resources if present (see # https://bitbucket.org/pypa/setuptools/pull-request/7/ for details). if 'pkg_resources' in sys.modules: del sys.modules['pkg_resources'] import setuptools setuptools.bootstrap_install_from = egg def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, download_delay=15): # making sure we use the absolute path to_dir = os.path.abspath(to_dir) was_imported = 'pkg_resources' in sys.modules or \ 'setuptools' in sys.modules try: import pkg_resources except ImportError: return _do_download(version, download_base, to_dir, download_delay) try: pkg_resources.require("setuptools>=" + version) return except pkg_resources.VersionConflict: e = sys.exc_info()[1] if was_imported: sys.stderr.write( "The required version of setuptools (>=%s) is not available,\n" "and can't be installed while this script is running. Please\n" "install a more recent version first, using\n" "'easy_install -U setuptools'." "\n\n(Currently using %r)\n" % (version, e.args[0])) sys.exit(2) else: del pkg_resources, sys.modules['pkg_resources'] # reload ok return _do_download(version, download_base, to_dir, download_delay) except pkg_resources.DistributionNotFound: return _do_download(version, download_base, to_dir, download_delay) def _clean_check(cmd, target): """ Run the command to download target. If the command fails, clean up before re-raising the error. """ try: subprocess.check_call(cmd) except subprocess.CalledProcessError: if os.access(target, os.F_OK): os.unlink(target) raise def download_file_powershell(url, target): """ Download the file at url to target using Powershell (which will validate trust). Raise an exception if the command cannot complete. """ target = os.path.abspath(target) cmd = [ 'powershell', '-Command', "(new-object System.Net.WebClient).DownloadFile(%(url)r, %(target)r)" % vars(), ] _clean_check(cmd, target) def has_powershell(): if platform.system() != 'Windows': return False cmd = ['powershell', '-Command', 'echo test'] devnull = open(os.path.devnull, 'wb') try: try: subprocess.check_call(cmd, stdout=devnull, stderr=devnull) except: return False finally: devnull.close() return True download_file_powershell.viable = has_powershell def download_file_curl(url, target): cmd = ['curl', url, '--silent', '--output', target] _clean_check(cmd, target) def has_curl(): cmd = ['curl', '--version'] devnull = open(os.path.devnull, 'wb') try: try: subprocess.check_call(cmd, stdout=devnull, stderr=devnull) except: return False finally: devnull.close() return True download_file_curl.viable = has_curl def download_file_wget(url, target): cmd = ['wget', url, '--quiet', '--output-document', target] _clean_check(cmd, target) def has_wget(): cmd = ['wget', '--version'] devnull = open(os.path.devnull, 'wb') try: try: subprocess.check_call(cmd, stdout=devnull, stderr=devnull) except: return False finally: devnull.close() return True download_file_wget.viable = has_wget def download_file_insecure(url, target): """ Use Python to download the file, even though it cannot authenticate the connection. """ try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen src = dst = None try: src = urlopen(url) # Read/write all in one block, so we don't create a corrupt file # if the download is interrupted. data = src.read() dst = open(target, "wb") dst.write(data) finally: if src: src.close() if dst: dst.close() download_file_insecure.viable = lambda: True def get_best_downloader(): downloaders = [ download_file_powershell, download_file_curl, download_file_wget, download_file_insecure, ] for dl in downloaders: if dl.viable(): return dl def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, delay=15, downloader_factory=get_best_downloader): """Download setuptools from a specified location and return its filename `version` should be a valid setuptools version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where the egg will be downloaded. `delay` is the number of seconds to pause before an actual download attempt. ``downloader_factory`` should be a function taking no arguments and returning a function for downloading a URL to a target. """ # making sure we use the absolute path to_dir = os.path.abspath(to_dir) tgz_name = "setuptools-%s.tar.gz" % version url = download_base + tgz_name saveto = os.path.join(to_dir, tgz_name) if not os.path.exists(saveto): # Avoid repeated downloads log.warn("Downloading %s", url) downloader = downloader_factory() downloader(url, saveto) return os.path.realpath(saveto) def _extractall(self, path=".", members=None): """Extract all members from the archive to the current working directory and set owner, modification time and permissions on directories afterwards. `path' specifies a different directory to extract to. `members' is optional and must be a subset of the list returned by getmembers(). """ import copy import operator from tarfile import ExtractError directories = [] if members is None: members = self for tarinfo in members: if tarinfo.isdir(): # Extract directories with a safe mode. directories.append(tarinfo) tarinfo = copy.copy(tarinfo) tarinfo.mode = 448 # decimal for oct 0700 self.extract(tarinfo, path) # Reverse sort directories. if sys.version_info < (2, 4): def sorter(dir1, dir2): return cmp(dir1.name, dir2.name) directories.sort(sorter) directories.reverse() else: directories.sort(key=operator.attrgetter('name'), reverse=True) # Set correct owner, mtime and filemode on directories. for tarinfo in directories: dirpath = os.path.join(path, tarinfo.name) try: self.chown(tarinfo, dirpath) self.utime(tarinfo, dirpath) self.chmod(tarinfo, dirpath) except ExtractError: e = sys.exc_info()[1] if self.errorlevel > 1: raise else: self._dbg(1, "tarfile: %s" % e) def _build_install_args(options): """ Build the arguments to 'python setup.py install' on the setuptools package """ install_args = [] if options.user_install: if sys.version_info < (2, 6): log.warn("--user requires Python 2.6 or later") raise SystemExit(1) install_args.append('--user') return install_args def _parse_args(): """ Parse the command line for options """ parser = optparse.OptionParser() parser.add_option( '--user', dest='user_install', action='store_true', default=False, help='install in user site package (requires Python 2.6 or later)') parser.add_option( '--download-base', dest='download_base', metavar="URL", default=DEFAULT_URL, help='alternative URL from where to download the setuptools package') parser.add_option( '--insecure', dest='downloader_factory', action='store_const', const=lambda: download_file_insecure, default=get_best_downloader, help='Use internal, non-validating downloader' ) options, args = parser.parse_args() # positional arguments are ignored return options def main(version=DEFAULT_VERSION): """Install or upgrade setuptools and EasyInstall""" options = _parse_args() tarball = download_setuptools(download_base=options.download_base, downloader_factory=options.downloader_factory) return _install(tarball, _build_install_args(options)) if __name__ == '__main__': sys.exit(main()) sunpy-0.6.3/ah_bootstrap.py0000644000175000017500000010650312675272112016635 0ustar stuartstuart00000000000000""" 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 # What follows are several import statements meant to deal with install-time # issues with either missing or misbehaving pacakges (including making sure # setuptools itself is installed): # 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() # Note: The following import is required as a workaround to # https://github.com/astropy/astropy-helpers/issues/89; if we don't import this # module now, it will get cleaned up after `run_setup` is called, but that will # later cause the TemporaryDirectory class defined in it to stop working when # used later on by setuptools try: import setuptools.py31compat except ImportError: pass # matplotlib can cause problems if it is imported from within a call of # run_setup(), because in some circumstances it will try to write to the user's # home directory, resulting in a SandboxViolation. See # https://github.com/matplotlib/matplotlib/pull/4165 # Making sure matplotlib, if it is available, is imported early in the setup # process can mitigate this (note importing matplotlib.pyplot has the same # issue) try: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot except: # Ignore if this fails for *any* reason* pass # End compatibility imports... # 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 from distutils import log from distutils.debug import DEBUG # 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 # A list of all the configuration options and their required types CFG_OPTIONS = [ ('auto_use', bool), ('path', str), ('download_if_needed', bool), ('index_url', str), ('use_git', bool), ('offline', bool), ('auto_upgrade', bool) ] 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 attributes, 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) # If this is a release then the .git directory will not exist so we # should not use git. git_dir_exists = os.path.exists(os.path.join(os.path.dirname(__file__), '.git')) if use_git is None and not git_dir_exists: use_git = False 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, argv=None): if argv is None: argv = sys.argv config = cls.parse_config() config.update(cls.parse_command_line(argv)) auto_use = config.pop('auto_use', False) bootstrapper = cls(**config) if auto_use: # Run the bootstrapper, otherwise the setup.py is using the old # use_astropy_helpers() interface, in which case it will run the # bootstrapper manually after reconfiguring it. bootstrapper.run() return bootstrapper @classmethod def parse_config(cls): 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, argv=None): if argv is None: argv = sys.argv 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 argv: config['use_git'] = False argv.remove('--no-git') if '--offline' in argv: config['offline'] = True argv.remove('--offline') return config def run(self): strategies = ['local_directory', 'local_file', 'index'] dist = None # First, remove any previously imported versions of astropy_helpers; # this is necessary for nested installs where one package's installer # is installing another package via setuptools.sandbox.run_setup, as in # the case of setup_requires for key in list(sys.modules): try: if key == PACKAGE_NAME or key.startswith(PACKAGE_NAME + '.'): del sys.modules[key] except AttributeError: # Sometimes mysterious non-string things can turn up in # sys.modules continue # 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)) # This is a bit hacky, but if astropy_helpers was loaded from a # directory/submodule its Distribution object gets a "precedence" of # "DEVELOP_DIST". However, in other cases it gets a precedence of # "EGG_DIST". However, when activing the distribution it will only be # placed early on sys.path if it is treated as an EGG_DIST, so always # do that dist = dist.clone(precedence=pkg_resources.EGG_DIST) # 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. try: pkg_resources.working_set.add(dist, replace=True) except TypeError: # Some (much) older versions of setuptools do not have the # replace=True option here. These versions are old enough that all # bets may be off anyways, but it's easy enough to work around just # in case... if dist.key in pkg_resources.working_set.by_key: del pkg_resources.working_set.by_key[dist.key] pkg_resources.working_set.add(dist) @property def config(self): """ A `dict` containing the options this `_Bootstrapper` was configured with. """ return dict((optname, getattr(self, optname)) for optname, _ in CFG_OPTIONS if hasattr(self, optname)) 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 straightforward 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) next_version = _next_version(dist.parsed_version) req = pkg_resources.Requirement.parse( '{0}>{1},<{2}'.format(DIST_NAME, dist.version, next_version)) 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 further 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 unknown 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 syntax (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) def _next_version(version): """ Given a parsed version from pkg_resources.parse_version, returns a new version string with the next minor version. Examples ======== >>> _next_version(pkg_resources.parse_version('1.2.3')) '1.3.0' """ if hasattr(version, 'base_version'): # New version parsing from setuptools >= 8.0 if version.base_version: parts = version.base_version.split('.') else: parts = [] else: parts = [] for part in version: if part.startswith('*'): break parts.append(part) parts = [int(p) for p in parts] if len(parts) < 3: parts += [0] * (3 - len(parts)) major, minor, micro = parts[:3] return '{0}.{1}.{2}'.format(major, minor + 1, 0) 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() BOOTSTRAPPER = _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 initialized 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 BOOTSTRAPPER config = BOOTSTRAPPER.config config.update(**kwargs) # Create a new bootstrapper with the updated configuration and run it BOOTSTRAPPER = _Bootstrapper(**config) BOOTSTRAPPER.run() sunpy-0.6.3/CHANGELOG.md0000644000175000017500000002546012675272112015411 0ustar stuartstuart000000000000000.6.3 ------ * Change setup.py extras to install suds-jurko not suds. 0.6.2 ----- * Changed start of GOES 2 operational time range back to 1980-01-04 so data from 1980 can be read into GOESLightCurve object * Fix bug with numpy 1.10 * update astropy_helpers * Added new sample data 0.6.1 ----- * Fixed MapCube animations by working around a bug in Astropy's ImageNormalize * Small fix to RTD builds for Affiliated packages * SunPy can now be installed without having to install Astropy first. * MapCubes processed with ``coalignment.apply_shifts`` now have correct metadata. * Multiple fixes for WCS transformations, especially with solar-x, solar-y CTYPE headers. 0.6.0 ----- * Enforced the use of Astropy Quantities through out most of SunPy. * Dropped Support for Python 2.6. * Remove old style string formatting and other 2.6 compatibility lines. * Added vso like querying feature to JSOC Client. * Refactor the JSOC client so that it follows the .query() .get() interface of VSOClient and UnifedDownloader. * Provide `__str__` and `__repr__` methods on vso `QueryResponse` deprecate `.show()`. * Downloaded files now keep file extensions rather than replacing all periods with underscores. * Update to TimeRange API, removed t1 and t0, start and end are now read-only attributes. * Added ability to download level3 data for lyra Light Curve along with corresponding tests. * Added support for gzipped FITS files. * Add STEREO HI Map subclass and color maps. * Map.rotate() no longer crops any image data. * For accuracy, default Map.rotate() transformation is set to bi-quartic. * `sunpy.image.transform.affine_transform` now casts integer data to float64 and sets NaN values to 0 for all transformations except scikit-image rotation with order <= 3. * CD matrix now updated, if present, when Map pixel size is changed. * Removed now-redundant method for rotating IRIS maps since the functionality exists in Map.rotate() * Provide `__str__` and `__repr__` methods on vso `QueryResponse` deprecate `.show()` * SunPy colormaps are now registered with matplotlib on import of `sunpy.cm` * `sunpy.cm.get_cmap` no longer defaults to 'sdoaia94' * Added database url config setting to be setup by default as a sqlite database in the sunpy working directory * Added a few tests for the sunpy.roi module * Added capability for figure-based tests * Removed now-redundant method for rotating IRIS maps since the functionality exists in Map.rotate(). * SunPy colormaps are now registered with matplotlib on import of `sunpy.cm`. * `sunpy.cm.get_cmap` no longer defaults to 'sdoaia94'. * Added database url config setting to be setup by default as a sqlite database in the sunpy working directory. * Added a few tests for the sunpy.roi module. * Refactored mapcube co-alignment functionality. * Removed sample data from distribution and added ability to download sample files * Require JSOC request data calls have an email address attached. * Calculation of the solar rotation of a point on the Sun as seen from Earth, and its application to the de-rotation of mapcubes. * Downloaded files now keep file extensions rather than replacing all periods with underscores * Fixed the downloading of files with duplicate names in sunpy.database * Removed sample data from distribution and added ability to download sample files. * Added the calculation of the solar rotation of a point on the Sun as seen from Earth, and its application to the de-rotation of mapcubes. * Changed default for GOESLightCurve.create() so that it gets the data from the most recent existing GOES fits file. * Map plot functionality now uses the mask property if it is present, allowing the plotting of masked map data * Map Expects Quantities and returns quantities for most parameters. * Map now used Astropy.wcs for world <-> pixel conversions. * map.data_to_pixel now has a similar API to map.pixel_to_data. * map.shape has been replaced with map.dimensions, which is ordered x first. * map.rsun_arcseconds is now map.rsun_obs as it returns a quantity. * Map properties are now named tuples rather than dictionaries. * Improvement for Map plots, standardization and improved color tables, better access to plot variables through new plot_settings variable. * Huge improvements in Instrument Map doc strings. Now contain instrument descriptions as well as reference links for more info. * net.jsoc can query data series with time sampling by a Sample attribute implemented in vso. * MapCube.plot and MapCube.peek now support a user defined plot_function argument for customising the animation. * Added new sample data file, an AIA cutout file. * Moved documentation build directory to doc/build 0.5.0 ----- * Added additional functionality to the GOES module i.e. the ability to calculate GOES temperature and emission measure from GOES fluxes. * changed _maps attribute in MapCube to a non-hidden type * Added Nobeyama Radioheliograph data support to Lightcurve object. * Fixed some tests on map method to support Windows * Added a window/split method to time range * Updates to spectrogram documentation * Added method Database.add_from_hek_query_result to HEK database * Added method Database.download_from_vso_query_result * GOES Lightcurve now makes use of a new source of GOES data, provides metadata, and data back to 1981. * Removed sqlalchemy as a requirement for SunPy * Added support for NOAA solar cycle prediction in lightcurves * Some basic tests for GenericLightCurve on types of expected input. * Fix algorithm in sunpy.sun.equation_of_center * Added Docstrings to LightCurve methods. * Added tests for classes in sunpy.map.sources. Note that some classes (TRACE, RHESSI) were left out because SunPy is not able to read their FITS files. * Added functions that implement image coalignment with support for MapCubes. * Cleaned up the sunpy namespace, removed .units, /ssw and .sphinx. Also moved .coords .physics.transforms. * Added contains functionality to TimeRange module * Added t='now' to parse_time to privide utcnow datetime. * Fixed time dependant functions (.sun) to default to t='now' * Fixed solar_semidiameter_angular_size * Improved line quality and performances issues with map.draw_grid() * Remove deprecated make_map command. 0.4.1 ----- Bug Fixes: * Fix map.rotate() functionality * Change of source for GOES data. * Fix EIT test data and sunpy FITS saving * Some documentation fixes * fix file paths to use os.path.join for platform independance. 0.4.0 ----- Features: * **Major** documentation refactor. A far reaching re-write and restructure. * Add a SunPy Database to store and search local data. * Add beta support for querying the HELIO HEC * Add beta HEK to VSO query translation. * Add the ability to download the GOES event list. * Add support for downloading and querying the LYTAF database. * Add support for ANA data. * Updated sun.constants to use astropy.constants objects which include units, source, and error instide. For more info check out http://docs.astropy.org/en/latest/constants/index.html * Add some beta support for IRIS data products * Add a new MapCubeAnimator class with interactive widgets which is returned by mapcube.peek(). * The Glymur library is now used to read JPEG2000 files. * GOESLightCurve now supports all satellites. Bug Fixes: * Add support for VSO queries through proxies. * Fix apparent Right Ascension calulations. * LightCurve meta data member now an OrderedDict Instance 0.3.2 ----- Bug Fixes: * Pass draw_limb arguments to patches.Circle * Pass graw_grid arguments to pyplot.plot() * Fix README code example * Fix Documentation links in potting guide * Update to new EVE data URL * Update LogicalLightcurve example in docs * Improved InteractiveVSOClient documentation * GOESLightCurve now fails politely if no data is avalible. Known Bugs: * sunpy.util.unit_conversion.to_angstrom does not work if 'nm' is passed in. 0.3.1 ----- * Bug Fix: Fix a regression in CompositeMap that made contor plots fail. * Bug Fix: Allow Map() to accept dict as metadata. * Bug Fix: Pass arguments from Map() to io.read_file. 0.3.0 ===== Major Changes: * Removal of Optional PIL dependancy * Parse_time now looks through nested lists/tuples * Draw_limb and draw_grid are now implemented on MapCube and CompositeMap * Caculations for differential roation added * mapcube.plot() now runs a mpl animation with optional controls * A basic Region of Interest framework now exists under sunpy.roi * STEREO COR colour maps have been ported from solarsoft. * sunpy.time.timerange has a split() method that divides up a time range into n equal parts. * Added download progress bar * pyfits is depricated in favor of Astropy spectra: * Plotting has been refactorted to use a consistent interface * spectra now no-longer inherits from numpy.ndarray instead has a .data attribute. Map: * map now no-longer inherits from numpy.ndarray instead has a .data attribute. * make_map is deprecated in favor of Map which is a new factory class * sunpy.map.Map is now sunpy.map.GenericMap * mymap.header is now mymap.meta * attributes of the map class are now read only, changes have to be made through map.meta * new MapMeta class to replace MapHeader, MapMeta is not returned by sunpy.io * The groundwork for GenericMap inherting from astropy.NDData has been done, there is now a NDDataStandin class to provide basic functionality. io: * top level file_tools improved to be more flexible and support multiple HDUs * all functions in sunpy.io now assume mutliple HDUs, even JP2 ones. * there is now a way to override the automatic filetype detection * Automatic fits file detection improved * extract_waveunit added to io.fits for detection of common ways of storing wavelength unit in fits files. Bug fixes or under the hood changes: * A major re-work of all interal imports has resulted in a much cleaner namespace, i.e. sunpy.util.util is no longer used to import util. * Some SOHO and STEREO files were not reading properly due to a date_obs parameter. * Sunpy will now read JP2 files without a comment parameter. * Memory leak in Crotate patched * Callisto: Max gap between files removed 0.2.0 ===== Below are the main features that have been added for this release: * Completely re-written plotting routines for most of the core datatypes. * JPEG 2000 support as an input file type. * Improved documentation for much of the code base, including re-written installation instructions. * New lightcurve object * LYRA support * GOES/XRS support * SDO/EVE support * New Spectrum and Spectrogram object (in development) * Spectrogram plotting routines * Callisto spectrum type and support * STEREO/SWAVES support * Map Object * Added support for LASCO, Yohkoh/XRT maps * A new CompositeMap object for overlaying maps * Resample method * Superpixel method * The addition of the rotate() method for 2D maps. sunpy-0.6.3/licenses/0000755000175000017500000000000012675276745015416 5ustar stuartstuart00000000000000sunpy-0.6.3/licenses/SUNPY.rst0000644000175000017500000000253012675272112017046 0ustar stuartstuart00000000000000SunPy is released under a BSD-style open source licence: Copyright (c) 2013 The SunPy developers All rights reserved. * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. 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. sunpy-0.6.3/licenses/ASTROPY.rst0000644000175000017500000000273012622602451017266 0ustar stuartstuart00000000000000Copyright (c) 2011-2014, Astropy Developers All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Astropy Team 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. sunpy-0.6.3/licenses/FUNCSIGS.rst0000644000175000017500000000104512622602451017344 0ustar stuartstuart00000000000000Copyright 2013 Aaron Iles Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. sunpy-0.6.3/astropy_helpers/0000755000175000017500000000000012675276744017033 5ustar stuartstuart00000000000000sunpy-0.6.3/astropy_helpers/CONTRIBUTING.md0000644000175000017500000000216512622602515021245 0ustar stuartstuart00000000000000Contributing to astropy-helpers =============================== The guidelines for contributing to ``astropy-helpers`` are generally the same as the [contributing guidelines for the astropy core package](http://github.com/astropy/astropy/blob/master/CONTRIBUTING.md). Basically, report relevant issues in the ``astropy-helpers`` issue tracker, and we welcome pull requests that broadly follow the [Astropy coding guidelines](http://docs.astropy.org/en/latest/development/codeguide.html). The key subtlety lies in understanding the relationship between ``astropy`` and ``astropy-helpers``. This package contains the build, installation, and documentation tools used by astropy. It also includes support for the ``setup.py test`` command, though Astropy is still required for this to function (it does not currently include the full Astropy test runner). So issues or improvements to that functionality should be addressed in this package. Any other aspect of the [astropy core package](http://github.com/astropy/astropy) (or any other package that uses ``astropy-helpers``) should be addressed in the github repository for that package. sunpy-0.6.3/astropy_helpers/setup.py0000755000175000017500000000402312662554110020525 0ustar stuartstuart00000000000000#!/usr/bin/env python # Licensed under a 3-clause BSD style license - see LICENSE.rst import ah_bootstrap import pkg_resources from setuptools import setup from astropy_helpers.setup_helpers import register_commands, get_package_info from astropy_helpers.version_helpers import generate_version_py NAME = 'astropy_helpers' VERSION = '1.1.1' RELEASE = 'dev' not in VERSION DOWNLOAD_BASE_URL = 'http://pypi.python.org/packages/source/a/astropy-helpers' generate_version_py(NAME, VERSION, RELEASE, False, uses_git=not RELEASE) # Use the updated version including the git rev count from astropy_helpers.version import version as VERSION cmdclass = register_commands(NAME, VERSION, RELEASE) # This package actually doesn't use the Astropy test command del cmdclass['test'] setup( name=pkg_resources.safe_name(NAME), # astropy_helpers -> astropy-helpers version=VERSION, description='Utilities for building and installing Astropy, Astropy ' 'affiliated packages, and their respective documentation.', author='The Astropy Developers', author_email='astropy.team@gmail.com', license='BSD', url='http://astropy.org', long_description=open('README.rst').read(), download_url='{0}/astropy-helpers-{1}.tar.gz'.format(DOWNLOAD_BASE_URL, VERSION), classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Framework :: Setuptools Plugin', 'Framework :: Sphinx :: Extension', 'Framework :: Sphinx :: Theme', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Build Tools', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: System :: Archiving :: Packaging' ], cmdclass=cmdclass, zip_safe=False, **get_package_info(exclude=['astropy_helpers.tests']) ) sunpy-0.6.3/astropy_helpers/MANIFEST.in0000644000175000017500000000024312622602515020545 0ustar stuartstuart00000000000000include README.rst include CHANGES.rst include LICENSE.rst include ez_setup.py include ah_bootstrap.py exclude *.pyc *.o prune build prune astropy_helpers/tests sunpy-0.6.3/astropy_helpers/ez_setup.py0000644000175000017500000002757312622602515021236 0ustar stuartstuart00000000000000#!python """Bootstrap setuptools installation If you want to use setuptools in your package's setup.py, just include this file in the same directory with it, and add this to the top of your setup.py:: from ez_setup import use_setuptools use_setuptools() If you want to require a specific version of setuptools, set a download mirror, or use an alternate download directory, you can do so by supplying the appropriate options to ``use_setuptools()``. This file can also be run as a script to install or upgrade setuptools. """ import os import shutil import sys import tempfile import tarfile import optparse import subprocess import platform from distutils import log try: from site import USER_SITE except ImportError: USER_SITE = None DEFAULT_VERSION = "1.4.2" DEFAULT_URL = "https://pypi.python.org/packages/source/s/setuptools/" def _python_cmd(*args): args = (sys.executable,) + args return subprocess.call(args) == 0 def _check_call_py24(cmd, *args, **kwargs): res = subprocess.call(cmd, *args, **kwargs) class CalledProcessError(Exception): pass if not res == 0: msg = "Command '%s' return non-zero exit status %d" % (cmd, res) raise CalledProcessError(msg) vars(subprocess).setdefault('check_call', _check_call_py24) def _install(tarball, install_args=()): # extracting the tarball tmpdir = tempfile.mkdtemp() log.warn('Extracting in %s', tmpdir) old_wd = os.getcwd() try: os.chdir(tmpdir) tar = tarfile.open(tarball) _extractall(tar) tar.close() # going in the directory subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0]) os.chdir(subdir) log.warn('Now working in %s', subdir) # installing log.warn('Installing Setuptools') if not _python_cmd('setup.py', 'install', *install_args): log.warn('Something went wrong during the installation.') log.warn('See the error message above.') # exitcode will be 2 return 2 finally: os.chdir(old_wd) shutil.rmtree(tmpdir) def _build_egg(egg, tarball, to_dir): # extracting the tarball tmpdir = tempfile.mkdtemp() log.warn('Extracting in %s', tmpdir) old_wd = os.getcwd() try: os.chdir(tmpdir) tar = tarfile.open(tarball) _extractall(tar) tar.close() # going in the directory subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0]) os.chdir(subdir) log.warn('Now working in %s', subdir) # building an egg log.warn('Building a Setuptools egg in %s', to_dir) _python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir) finally: os.chdir(old_wd) shutil.rmtree(tmpdir) # returning the result log.warn(egg) if not os.path.exists(egg): raise IOError('Could not build the egg.') def _do_download(version, download_base, to_dir, download_delay): egg = os.path.join(to_dir, 'setuptools-%s-py%d.%d.egg' % (version, sys.version_info[0], sys.version_info[1])) if not os.path.exists(egg): tarball = download_setuptools(version, download_base, to_dir, download_delay) _build_egg(egg, tarball, to_dir) sys.path.insert(0, egg) # Remove previously-imported pkg_resources if present (see # https://bitbucket.org/pypa/setuptools/pull-request/7/ for details). if 'pkg_resources' in sys.modules: del sys.modules['pkg_resources'] import setuptools setuptools.bootstrap_install_from = egg def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, download_delay=15): # making sure we use the absolute path to_dir = os.path.abspath(to_dir) was_imported = 'pkg_resources' in sys.modules or \ 'setuptools' in sys.modules try: import pkg_resources except ImportError: return _do_download(version, download_base, to_dir, download_delay) try: pkg_resources.require("setuptools>=" + version) return except pkg_resources.VersionConflict: e = sys.exc_info()[1] if was_imported: sys.stderr.write( "The required version of setuptools (>=%s) is not available,\n" "and can't be installed while this script is running. Please\n" "install a more recent version first, using\n" "'easy_install -U setuptools'." "\n\n(Currently using %r)\n" % (version, e.args[0])) sys.exit(2) else: del pkg_resources, sys.modules['pkg_resources'] # reload ok return _do_download(version, download_base, to_dir, download_delay) except pkg_resources.DistributionNotFound: return _do_download(version, download_base, to_dir, download_delay) def _clean_check(cmd, target): """ Run the command to download target. If the command fails, clean up before re-raising the error. """ try: subprocess.check_call(cmd) except subprocess.CalledProcessError: if os.access(target, os.F_OK): os.unlink(target) raise def download_file_powershell(url, target): """ Download the file at url to target using Powershell (which will validate trust). Raise an exception if the command cannot complete. """ target = os.path.abspath(target) cmd = [ 'powershell', '-Command', "(new-object System.Net.WebClient).DownloadFile(%(url)r, %(target)r)" % vars(), ] _clean_check(cmd, target) def has_powershell(): if platform.system() != 'Windows': return False cmd = ['powershell', '-Command', 'echo test'] devnull = open(os.path.devnull, 'wb') try: try: subprocess.check_call(cmd, stdout=devnull, stderr=devnull) except: return False finally: devnull.close() return True download_file_powershell.viable = has_powershell def download_file_curl(url, target): cmd = ['curl', url, '--silent', '--output', target] _clean_check(cmd, target) def has_curl(): cmd = ['curl', '--version'] devnull = open(os.path.devnull, 'wb') try: try: subprocess.check_call(cmd, stdout=devnull, stderr=devnull) except: return False finally: devnull.close() return True download_file_curl.viable = has_curl def download_file_wget(url, target): cmd = ['wget', url, '--quiet', '--output-document', target] _clean_check(cmd, target) def has_wget(): cmd = ['wget', '--version'] devnull = open(os.path.devnull, 'wb') try: try: subprocess.check_call(cmd, stdout=devnull, stderr=devnull) except: return False finally: devnull.close() return True download_file_wget.viable = has_wget def download_file_insecure(url, target): """ Use Python to download the file, even though it cannot authenticate the connection. """ try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen src = dst = None try: src = urlopen(url) # Read/write all in one block, so we don't create a corrupt file # if the download is interrupted. data = src.read() dst = open(target, "wb") dst.write(data) finally: if src: src.close() if dst: dst.close() download_file_insecure.viable = lambda: True def get_best_downloader(): downloaders = [ download_file_powershell, download_file_curl, download_file_wget, download_file_insecure, ] for dl in downloaders: if dl.viable(): return dl def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, delay=15, downloader_factory=get_best_downloader): """Download setuptools from a specified location and return its filename `version` should be a valid setuptools version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where the egg will be downloaded. `delay` is the number of seconds to pause before an actual download attempt. ``downloader_factory`` should be a function taking no arguments and returning a function for downloading a URL to a target. """ # making sure we use the absolute path to_dir = os.path.abspath(to_dir) tgz_name = "setuptools-%s.tar.gz" % version url = download_base + tgz_name saveto = os.path.join(to_dir, tgz_name) if not os.path.exists(saveto): # Avoid repeated downloads log.warn("Downloading %s", url) downloader = downloader_factory() downloader(url, saveto) return os.path.realpath(saveto) def _extractall(self, path=".", members=None): """Extract all members from the archive to the current working directory and set owner, modification time and permissions on directories afterwards. `path' specifies a different directory to extract to. `members' is optional and must be a subset of the list returned by getmembers(). """ import copy import operator from tarfile import ExtractError directories = [] if members is None: members = self for tarinfo in members: if tarinfo.isdir(): # Extract directories with a safe mode. directories.append(tarinfo) tarinfo = copy.copy(tarinfo) tarinfo.mode = 448 # decimal for oct 0700 self.extract(tarinfo, path) # Reverse sort directories. if sys.version_info < (2, 4): def sorter(dir1, dir2): return cmp(dir1.name, dir2.name) directories.sort(sorter) directories.reverse() else: directories.sort(key=operator.attrgetter('name'), reverse=True) # Set correct owner, mtime and filemode on directories. for tarinfo in directories: dirpath = os.path.join(path, tarinfo.name) try: self.chown(tarinfo, dirpath) self.utime(tarinfo, dirpath) self.chmod(tarinfo, dirpath) except ExtractError: e = sys.exc_info()[1] if self.errorlevel > 1: raise else: self._dbg(1, "tarfile: %s" % e) def _build_install_args(options): """ Build the arguments to 'python setup.py install' on the setuptools package """ install_args = [] if options.user_install: if sys.version_info < (2, 6): log.warn("--user requires Python 2.6 or later") raise SystemExit(1) install_args.append('--user') return install_args def _parse_args(): """ Parse the command line for options """ parser = optparse.OptionParser() parser.add_option( '--user', dest='user_install', action='store_true', default=False, help='install in user site package (requires Python 2.6 or later)') parser.add_option( '--download-base', dest='download_base', metavar="URL", default=DEFAULT_URL, help='alternative URL from where to download the setuptools package') parser.add_option( '--insecure', dest='downloader_factory', action='store_const', const=lambda: download_file_insecure, default=get_best_downloader, help='Use internal, non-validating downloader' ) options, args = parser.parse_args() # positional arguments are ignored return options def main(version=DEFAULT_VERSION): """Install or upgrade setuptools and EasyInstall""" options = _parse_args() tarball = download_setuptools(download_base=options.download_base, downloader_factory=options.downloader_factory) return _install(tarball, _build_install_args(options)) if __name__ == '__main__': sys.exit(main()) sunpy-0.6.3/astropy_helpers/ah_bootstrap.py0000644000175000017500000010650212662554110022054 0ustar stuartstuart00000000000000""" 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 # What follows are several import statements meant to deal with install-time # issues with either missing or misbehaving pacakges (including making sure # setuptools itself is installed): # 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() # Note: The following import is required as a workaround to # https://github.com/astropy/astropy-helpers/issues/89; if we don't import this # module now, it will get cleaned up after `run_setup` is called, but that will # later cause the TemporaryDirectory class defined in it to stop working when # used later on by setuptools try: import setuptools.py31compat except ImportError: pass # matplotlib can cause problems if it is imported from within a call of # run_setup(), because in some circumstances it will try to write to the user's # home directory, resulting in a SandboxViolation. See # https://github.com/matplotlib/matplotlib/pull/4165 # Making sure matplotlib, if it is available, is imported early in the setup # process can mitigate this (note importing matplotlib.pyplot has the same # issue) try: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot except: # Ignore if this fails for *any* reason* pass # End compatibility imports... # 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 from distutils import log from distutils.debug import DEBUG # 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 # A list of all the configuration options and their required types CFG_OPTIONS = [ ('auto_use', bool), ('path', str), ('download_if_needed', bool), ('index_url', str), ('use_git', bool), ('offline', bool), ('auto_upgrade', bool) ] 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 attributes, 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) # If this is a release then the .git directory will not exist so we # should not use git. git_dir_exists = os.path.exists(os.path.join(os.path.dirname(__file__), '.git')) if use_git is None and not git_dir_exists: use_git = False 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, argv=None): if argv is None: argv = sys.argv config = cls.parse_config() config.update(cls.parse_command_line(argv)) auto_use = config.pop('auto_use', False) bootstrapper = cls(**config) if auto_use: # Run the bootstrapper, otherwise the setup.py is using the old # use_astropy_helpers() interface, in which case it will run the # bootstrapper manually after reconfiguring it. bootstrapper.run() return bootstrapper @classmethod def parse_config(cls): 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, argv=None): if argv is None: argv = sys.argv 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 argv: config['use_git'] = False argv.remove('--no-git') if '--offline' in argv: config['offline'] = True argv.remove('--offline') return config def run(self): strategies = ['local_directory', 'local_file', 'index'] dist = None # First, remove any previously imported versions of astropy_helpers; # this is necessary for nested installs where one package's installer # is installing another package via setuptools.sandbox.run_setup, as in # the case of setup_requires for key in list(sys.modules): try: if key == PACKAGE_NAME or key.startswith(PACKAGE_NAME + '.'): del sys.modules[key] except AttributeError: # Sometimes mysterious non-string things can turn up in # sys.modules continue # 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)) # This is a bit hacky, but if astropy_helpers was loaded from a # directory/submodule its Distribution object gets a "precedence" of # "DEVELOP_DIST". However, in other cases it gets a precedence of # "EGG_DIST". However, when activing the distribution it will only be # placed early on sys.path if it is treated as an EGG_DIST, so always # do that dist = dist.clone(precedence=pkg_resources.EGG_DIST) # 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. try: pkg_resources.working_set.add(dist, replace=True) except TypeError: # Some (much) older versions of setuptools do not have the # replace=True option here. These versions are old enough that all # bets may be off anyways, but it's easy enough to work around just # in case... if dist.key in pkg_resources.working_set.by_key: del pkg_resources.working_set.by_key[dist.key] pkg_resources.working_set.add(dist) @property def config(self): """ A `dict` containing the options this `_Bootstrapper` was configured with. """ return dict((optname, getattr(self, optname)) for optname, _ in CFG_OPTIONS if hasattr(self, optname)) 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 None 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 straightforward 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) next_version = _next_version(dist.parsed_version) req = pkg_resources.Requirement.parse( '{0}>{1},<{2}'.format(DIST_NAME, dist.version, next_version)) 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 further 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 unknown 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 syntax (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) def _next_version(version): """ Given a parsed version from pkg_resources.parse_version, returns a new version string with the next minor version. Examples ======== >>> _next_version(pkg_resources.parse_version('1.2.3')) '1.3.0' """ if hasattr(version, 'base_version'): # New version parsing from setuptools >= 8.0 if version.base_version: parts = version.base_version.split('.') else: parts = [] else: parts = [] for part in version: if part.startswith('*'): break parts.append(part) parts = [int(p) for p in parts] if len(parts) < 3: parts += [0] * (3 - len(parts)) major, minor, micro = parts[:3] return '{0}.{1}.{2}'.format(major, minor + 1, 0) 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() BOOTSTRAPPER = _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 initialized 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 BOOTSTRAPPER config = BOOTSTRAPPER.config config.update(**kwargs) # Create a new bootstrapper with the updated configuration and run it BOOTSTRAPPER = _Bootstrapper(**config) BOOTSTRAPPER.run() sunpy-0.6.3/astropy_helpers/tox.ini0000644000175000017500000000045012622602515020322 0ustar stuartstuart00000000000000[tox] envlist = py26,py27,py32,py33,py34 [testenv] deps = pytest numpy Cython Sphinx==1.2.3 # Note: Sphinx is required to run the sphinx.ext tests commands = py.test {posargs} sitepackages = False [testenv:py32] deps = pygments<=1.9 Jinja2<2.7 {[testenv]deps} sunpy-0.6.3/astropy_helpers/licenses/0000755000175000017500000000000012675276745020641 5ustar stuartstuart00000000000000sunpy-0.6.3/astropy_helpers/licenses/LICENSE_COPYBUTTON.rst0000644000175000017500000000471112622602515024222 0ustar stuartstuart00000000000000Copyright 2014 Python Software Foundation License: PSF PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 -------------------------------------------- . 1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and the Individual or Organization ("Licensee") accessing and otherwise using this software ("Python") in source or binary form and its associated documentation. . 2. Subject to the terms and conditions of this License Agreement, PSF hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use Python alone or in any derivative version, provided, however, that PSF's License Agreement and PSF's notice of copyright, i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Python Software Foundation; All Rights Reserved" are retained in Python alone or in any derivative version prepared by Licensee. . 3. In the event Licensee prepares a derivative work that is based on or incorporates Python or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to Python. . 4. PSF is making Python available to Licensee on an "AS IS" basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. . 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. . 6. This License Agreement will automatically terminate upon a material breach of its terms and conditions. . 7. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between PSF and Licensee. This License Agreement does not grant permission to use PSF trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party. . 8. By copying, installing or otherwise using Python, Licensee agrees to be bound by the terms and conditions of this License Agreement. sunpy-0.6.3/astropy_helpers/licenses/LICENSE_NUMPYDOC.rst0000644000175000017500000001350712622602515023755 0ustar stuartstuart00000000000000------------------------------------------------------------------------------- The files - numpydoc.py - docscrape.py - docscrape_sphinx.py - phantom_import.py have the following license: Copyright (C) 2008 Stefan van der Walt , Pauli Virtanen 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. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. ------------------------------------------------------------------------------- The files - compiler_unparse.py - comment_eater.py - traitsdoc.py have the following license: This software is OSI Certified Open Source Software. OSI Certified is a certification mark of the Open Source Initiative. Copyright (c) 2006, Enthought, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of Enthought, Inc. 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. ------------------------------------------------------------------------------- The file - plot_directive.py originates from Matplotlib (http://matplotlib.sf.net/) which has the following license: Copyright (c) 2002-2008 John D. Hunter; All Rights Reserved. 1. This LICENSE AGREEMENT is between John D. Hunter (ā€œJDHā€), and the Individual or Organization (ā€œLicenseeā€) accessing and otherwise using matplotlib software in source or binary form and its associated documentation. 2. Subject to the terms and conditions of this License Agreement, JDH hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use matplotlib 0.98.3 alone or in any derivative version, provided, however, that JDH’s License Agreement and JDH’s notice of copyright, i.e., ā€œCopyright (c) 2002-2008 John D. Hunter; All Rights Reservedā€ are retained in matplotlib 0.98.3 alone or in any derivative version prepared by Licensee. 3. In the event Licensee prepares a derivative work that is based on or incorporates matplotlib 0.98.3 or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to matplotlib 0.98.3. 4. JDH is making matplotlib 0.98.3 available to Licensee on an ā€œAS ISā€ basis. JDH MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, JDH MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF MATPLOTLIB 0.98.3 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 5. JDH SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF MATPLOTLIB 0.98.3 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING MATPLOTLIB 0.98.3, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 6. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 7. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between JDH and Licensee. This License Agreement does not grant permission to use JDH trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party. 8. By copying, installing or otherwise using matplotlib 0.98.3, Licensee agrees to be bound by the terms and conditions of this License Agreement. sunpy-0.6.3/astropy_helpers/CHANGES.rst0000644000175000017500000003126512662554110020622 0ustar stuartstuart00000000000000astropy-helpers Changelog ========================= 1.1.1 (2015-12-23) ------------------ - Fixed crash in build with ``AttributeError: cython_create_listing`` with older versions of setuptools. [#209] 1.1 (2015-12-10) ---------------- - The original ``AstropyTest`` class in ``astropy_helpers``, which implements the ``setup.py test`` command, is deprecated in favor of moving the implementation of that command closer to the actual Astropy test runner in ``astropy.tests``. Now a dummy ``test`` command is provided solely for informing users that they need ``astropy`` installed to run the tests (however, the previous, now deprecated implementation is still provided and continues to work with older versions of Astropy). See the related issue for more details. [#184] - Added a useful new utility function to ``astropy_helpers.utils`` called ``find_data_files``. This is similar to the ``find_packages`` function in setuptools in that it can be used to search a package for data files (matching a pattern) that can be passed to the ``package_data`` argument for ``setup()``. See the docstring to ``astropy_helpers.utils.find_data_files`` for more details. [#42] - The ``astropy_helpers`` module now sets the global ``_ASTROPY_SETUP_`` flag upon import (from within a ``setup.py``) script, so it's not necessary to have this in the ``setup.py`` script explicitly. If in doubt though, there's no harm in setting it twice. Putting it in ``astropy_helpers`` just ensures that any other imports that occur during build will have this flag set. [#191] - It is now possible to use Cython as a ``setup_requires`` build requirement, and still build Cython extensions even if Cython wasn't available at the beginning of the build processes (that is, is automatically downloaded via setuptools' processing of ``setup_requires``). [#185] - Moves the ``adjust_compiler`` check into the ``build_ext`` command itself, so it's only used when actually building extension modules. This also deprecates the stand-alone ``adjust_compiler`` function. [#76] - When running the ``build_sphinx`` / ``build_docs`` command with the ``-w`` option, the output from Sphinx is streamed as it runs instead of silently buffering until the doc build is complete. [#197] 1.0.6 (2015-12-04) ------------------ - Fixed bug where running ``./setup.py build_sphinx`` could return successfully even when the build was not successful (and should have returned a non-zero error code). [#199] 1.0.5 (2015-10-02) ------------------ - Fixed a regression in the ``./setup.py test`` command that was introduced in v1.0.4. 1.0.4 (2015-10-02) ------------------ - Fixed issue with the sphinx documentation css where the line numbers for code blocks were not aligned with the code. [#179] - Fixed crash that could occur when trying to build Cython extension modules when Cython isn't installed. Normally this still results in a failed build, but was supposed to provide a useful error message rather than crash outright (this was a regression introduced in v1.0.3). [#181] - Fixed a crash that could occur on Python 3 when a working C compiler isn't found. [#182] - Quieted warnings about deprecated Numpy API in Cython extensions, when building Cython extensions against Numpy >= 1.7. [#183] - Improved support for py.test >= 2.7--running the ``./setup.py test`` command now copies all doc pages into the temporary test directory as well, so that all test files have a "common root directory". [#189] 1.0.3 (2015-07-22) ------------------ - Added workaround for sphinx-doc/sphinx#1843, a but in Sphinx which prevented descriptor classes with a custom metaclass from being documented correctly. [#158] - Added an alias for the ``./setup.py build_sphinx`` command as ``./setup.py build_docs`` which, to a new contributor, should hopefully be less cryptic. [#161] - The fonts in graphviz diagrams now match the font of the HTML content. [#169] - When the documentation is built on readthedocs.org, MathJax will be used for math rendering. When built elsewhere, the "pngmath" extension is still used for math rendering. [#170] - Fix crash when importing astropy_helpers when running with ``python -OO`` [#171] - The ``build`` and ``build_ext`` stages now correctly recognize the presence of C++ files in Cython extensions (previously only vanilla C worked). [#173] 1.0.2 (2015-04-02) ------------------ - Various fixes enabling the astropy-helpers Sphinx build command and Sphinx extensions to work with Sphinx 1.3. [#148] - More improvement to the ability to handle multiple versions of astropy-helpers being imported in the same Python interpreter session in the (somewhat rare) case of nested installs. [#147] - To better support high resolution displays, use SVG for the astropy logo and linkout image, falling back to PNGs for browsers that support it. [#150, #151] - Improve ``setup_helpers.get_compiler_version`` to work with more compilers, and to return more info. This will help fix builds of Astropy on less common compilers, like Sun C. [#153] 1.0.1 (2015-03-04) ------------------ - Released in concert with v0.4.8 to address the same issues. - Improved the ``ah_bootstrap`` script's ability to override existing installations of astropy-helpers with new versions in the context of installing multiple packages simultaneously within the same Python interpreter (e.g. when one package has in its ``setup_requires`` another package that uses a different version of astropy-helpers. [#144] - Added a workaround to an issue in matplotlib that can, in rare cases, lead to a crash when installing packages that import matplotlib at build time. [#144] 0.4.8 (2015-03-04) ------------------ - Improved the ``ah_bootstrap`` script's ability to override existing installations of astropy-helpers with new versions in the context of installing multiple packages simultaneously within the same Python interpreter (e.g. when one package has in its ``setup_requires`` another package that uses a different version of astropy-helpers. [#144] - Added a workaround to an issue in matplotlib that can, in rare cases, lead to a crash when installing packages that import matplotlib at build time. [#144] 1.0 (2015-02-17) ---------------- - Added new pre-/post-command hook points for ``setup.py`` commands. Now any package can define code to run before and/or after any ``setup.py`` command without having to manually subclass that command by adding ``pre__hook`` and ``post__hook`` callables to the package's ``setup_package.py`` module. See the PR for more details. [#112] - The following objects in the ``astropy_helpers.setup_helpers`` module have been relocated: - ``get_dummy_distribution``, ``get_distutils_*``, ``get_compiler_option``, ``add_command_option``, ``is_distutils_display_option`` -> ``astropy_helpers.distutils_helpers`` - ``should_build_with_cython``, ``generate_build_ext_command`` -> ``astropy_helpers.commands.build_ext`` - ``AstropyBuildPy`` -> ``astropy_helpers.commands.build_py`` - ``AstropyBuildSphinx`` -> ``astropy_helpers.commands.build_sphinx`` - ``AstropyInstall`` -> ``astropy_helpers.commands.install`` - ``AstropyInstallLib`` -> ``astropy_helpers.commands.install_lib`` - ``AstropyRegister`` -> ``astropy_helpers.commands.register`` - ``get_pkg_version_module`` -> ``astropy_helpers.version_helpers`` - ``write_if_different``, ``import_file``, ``get_numpy_include_path`` -> ``astropy_helpers.utils`` All of these are "soft" deprecations in the sense that they are still importable from ``astropy_helpers.setup_helpers`` for now, and there is no (easy) way to produce deprecation warnings when importing these objects from ``setup_helpers`` rather than directly from the modules they are defined in. But please consider updating any imports to these objects. [#110] - Use of the ``astropy.sphinx.ext.astropyautosummary`` extension is deprecated for use with Sphinx < 1.2. Instead it should suffice to remove this extension for the ``extensions`` list in your ``conf.py`` and add the stock ``sphinx.ext.autosummary`` instead. [#131] 0.4.7 (2015-02-17) ------------------ - Fixed incorrect/missing git hash being added to the generated ``version.py`` when creating a release. [#141] 0.4.6 (2015-02-16) ------------------ - Fixed problems related to the automatically generated _compiler module not being created properly. [#139] 0.4.5 (2015-02-11) ------------------ - Fixed an issue where ah_bootstrap.py could blow up when astropy_helper's version number is 1.0. - Added a workaround for documentation of properties in the rare case where the class's metaclass has a property of the same name. [#130] - Fixed an issue on Python 3 where importing a package using astropy-helper's generated version.py module would crash when the current working directory is an empty git repository. [#114] - Fixed an issue where the "revision count" appended to .dev versions by the generated version.py did not accurately reflect the revision count for the package it belongs to, and could be invalid if the current working directory is an unrelated git repository. [#107] - Likewise, fixed a confusing warning message that could occur in the same circumstances as the above issue. [#121] 0.4.4 (2014-12-31) ------------------ - More improvements for building the documentation using Python 3.x. [#100] - Additional minor fixes to Python 3 support. [#115] - Updates to support new test features in Astropy [#92, #106] 0.4.3 (2014-10-22) ------------------ - The generated ``version.py`` file now preserves the git hash of installed copies of the package as well as when building a source distribution. That is, the git hash of the changeset that was installed/released is preserved. [#87] - In smart resolver add resolution for class links when they exist in the intersphinx inventory, but not the mapping of the current package (e.g. when an affiliated package uses an astropy core class of which "actual" and "documented" location differs) [#88] - Fixed a bug that could occur when running ``setup.py`` for the first time in a repository that uses astropy-helpers as a submodule: ``AttributeError: 'NoneType' object has no attribute 'mkdtemp'`` [#89] - Fixed a bug where optional arguments to the ``doctest-skip`` Sphinx directive were sometimes being left in the generated documentation output. [#90] - Improved support for building the documentation using Python 3.x. [#96] - Avoid error message if .git directory is not present. [#91] 0.4.2 (2014-08-09) ------------------ - Fixed some CSS issues in generated API docs. [#69] - Fixed the warning message that could be displayed when generating a version number with some older versions of git. [#77] - Fixed automodsumm to work with new versions of Sphinx (>= 1.2.2). [#80] 0.4.1 (2014-08-08) ------------------ - Fixed git revision count on systems with git versions older than v1.7.2. [#70] - Fixed display of warning text when running a git command fails (previously the output of stderr was not being decoded properly). [#70] - The ``--offline`` flag to ``setup.py`` understood by ``ah_bootstrap.py`` now also prevents git from going online to fetch submodule updates. [#67] - The Sphinx extension for converting issue numbers to links in the changelog now supports working on arbitrary pages via a new ``conf.py`` setting: ``changelog_links_docpattern``. By default it affects the ``changelog`` and ``whatsnew`` pages in one's Sphinx docs. [#61] - Fixed crash that could result from users with missing/misconfigured locale settings. [#58] - The font used for code examples in the docs is now the system-defined ``monospace`` font, rather than ``Minaco``, which is not available on all platforms. [#50] 0.4 (2014-07-15) ---------------- - Initial release of astropy-helpers. See `APE4 `_ for details of the motivation and design of this package. - The ``astropy_helpers`` package replaces the following modules in the ``astropy`` package: - ``astropy.setup_helpers`` -> ``astropy_helpers.setup_helpers`` - ``astropy.version_helpers`` -> ``astropy_helpers.version_helpers`` - ``astropy.sphinx`` - > ``astropy_helpers.sphinx`` These modules should be considered deprecated in ``astropy``, and any new, non-critical changes to those modules will be made in ``astropy_helpers`` instead. Affiliated packages wishing to make use those modules (as in the Astropy package-template) should use the versions from ``astropy_helpers`` instead, and include the ``ah_bootstrap.py`` script in their project, for bootstrapping the ``astropy_helpers`` package in their setup.py script. sunpy-0.6.3/astropy_helpers/astropy_helpers/0000755000175000017500000000000012675276744022256 5ustar stuartstuart00000000000000sunpy-0.6.3/astropy_helpers/astropy_helpers/distutils_helpers.py0000644000175000017500000001735512622602515026366 0ustar stuartstuart00000000000000""" This module contains various utilities for introspecting the distutils module and the setup process. Some of these utilities require the `astropy_helpers.setup_helpers.register_commands` function to be called first, as it will affect introspection of setuptools command-line arguments. Other utilities in this module do not have that restriction. """ import os import sys from distutils import ccompiler from distutils.dist import Distribution from distutils.errors import DistutilsError from .utils import silence # This function, and any functions that call it, require the setup in # `astropy_helpers.setup_helpers.register_commands` to be run first. def get_dummy_distribution(): """ Returns a distutils Distribution object used to instrument the setup environment before calling the actual setup() function. """ from .setup_helpers import _module_state if _module_state['registered_commands'] is None: raise RuntimeError( 'astropy_helpers.setup_helpers.register_commands() must be ' 'called before using ' 'astropy_helpers.setup_helpers.get_dummy_distribution()') # Pre-parse the Distutils command-line options and config files to if # the option is set. dist = Distribution({'script_name': os.path.basename(sys.argv[0]), 'script_args': sys.argv[1:]}) dist.cmdclass.update(_module_state['registered_commands']) with silence(): try: dist.parse_config_files() dist.parse_command_line() except (DistutilsError, AttributeError, SystemExit): # Let distutils handle DistutilsErrors itself AttributeErrors can # get raise for ./setup.py --help SystemExit can be raised if a # display option was used, for example pass return dist def get_distutils_option(option, commands): """ 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. """ dist = get_dummy_distribution() for cmd in commands: cmd_opts = dist.command_options.get(cmd) if cmd_opts is not None and option in cmd_opts: return cmd_opts[option][1] else: return None def get_distutils_build_option(option): """ 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. """ return get_distutils_option(option, ['build', 'build_ext', 'build_clib']) def get_distutils_install_option(option): """ 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. """ return get_distutils_option(option, ['install']) def get_distutils_build_or_install_option(option): """ 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. """ return get_distutils_option(option, ['build', 'build_ext', 'build_clib', 'install']) def get_compiler_option(): """ Determines the compiler that will be used to build extension modules. Returns ------- compiler : str The compiler option specified for the build, build_ext, or build_clib command; or the default compiler for the platform if none was specified. """ compiler = get_distutils_build_option('compiler') if compiler is None: return ccompiler.get_default_compiler() return compiler def add_command_option(command, name, doc, is_bool=False): """ 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. """ dist = get_dummy_distribution() cmdcls = dist.get_command_class(command) if (hasattr(cmdcls, '_astropy_helpers_options') and name in cmdcls._astropy_helpers_options): return attr = name.replace('-', '_') if hasattr(cmdcls, attr): raise RuntimeError( '{0!r} already has a {1!r} class attribute, barring {2!r} from ' 'being usable as a custom option name.'.format(cmdcls, attr, name)) for idx, cmd in enumerate(cmdcls.user_options): if cmd[0] == name: log.warn('Overriding existing {0!r} option ' '{1!r}'.format(command, name)) del cmdcls.user_options[idx] if name in cmdcls.boolean_options: cmdcls.boolean_options.remove(name) break cmdcls.user_options.append((name, None, doc)) if is_bool: cmdcls.boolean_options.append(name) # Distutils' command parsing requires that a command object have an # attribute with the same name as the option (with '-' replaced with '_') # in order for that option to be recognized as valid setattr(cmdcls, attr, None) # This caches the options added through add_command_option so that if it is # run multiple times in the same interpreter repeated adds are ignored # (this way we can still raise a RuntimeError if a custom option overrides # a built-in option) if not hasattr(cmdcls, '_astropy_helpers_options'): cmdcls._astropy_helpers_options = set([name]) else: cmdcls._astropy_helpers_options.add(name) def get_distutils_display_options(): """ 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 -- """ short_display_opts = set('-' + o[1] for o in Distribution.display_options if o[1]) long_display_opts = set('--' + o[0] for o in Distribution.display_options) # Include -h and --help which are not explicitly listed in # Distribution.display_options (as they are handled by optparse) short_display_opts.add('-h') long_display_opts.add('--help') # This isn't the greatest approach to hardcode these commands. # However, there doesn't seem to be a good way to determine # whether build *will be* run as part of the command at this # phase. display_commands = set([ 'clean', 'register', 'setopt', 'saveopts', 'egg_info', 'alias']) return short_display_opts.union(long_display_opts.union(display_commands)) def is_distutils_display_option(): """ Returns True if sys.argv contains any of the distutils display options such as --version or --name. """ display_options = get_distutils_display_options() return bool(set(sys.argv[1:]).intersection(display_options)) sunpy-0.6.3/astropy_helpers/astropy_helpers/tests/0000755000175000017500000000000012675276745023421 5ustar stuartstuart00000000000000sunpy-0.6.3/astropy_helpers/astropy_helpers/tests/test_git_helpers.py0000644000175000017500000001627412622602515027325 0ustar stuartstuart00000000000000import glob import imp import os import pkgutil import re import sys import tarfile from . import * PY3 = sys.version_info[0] == 3 if PY3: _text_type = str else: _text_type = unicode _DEV_VERSION_RE = re.compile(r'\d+\.\d+(?:\.\d+)?\.dev(\d+)') TEST_VERSION_SETUP_PY = """\ #!/usr/bin/env python from setuptools import setup NAME = '_eva_' VERSION = {version!r} RELEASE = 'dev' not in VERSION from astropy_helpers.git_helpers import get_git_devstr from astropy_helpers.version_helpers import generate_version_py if not RELEASE: VERSION += get_git_devstr(False) generate_version_py(NAME, VERSION, RELEASE, False, uses_git=not RELEASE) setup(name=NAME, version=VERSION, packages=['_eva_']) """ TEST_VERSION_INIT = """\ try: from .version import version as __version__ from .version import githash as __githash__ except ImportError: __version__ = __githash__ = '' """ @pytest.fixture def version_test_package(tmpdir, request): def make_test_package(version='42.42.dev'): test_package = tmpdir.mkdir('test_package') test_package.join('setup.py').write( TEST_VERSION_SETUP_PY.format(version=version)) test_package.mkdir('_eva_').join('__init__.py').write(TEST_VERSION_INIT) with test_package.as_cwd(): run_cmd('git', ['init']) run_cmd('git', ['add', '--all']) run_cmd('git', ['commit', '-m', 'test package']) if '' in sys.path: sys.path.remove('') sys.path.insert(0, '') def finalize(): cleanup_import('_eva_') request.addfinalizer(finalize) return test_package return make_test_package def test_update_git_devstr(version_test_package, capsys): """Tests that the commit number in the package's version string updates after git commits even without re-running setup.py. """ # We have to call version_test_package to actually create the package test_pkg = version_test_package() with test_pkg.as_cwd(): run_setup('setup.py', ['--version']) stdout, stderr = capsys.readouterr() version = stdout.strip() m = _DEV_VERSION_RE.match(version) assert m, ( "Stdout did not match the version string pattern:" "\n\n{0}\n\nStderr:\n\n{1}".format(stdout, stderr)) revcount = int(m.group(1)) import _eva_ assert _eva_.__version__ == version # Make a silly git commit with open('.test', 'w'): pass run_cmd('git', ['add', '.test']) run_cmd('git', ['commit', '-m', 'test']) import _eva_.version imp.reload(_eva_.version) # Previously this checked packagename.__version__, but in order for that to # be updated we also have to re-import _astropy_init which could be tricky. # Checking directly that the packagename.version module was updated is # sufficient: m = _DEV_VERSION_RE.match(_eva_.version.version) assert m assert int(m.group(1)) == revcount + 1 # This doesn't test astropy_helpers.get_helpers.update_git_devstr directly # since a copy of that function is made in packagename.version (so that it # can work without astropy_helpers installed). In order to get test # coverage on the actual astropy_helpers copy of that function just call it # directly and compare to the value in packagename from astropy_helpers.git_helpers import update_git_devstr newversion = update_git_devstr(version, path=str(test_pkg)) assert newversion == _eva_.version.version def test_version_update_in_other_repos(version_test_package, tmpdir): """ Regression test for https://github.com/astropy/astropy-helpers/issues/114 and for https://github.com/astropy/astropy-helpers/issues/107 """ test_pkg = version_test_package() with test_pkg.as_cwd(): run_setup('setup.py', ['build']) # Add the path to the test package to sys.path for now sys.path.insert(0, str(test_pkg)) try: import _eva_ m = _DEV_VERSION_RE.match(_eva_.__version__) assert m correct_revcount = int(m.group(1)) with tmpdir.as_cwd(): testrepo = tmpdir.mkdir('testrepo') testrepo.chdir() # Create an empty git repo run_cmd('git', ['init']) import _eva_.version imp.reload(_eva_.version) m = _DEV_VERSION_RE.match(_eva_.version.version) assert m assert int(m.group(1)) == correct_revcount correct_revcount = int(m.group(1)) # Add several commits--more than the revcount for the _eva_ package for idx in range(correct_revcount + 5): test_filename = '.test' + str(idx) testrepo.ensure(test_filename) run_cmd('git', ['add', test_filename]) run_cmd('git', ['commit', '-m', 'A message']) import _eva_.version imp.reload(_eva_.version) m = _DEV_VERSION_RE.match(_eva_.version.version) assert m assert int(m.group(1)) == correct_revcount correct_revcount = int(m.group(1)) finally: sys.path.remove(str(test_pkg)) @pytest.mark.parametrize('version', ['1.0.dev', '1.0']) def test_installed_git_version(version_test_package, version, tmpdir, capsys): """ Test for https://github.com/astropy/astropy-helpers/issues/87 Ensures that packages installed with astropy_helpers have a correct copy of the git hash of the installed commit. """ # To test this, it should suffice to build a source dist, unpack it # somewhere outside the git repository, and then do a build and import # from the build directory--no need to "install" as such test_pkg = version_test_package(version) with test_pkg.as_cwd(): run_setup('setup.py', ['build']) try: import _eva_ githash = _eva_.__githash__ assert githash and isinstance(githash, _text_type) # Ensure that it does in fact look like a git hash and not some # other arbitrary string assert re.match(r'[0-9a-f]{40}', githash) finally: cleanup_import('_eva_') run_setup('setup.py', ['sdist', '--dist-dir=dist', '--formats=gztar']) tgzs = glob.glob(os.path.join('dist', '*.tar.gz')) assert len(tgzs) == 1 tgz = test_pkg.join(tgzs[0]) build_dir = tmpdir.mkdir('build_dir') tf = tarfile.open(str(tgz), mode='r:gz') tf.extractall(str(build_dir)) with build_dir.as_cwd(): pkg_dir = glob.glob('_eva_-*')[0] os.chdir(pkg_dir) run_setup('setup.py', ['build']) try: import _eva_ loader = pkgutil.get_loader('_eva_') # Ensure we are importing the 'packagename' that was just unpacked # into the build_dir if sys.version_info[:2] != (3, 3): # Skip this test on Python 3.3 wherein the SourceFileLoader # has a bug where get_filename() does not return an absolute # path assert loader.get_filename().startswith(str(build_dir)) assert _eva_.__githash__ == githash finally: cleanup_import('_eva_') sunpy-0.6.3/astropy_helpers/astropy_helpers/tests/__init__.py0000644000175000017500000001121512622602515025506 0ustar stuartstuart00000000000000import os import subprocess as sp import sys from setuptools import sandbox import pytest from ..utils import extends_doc PACKAGE_DIR = os.path.dirname(__file__) def run_cmd(cmd, args, path=None, raise_error=True): """ Runs a shell command with the given argument list. Changes directory to ``path`` if given, otherwise runs the command in the current directory. Returns a 3-tuple of (stdout, stderr, exit code) If ``raise_error=True`` raise an exception on non-zero exit codes. """ if path is not None: # Transparently support py.path objects path = str(path) p = sp.Popen([cmd] + list(args), stdout=sp.PIPE, stderr=sp.PIPE, cwd=path) streams = tuple(s.decode('latin1').strip() for s in p.communicate()) return_code = p.returncode if raise_error and return_code != 0: raise RuntimeError( "The command `{0}` with args {1!r} exited with code {2}.\n" "Stdout:\n\n{3}\n\nStderr:\n\n{4}".format( cmd, list(args), return_code, streams[0], streams[1])) return streams + (return_code,) @extends_doc(sandbox.run_setup) def run_setup(*args, **kwargs): """ In Python 3, on MacOS X, the import cache has to be invalidated otherwise new extensions built with ``run_setup`` do not always get picked up. """ try: return sandbox.run_setup(*args, **kwargs) finally: if sys.version_info[:2] >= (3, 3): import importlib importlib.invalidate_caches() @pytest.fixture(scope='function', autouse=True) def reset_setup_helpers(request): """ Saves and restores the global state of the astropy_helpers.setup_helpers module between tests. """ mod = __import__('astropy_helpers.setup_helpers', fromlist=['']) old_state = mod._module_state.copy() def finalizer(old_state=old_state): mod = sys.modules.get('astropy_helpers.setup_helpers') if mod is not None: mod._module_state.update(old_state) request.addfinalizer(finalizer) @pytest.fixture(scope='function', autouse=True) def reset_distutils_log(): """ This is a setup/teardown fixture that ensures the log-level of the distutils log is always set to a default of WARN, since different settings could affect tests that check the contents of stdout. """ from distutils import log log.set_threshold(log.WARN) @pytest.fixture(scope='module', autouse=True) def fix_hide_setuptools(): """ Workaround for https://github.com/astropy/astropy-helpers/issues/124 In setuptools 10.0 run_setup was changed in such a way that it sweeps away the existing setuptools import before running the setup script. In principle this is nice, but in the practice of testing astropy_helpers this is problematic since we're trying to test code that has already been imported during the testing process, and which relies on the setuptools module that was already in use. """ if hasattr(sandbox, 'hide_setuptools'): sandbox.hide_setuptools = lambda: None TEST_PACKAGE_SETUP_PY = """\ #!/usr/bin/env python from setuptools import setup NAME = 'astropy-helpers-test' VERSION = {version!r} setup(name=NAME, version=VERSION, packages=['_astropy_helpers_test_'], zip_safe=False) """ @pytest.fixture def testpackage(tmpdir, version='0.1'): """ This fixture creates a simplified package called _astropy_helpers_test_ used primarily for testing ah_boostrap, but without using the astropy_helpers package directly and getting it confused with the astropy_helpers package already under test. """ source = tmpdir.mkdir('testpkg') with source.as_cwd(): source.mkdir('_astropy_helpers_test_') init = source.join('_astropy_helpers_test_', '__init__.py') init.write('__version__ = {0!r}'.format(version)) setup_py = TEST_PACKAGE_SETUP_PY.format(version=version) source.join('setup.py').write(setup_py) # Make the new test package into a git repo run_cmd('git', ['init']) run_cmd('git', ['add', '--all']) run_cmd('git', ['commit', '-m', 'test package']) return source def cleanup_import(package_name): """Remove all references to package_name from sys.modules""" for k in list(sys.modules): if not isinstance(k, str): # Some things will actually do this =_= continue elif k.startswith('astropy_helpers.tests'): # Don't delete imported test modules or else the tests will break, # badly continue if k == package_name or k.startswith(package_name + '.'): del sys.modules[k] sunpy-0.6.3/astropy_helpers/astropy_helpers/tests/test_setup_helpers.py0000644000175000017500000003626512662554110027705 0ustar stuartstuart00000000000000import contextlib import shutil import stat import sys from textwrap import dedent from setuptools import Distribution from ..setup_helpers import get_package_info, register_commands from ..commands import build_ext from . import * def _extension_test_package(tmpdir, request, extension_type='c'): """Creates a simple test package with an extension module.""" test_pkg = tmpdir.mkdir('test_pkg') test_pkg.mkdir('_eva_').ensure('__init__.py') # TODO: It might be later worth making this particular test package into a # reusable fixture for other build_ext tests if extension_type in ('c', 'both'): # A minimal C extension for testing test_pkg.join('_eva_', 'unit01.c').write(dedent("""\ #include #ifndef PY3K #if PY_MAJOR_VERSION >= 3 #define PY3K 1 #else #define PY3K 0 #endif #endif #if PY3K static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "unit01", NULL, -1, NULL }; PyMODINIT_FUNC PyInit_unit01(void) { return PyModule_Create(&moduledef); } #else PyMODINIT_FUNC initunit01(void) { Py_InitModule3("unit01", NULL, NULL); } #endif """)) if extension_type in ('pyx', 'both'): # A minimal Cython extension for testing test_pkg.join('_eva_', 'unit02.pyx').write(dedent("""\ print("Hello cruel angel.") """)) if extension_type == 'c': extensions = ['unit01.c'] elif extension_type == 'pyx': extensions = ['unit02.pyx'] elif extension_type == 'both': extensions = ['unit01.c', 'unit02.pyx'] extensions_list = [ "Extension('_eva_.{0}', [join('_eva_', '{1}')])".format( os.path.splitext(extension)[0], extension) for extension in extensions] test_pkg.join('_eva_', 'setup_package.py').write(dedent("""\ from setuptools import Extension from os.path import join def get_extensions(): return [{0}] """.format(', '.join(extensions_list)))) test_pkg.join('setup.py').write(dedent("""\ from os.path import join from setuptools import setup from astropy_helpers.setup_helpers import register_commands from astropy_helpers.setup_helpers import get_package_info from astropy_helpers.version_helpers import generate_version_py NAME = '_eva_' VERSION = '0.1' RELEASE = True cmdclassd = register_commands(NAME, VERSION, RELEASE) generate_version_py(NAME, VERSION, RELEASE, False, False) package_info = get_package_info() setup( name=NAME, version=VERSION, cmdclass=cmdclassd, **package_info ) """)) if '' in sys.path: sys.path.remove('') sys.path.insert(0, '') def finalize(): cleanup_import('_eva_') request.addfinalizer(finalize) return test_pkg @pytest.fixture def extension_test_package(tmpdir, request): return _extension_test_package(tmpdir, request, extension_type='both') @pytest.fixture def c_extension_test_package(tmpdir, request): return _extension_test_package(tmpdir, request, extension_type='c') @pytest.fixture def pyx_extension_test_package(tmpdir, request): return _extension_test_package(tmpdir, request, extension_type='pyx') def test_cython_autoextensions(tmpdir): """ Regression test for https://github.com/astropy/astropy-helpers/pull/19 Ensures that Cython extensions in sub-packages are discovered and built only once. """ # Make a simple test package test_pkg = tmpdir.mkdir('test_pkg') test_pkg.mkdir('yoda').mkdir('luke') test_pkg.ensure('yoda', '__init__.py') test_pkg.ensure('yoda', 'luke', '__init__.py') test_pkg.join('yoda', 'luke', 'dagobah.pyx').write( """def testfunc(): pass""") # Required, currently, for get_package_info to work register_commands('yoda', '0.0', False, srcdir=str(test_pkg)) package_info = get_package_info(str(test_pkg)) assert len(package_info['ext_modules']) == 1 assert package_info['ext_modules'][0].name == 'yoda.luke.dagobah' def test_compiler_module(c_extension_test_package): """ Test ensuring that the compiler module is built and installed for packages that have extension modules. """ test_pkg = c_extension_test_package install_temp = test_pkg.mkdir('install_temp') with test_pkg.as_cwd(): # This is one of the simplest ways to install just a package into a # test directory run_setup('setup.py', ['install', '--single-version-externally-managed', '--install-lib={0}'.format(install_temp), '--record={0}'.format(install_temp.join('record.txt'))]) with install_temp.as_cwd(): import _eva_ # Make sure we imported the _eva_ package from the correct place dirname = os.path.abspath(os.path.dirname(_eva_.__file__)) assert dirname == str(install_temp.join('_eva_')) import _eva_._compiler import _eva_.version assert _eva_.version.compiler == _eva_._compiler.compiler assert _eva_.version.compiler != 'unknown' def test_no_cython_buildext(c_extension_test_package, monkeypatch): """ Regression test for https://github.com/astropy/astropy-helpers/pull/35 This tests the custom build_ext command installed by astropy_helpers when used with a project that has no Cython extensions (but does have one or more normal C extensions). """ test_pkg = c_extension_test_package # In order for this test to test the correct code path we need to fool # build_ext into thinking we don't have Cython installed monkeypatch.setattr(build_ext, 'should_build_with_cython', lambda *args: False) with test_pkg.as_cwd(): run_setup('setup.py', ['build_ext', '--inplace']) sys.path.insert(0, str(test_pkg)) try: import _eva_.unit01 dirname = os.path.abspath(os.path.dirname(_eva_.unit01.__file__)) assert dirname == str(test_pkg.join('_eva_')) finally: sys.path.remove(str(test_pkg)) def test_missing_cython_c_files(pyx_extension_test_package, monkeypatch): """ Regression test for https://github.com/astropy/astropy-helpers/pull/181 Test failure mode when building a package that has Cython modules, but where Cython is not installed and the generated C files are missing. """ test_pkg = pyx_extension_test_package # In order for this test to test the correct code path we need to fool # build_ext into thinking we don't have Cython installed monkeypatch.setattr(build_ext, 'should_build_with_cython', lambda *args: False) with test_pkg.as_cwd(): with pytest.raises(SystemExit) as exc_info: run_setup('setup.py', ['build_ext', '--inplace']) msg = ('Could not find C/C++ file ' '{0}.(c/cpp)'.format('_eva_/unit02'.replace('/', os.sep))) assert msg in str(exc_info.value) @pytest.mark.parametrize('mode', ['cli', 'cli-w', 'direct']) def test_build_sphinx(tmpdir, mode): """ Test for build_sphinx """ import astropy_helpers ah_path = os.path.dirname(astropy_helpers.__file__) test_pkg = tmpdir.mkdir('test_pkg') test_pkg.mkdir('mypackage') test_pkg.join('mypackage').join('__init__.py').write(dedent("""\ def test_function(): pass class A(): pass class B(A): pass """)) docs = test_pkg.mkdir('docs') autosummary = docs.mkdir('_templates').mkdir('autosummary') autosummary.join('base.rst').write('{% extends "autosummary_core/base.rst" %}') autosummary.join('class.rst').write('{% extends "autosummary_core/class.rst" %}') autosummary.join('module.rst').write('{% extends "autosummary_core/module.rst" %}') docs_dir = test_pkg.join('docs') docs_dir.join('conf.py').write(dedent("""\ import sys sys.path.append("../") import warnings with warnings.catch_warnings(): # ignore matplotlib warning warnings.simplefilter("ignore") from astropy_helpers.sphinx.conf import * exclude_patterns.append('_templates') """)) docs_dir.join('index.rst').write(dedent("""\ .. automodapi:: mypackage """)) test_pkg.join('setup.py').write(dedent("""\ from os.path import join from setuptools import setup, Extension from astropy_helpers.setup_helpers import register_commands, get_package_info NAME = 'mypackage' VERSION = 0.1 RELEASE = True cmdclassd = register_commands(NAME, VERSION, RELEASE) setup( name=NAME, version=VERSION, cmdclass=cmdclassd, **get_package_info() ) """)) with test_pkg.as_cwd(): shutil.copytree(ah_path, 'astropy_helpers') if mode == 'cli': run_setup('setup.py', ['build_sphinx']) elif mode == 'cli-w': run_setup('setup.py', ['build_sphinx', '-w']) elif mode == 'direct': # to check coverage with docs_dir.as_cwd(): from sphinx import main try: main(['-b html', '-d _build/doctrees', '.', '_build/html']) except SystemExit as exc: assert exc.code == 0 def test_command_hooks(tmpdir, capsys): """A basic test for pre- and post-command hooks.""" test_pkg = tmpdir.mkdir('test_pkg') test_pkg.mkdir('_welltall_') test_pkg.join('_welltall_', '__init__.py').ensure() # Create a setup_package module with a couple of command hooks in it test_pkg.join('_welltall_', 'setup_package.py').write(dedent("""\ def pre_build_hook(cmd_obj): print('Hello build!') def post_build_hook(cmd_obj): print('Goodbye build!') """)) # A simple setup.py for the test package--running register_commands should # discover and enable the command hooks test_pkg.join('setup.py').write(dedent("""\ from os.path import join from setuptools import setup, Extension from astropy_helpers.setup_helpers import register_commands, get_package_info NAME = '_welltall_' VERSION = 0.1 RELEASE = True cmdclassd = register_commands(NAME, VERSION, RELEASE) setup( name=NAME, version=VERSION, cmdclass=cmdclassd ) """)) with test_pkg.as_cwd(): try: run_setup('setup.py', ['build']) finally: cleanup_import('_welltall_') stdout, stderr = capsys.readouterr() want = dedent("""\ running build running pre_hook from _welltall_.setup_package for build command Hello build! running post_hook from _welltall_.setup_package for build command Goodbye build! """).strip() assert want in stdout def test_adjust_compiler(monkeypatch, tmpdir): """ Regression test for https://github.com/astropy/astropy-helpers/issues/182 """ from distutils import ccompiler, sysconfig class MockLog(object): def __init__(self): self.messages = [] def warn(self, message): self.messages.append(message) good = tmpdir.join('gcc-good') good.write(dedent("""\ #!{python} import sys print('gcc 4.10') sys.exit(0) """.format(python=sys.executable))) good.chmod(stat.S_IRUSR | stat.S_IEXEC) # A "compiler" that reports itself to be a version of Apple's llvm-gcc # which is broken bad = tmpdir.join('gcc-bad') bad.write(dedent("""\ #!{python} import sys print('i686-apple-darwin-llvm-gcc-4.2') sys.exit(0) """.format(python=sys.executable))) bad.chmod(stat.S_IRUSR | stat.S_IEXEC) # A "compiler" that doesn't even know its identity (this reproduces the bug # in #182) ugly = tmpdir.join('gcc-ugly') ugly.write(dedent("""\ #!{python} import sys sys.exit(1) """.format(python=sys.executable))) ugly.chmod(stat.S_IRUSR | stat.S_IEXEC) # Scripts with shebang lines don't work implicitly in Windows when passed # to subprocess.Popen, so... if 'win' in sys.platform: good = ' '.join((sys.executable, str(good))) bad = ' '.join((sys.executable, str(bad))) ugly = ' '.join((sys.executable, str(ugly))) dist = Distribution({}) cmd_cls = build_ext.generate_build_ext_command('astropy', False) cmd = cmd_cls(dist) adjust_compiler = cmd._adjust_compiler @contextlib.contextmanager def test_setup(): log = MockLog() monkeypatch.setattr(build_ext, 'log', log) yield log monkeypatch.undo() @contextlib.contextmanager def compiler_setter_with_environ(compiler): monkeypatch.setenv('CC', compiler) with test_setup() as log: yield log monkeypatch.undo() @contextlib.contextmanager def compiler_setter_with_sysconfig(compiler): monkeypatch.setattr(ccompiler, 'get_default_compiler', lambda: 'unix') monkeypatch.setattr(sysconfig, 'get_config_var', lambda v: compiler) old_cc = os.environ.get('CC') if old_cc is not None: del os.environ['CC'] with test_setup() as log: yield log monkeypatch.undo() monkeypatch.undo() monkeypatch.undo() if old_cc is not None: os.environ['CC'] = old_cc compiler_setters = (compiler_setter_with_environ, compiler_setter_with_sysconfig) for compiler_setter in compiler_setters: with compiler_setter(str(good)): # Should have no side-effects adjust_compiler() with compiler_setter(str(ugly)): # Should just pass without complaint, since we can't determine # anything about the compiler anyways adjust_compiler() # In the following tests we check the log messages just to ensure that the # failures occur on the correct code paths for these cases with compiler_setter_with_environ(str(bad)) as log: with pytest.raises(SystemExit): adjust_compiler() assert len(log.messages) == 1 assert 'will fail to compile' in log.messages[0] with compiler_setter_with_sysconfig(str(bad)): adjust_compiler() assert 'CC' in os.environ and os.environ['CC'] == 'clang' with compiler_setter_with_environ('bogus') as log: with pytest.raises(SystemExit): # Missing compiler? adjust_compiler() assert len(log.messages) == 1 assert 'cannot be found or executed' in log.messages[0] with compiler_setter_with_sysconfig('bogus') as log: with pytest.raises(SystemExit): # Missing compiler? adjust_compiler() assert len(log.messages) == 1 assert 'The C compiler used to compile Python' in log.messages[0] sunpy-0.6.3/astropy_helpers/astropy_helpers/tests/test_utils.py0000644000175000017500000000135712662554110026155 0ustar stuartstuart00000000000000import os from ..utils import find_data_files def test_find_data_files(tmpdir): data = tmpdir.mkdir('data') sub1 = data.mkdir('sub1') sub2 = data.mkdir('sub2') sub3 = sub1.mkdir('sub3') for directory in (data, sub1, sub2, sub3): filename = directory.join('data.dat').strpath with open(filename, 'w') as f: f.write('test') filenames = find_data_files(data.strpath, '**/*.dat') filenames = sorted(os.path.relpath(x, data.strpath) for x in filenames) assert filenames[0] == os.path.join('data.dat') assert filenames[1] == os.path.join('sub1', 'data.dat') assert filenames[2] == os.path.join('sub1', 'sub3', 'data.dat') assert filenames[3] == os.path.join('sub2', 'data.dat') sunpy-0.6.3/astropy_helpers/astropy_helpers/tests/test_ah_bootstrap.py0000644000175000017500000003434012622602515027477 0ustar stuartstuart00000000000000# -*- coding: utf-8 -*- import glob import os import textwrap import sys from distutils.version import StrictVersion import setuptools from setuptools.package_index import PackageIndex import pytest from . import * from ..utils import silence TEST_SETUP_PY = """\ #!/usr/bin/env python from __future__ import print_function import os import sys import ah_bootstrap # reset the name of the package installed by ah_boostrap to # _astropy_helpers_test_--this will prevent any confusion by pkg_resources with # any already installed packages named astropy_helpers # We also disable auto-upgrade by default ah_bootstrap.DIST_NAME = 'astropy-helpers-test' ah_bootstrap.PACKAGE_NAME = '_astropy_helpers_test_' ah_bootstrap.AUTO_UPGRADE = False ah_bootstrap.DOWNLOAD_IF_NEEDED = False try: ah_bootstrap.BOOTSTRAPPER = ah_bootstrap._Bootstrapper.main() ah_bootstrap.use_astropy_helpers({args}) finally: ah_bootstrap.DIST_NAME = 'astropy-helpers' ah_bootstrap.PACKAGE_NAME = 'astropy_helpers' ah_bootstrap.AUTO_UPGRADE = True ah_bootstrap.DOWNLOAD_IF_NEEDED = True # Kind of a hacky way to do this, but this assertion is specifically # for test_check_submodule_no_git # TODO: Rework the tests in this module so that it's easier to test specific # behaviors of ah_bootstrap for each test assert '--no-git' not in sys.argv import _astropy_helpers_test_ filename = os.path.abspath(_astropy_helpers_test_.__file__) filename = filename.replace('.pyc', '.py') # More consistent this way print(filename) """ # The behavior checked in some of the tests depends on the version of # setuptools try: SETUPTOOLS_VERSION = StrictVersion(setuptools.__version__).version except: # Broken setuptools? ĀÆ\_(惄)_/ĀÆ SETUPTOOLS_VERSION = (0, 0, 0) def test_bootstrap_from_submodule(tmpdir, testpackage, capsys): """ Tests importing _astropy_helpers_test_ from a submodule in a git repository. This tests actually performing a fresh clone of the repository without the submodule initialized, and that importing astropy_helpers in that context works transparently after calling `ah_boostrap.use_astropy_helpers`. """ orig_repo = tmpdir.mkdir('orig') # Ensure ah_bootstrap is imported from the local directory import ah_bootstrap with orig_repo.as_cwd(): run_cmd('git', ['init']) # Write a test setup.py that uses ah_bootstrap; it also ensures that # any previous reference to astropy_helpers is first wiped from # sys.modules orig_repo.join('setup.py').write(TEST_SETUP_PY.format(args='')) run_cmd('git', ['add', 'setup.py']) # Add our own clone of the astropy_helpers repo as a submodule named # astropy_helpers run_cmd('git', ['submodule', 'add', str(testpackage), '_astropy_helpers_test_']) run_cmd('git', ['commit', '-m', 'test repository']) os.chdir(str(tmpdir)) # Creates a clone of our test repo in the directory 'clone' run_cmd('git', ['clone', 'orig', 'clone']) os.chdir('clone') run_setup('setup.py', []) stdout, stderr = capsys.readouterr() path = stdout.strip() # Ensure that the astropy_helpers used by the setup.py is the one that # was imported from git submodule a = os.path.normcase(path) b = os.path.normcase(str(tmpdir.join('clone', '_astropy_helpers_test_', '_astropy_helpers_test_', '__init__.py'))) assert a == b def test_bootstrap_from_submodule_no_locale(tmpdir, testpackage, capsys, monkeypatch): """ Regression test for https://github.com/astropy/astropy/issues/2749 Runs test_bootstrap_from_submodule but with missing locale/language settings. """ for varname in ('LC_ALL', 'LC_CTYPE', 'LANG', 'LANGUAGE'): monkeypatch.delenv(varname, raising=False) test_bootstrap_from_submodule(tmpdir, testpackage, capsys) def test_bootstrap_from_submodule_bad_locale(tmpdir, testpackage, capsys, monkeypatch): """ Additional regression test for https://github.com/astropy/astropy/issues/2749 """ for varname in ('LC_ALL', 'LC_CTYPE', 'LANG', 'LANGUAGE'): monkeypatch.delenv(varname, raising=False) # Test also with bad LC_CTYPE a la http://bugs.python.org/issue18378 monkeypatch.setenv('LC_CTYPE', 'UTF-8') test_bootstrap_from_submodule(tmpdir, testpackage, capsys) def test_check_submodule_no_git(tmpdir, testpackage): """ Tests that when importing astropy_helpers from a submodule, it is still recognized as a submodule even when using the --no-git option. In particular this ensures that the auto-upgrade feature is not activated. """ orig_repo = tmpdir.mkdir('orig') # Ensure ah_bootstrap is imported from the local directory import ah_bootstrap with orig_repo.as_cwd(): run_cmd('git', ['init']) # Write a test setup.py that uses ah_bootstrap; it also ensures that # any previous reference to astropy_helpers is first wiped from # sys.modules args = 'auto_upgrade=True' orig_repo.join('setup.py').write(TEST_SETUP_PY.format(args=args)) run_cmd('git', ['add', 'setup.py']) # Add our own clone of the astropy_helpers repo as a submodule named # astropy_helpers run_cmd('git', ['submodule', 'add', str(testpackage), '_astropy_helpers_test_']) run_cmd('git', ['commit', '-m', 'test repository']) # Temporarily patch _do_upgrade to fail if called class UpgradeError(Exception): pass def _do_upgrade(*args, **kwargs): raise UpgradeError() orig_do_upgrade = ah_bootstrap._Bootstrapper._do_upgrade ah_bootstrap._Bootstrapper._do_upgrade = _do_upgrade try: run_setup('setup.py', ['--no-git']) except UpgradeError: pytest.fail('Attempted to run auto-upgrade despite importing ' '_astropy_helpers_test_ from a git submodule') finally: ah_bootstrap._Bootstrapper._do_upgrade = orig_do_upgrade # Ensure that the no-git option was in fact set assert not ah_bootstrap.BOOTSTRAPPER.use_git def test_bootstrap_from_directory(tmpdir, testpackage, capsys): """ Tests simply bundling a copy of the astropy_helpers source code in its entirety bundled directly in the source package and not in an archive. """ import ah_bootstrap source = tmpdir.mkdir('source') testpackage.copy(source.join('_astropy_helpers_test_')) with source.as_cwd(): source.join('setup.py').write(TEST_SETUP_PY.format(args='')) run_setup('setup.py', []) stdout, stderr = capsys.readouterr() stdout = stdout.splitlines() if stdout: path = stdout[-1].strip() else: path = '' # Ensure that the astropy_helpers used by the setup.py is the one that # was imported from git submodule a = os.path.normcase(path) b = os.path.normcase(str(source.join('_astropy_helpers_test_', '_astropy_helpers_test_', '__init__.py'))) assert a == b def test_bootstrap_from_archive(tmpdir, testpackage, capsys): """ Tests importing _astropy_helpers_test_ from a .tar.gz source archive shipped alongside the package that uses it. """ orig_repo = tmpdir.mkdir('orig') # Ensure ah_bootstrap is imported from the local directory import ah_bootstrap # Make a source distribution of the test package with silence(): run_setup(str(testpackage.join('setup.py')), ['sdist', '--dist-dir=dist', '--formats=gztar']) dist_dir = testpackage.join('dist') for dist_file in dist_dir.visit('*.tar.gz'): dist_file.copy(orig_repo) with orig_repo.as_cwd(): # Write a test setup.py that uses ah_bootstrap; it also ensures that # any previous reference to astropy_helpers is first wiped from # sys.modules args = 'path={0!r}'.format(os.path.basename(str(dist_file))) orig_repo.join('setup.py').write(TEST_SETUP_PY.format(args=args)) run_setup('setup.py', []) stdout, stderr = capsys.readouterr() path = stdout.splitlines()[-1].strip() # Installation from the .tar.gz should have resulted in a .egg # directory that the _astropy_helpers_test_ package was imported from eggs = _get_local_eggs() assert eggs egg = orig_repo.join(eggs[0]) assert os.path.isdir(str(egg)) a = os.path.normcase(path) b = os.path.normcase(str(egg.join('_astropy_helpers_test_', '__init__.py'))) assert a == b def test_download_if_needed(tmpdir, testpackage, capsys): """ Tests the case where astropy_helpers was not actually included in a package, or is otherwise missing, and we need to "download" it. This does not test actually downloading from the internet--this is normally done through setuptools' easy_install command which can also install from a source archive. From the point of view of ah_boostrap the two actions are equivalent, so we can just as easily simulate this by providing a setup.cfg giving the path to a source archive to "download" (as though it were a URL). """ source = tmpdir.mkdir('source') # Ensure ah_bootstrap is imported from the local directory import ah_bootstrap # Make a source distribution of the test package with silence(): run_setup(str(testpackage.join('setup.py')), ['sdist', '--dist-dir=dist', '--formats=gztar']) dist_dir = testpackage.join('dist') with source.as_cwd(): source.join('setup.py').write(TEST_SETUP_PY.format( args='download_if_needed=True')) source.join('setup.cfg').write(textwrap.dedent("""\ [easy_install] find_links = {find_links} """.format(find_links=str(dist_dir)))) run_setup('setup.py', []) stdout, stderr = capsys.readouterr() # Just take the last line--on Python 2.6 distutils logs warning # messages to stdout instead of stderr, causing them to be mixed up # with our expected output path = stdout.splitlines()[-1].strip() # easy_install should have worked by 'installing' astropy_helpers as a # .egg in the current directory eggs = _get_local_eggs() assert eggs egg = source.join(eggs[0]) assert os.path.isdir(str(egg)) a = os.path.normcase(path) b = os.path.normcase(str(egg.join('_astropy_helpers_test_', '__init__.py'))) assert a == b def test_upgrade(tmpdir, capsys): # Run the testpackage fixture manually, since we use it multiple times in # this test to make different versions of _astropy_helpers_test_ orig_dir = testpackage(tmpdir.mkdir('orig')) # Make a test package that uses _astropy_helpers_test_ source = tmpdir.mkdir('source') dist_dir = source.mkdir('dists') orig_dir.copy(source.join('_astropy_helpers_test_')) with source.as_cwd(): setup_py = TEST_SETUP_PY.format(args='auto_upgrade=True') source.join('setup.py').write(setup_py) # This will be used to later to fake downloading the upgrade package source.join('setup.cfg').write(textwrap.dedent("""\ [easy_install] find_links = {find_links} """.format(find_links=str(dist_dir)))) # Make additional "upgrade" versions of the _astropy_helpers_test_ # package--one of them is version 0.2 and the other is version 0.1.1. The # auto-upgrade should ignore version 0.2 but use version 0.1.1. upgrade_dir_1 = testpackage(tmpdir.mkdir('upgrade_1'), version='0.2') upgrade_dir_2 = testpackage(tmpdir.mkdir('upgrade_2'), version='0.1.1') dists = [] # For each upgrade package go ahead and build a source distribution of it # and copy that source distribution to a dist directory we'll use later to # simulate a 'download' for upgrade_dir in [upgrade_dir_1, upgrade_dir_2]: with silence(): run_setup(str(upgrade_dir.join('setup.py')), ['sdist', '--dist-dir=dist', '--formats=gztar']) dists.append(str(upgrade_dir.join('dist'))) for dist_file in upgrade_dir.visit('*.tar.gz'): dist_file.copy(source.join('dists')) # Monkey with the PackageIndex in ah_bootstrap so that it is initialized # with the test upgrade packages, and so that it does not actually go out # to the internet to look for anything import ah_bootstrap class FakePackageIndex(PackageIndex): def __init__(self, *args, **kwargs): PackageIndex.__init__(self, *args, **kwargs) self.to_scan = dists def find_packages(self, requirement): # no-op pass ah_bootstrap.PackageIndex = FakePackageIndex try: with source.as_cwd(): # Now run the source setup.py; this test is similar to # test_download_if_needed, but we explicitly check that the correct # *version* of _astropy_helpers_test_ was used run_setup('setup.py', []) stdout, stderr = capsys.readouterr() path = stdout.splitlines()[-1].strip() eggs = _get_local_eggs() assert eggs egg = source.join(eggs[0]) assert os.path.isdir(str(egg)) a = os.path.normcase(path) b = os.path.normcase(str(egg.join('_astropy_helpers_test_', '__init__.py'))) assert a == b assert 'astropy_helpers_test-0.1.1-' in str(egg) finally: ah_bootstrap.PackageIndex = PackageIndex def _get_local_eggs(path='.'): """ Helper utility used by some tests to get the list of egg archive files in a local directory. """ if SETUPTOOLS_VERSION[0] >= 7: eggs = glob.glob(os.path.join(path, '.eggs', '*.egg')) else: eggs = glob.glob('*.egg') return eggs sunpy-0.6.3/astropy_helpers/astropy_helpers/tests/__init__.pyc0000644000175000017500000001416212632251735025662 0ustar stuartstuart00000000000000ó MKVc@sddlZddlZddlZddlmZddlZddlmZej j e ƒZ ded„Zeejƒd„ƒZejddd eƒd „ƒZejddd eƒd „ƒZejdd d eƒd „ƒZdZejdd„ƒZd„ZdS(i’’’’N(tsandboxi(t extends_doccCsĆ|dk rt|ƒ}ntj|gt|ƒdtjdtjd|ƒ}td„|jƒDƒƒ}|j}|rø|dkrøt dj |t|ƒ||d|dƒƒ‚n||fS( s Runs a shell command with the given argument list. Changes directory to ``path`` if given, otherwise runs the command in the current directory. Returns a 3-tuple of (stdout, stderr, exit code) If ``raise_error=True`` raise an exception on non-zero exit codes. tstdouttstderrtcwdcss$|]}|jdƒjƒVqdS(tlatin1N(tdecodetstrip(t.0ts((sK/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/__init__.pys sisRThe command `{0}` with args {1!r} exited with code {2}. Stdout: {3} Stderr: {4}iN( tNonetstrtsptPopentlisttPIPEttuplet communicatet returncodet RuntimeErrortformat(tcmdtargstpatht raise_errortptstreamst return_code((sK/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/__init__.pytrun_cmds +  )cOsHztj||ŽSWdtjd dkrCddl}|jƒnXdS(sœ In Python 3, on MacOS X, the import cache has to be invalidated otherwise new extensions built with ``run_setup`` do not always get picked up. Niii’’’’(ii(Rt run_setuptsyst version_infot importlibtinvalidate_caches(RtkwargsR ((sK/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/__init__.pyR*s  tscopetfunctiontautousecCsAtdddgƒ}|jjƒ}|d„}|j|ƒdS(sl Saves and restores the global state of the astropy_helpers.setup_helpers module between tests. sastropy_helpers.setup_helperstfromlisttcSs5tjjdƒ}|dk r1|jj|ƒndS(Nsastropy_helpers.setup_helpers(RtmodulestgetR t _module_statetupdate(t old_statetmod((sK/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/__init__.pyt finalizerDs N(t __import__R*tcopyt addfinalizer(trequestR-R,R.((sK/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/__init__.pytreset_setup_helpers9s cCs$ddlm}|j|jƒdS(sÕ This is a setup/teardown fixture that ensures the log-level of the distutils log is always set to a default of WARN, since different settings could affect tests that check the contents of stdout. i’’’’(tlogN(t distutilsR4t set_thresholdtWARN(R4((sK/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/__init__.pytreset_distutils_logLstmodulecCs"ttdƒrd„t_ndS(sļ Workaround for https://github.com/astropy/astropy-helpers/issues/124 In setuptools 10.0 run_setup was changed in such a way that it sweeps away the existing setuptools import before running the setup script. In principle this is nice, but in the practice of testing astropy_helpers this is problematic since we're trying to test code that has already been imported during the testing process, and which relies on the setuptools module that was already in use. thide_setuptoolscSsdS(N(R (((sK/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/__init__.pytfsN(thasattrRR:(((sK/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/__init__.pytfix_hide_setuptoolsXs sĶ#!/usr/bin/env python from setuptools import setup NAME = 'astropy-helpers-test' VERSION = {version!r} setup(name=NAME, version=VERSION, packages=['_astropy_helpers_test_'], zip_safe=False) s0.1c Cs¼|jdƒ}|jƒ›|jdƒ|jddƒ}|jdj|ƒƒtjd|ƒ}|jdƒj|ƒtddgƒtdd d gƒtdd d d gƒWdQX|S(s  This fixture creates a simplified package called _astropy_helpers_test_ used primarily for testing ah_boostrap, but without using the astropy_helpers package directly and getting it confused with the astropy_helpers package already under test. ttestpkgt_astropy_helpers_test_s __init__.pys__version__ = {0!r}tversionssetup.pytgittinittadds--alltcommits-ms test packageN(tmkdirtas_cwdtjointwriteRtTEST_PACKAGE_SETUP_PYR(ttmpdirR@tsourceRBtsetup_py((sK/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/__init__.pyt testpackagews   cCstxmttjƒD]\}t|tƒs+qn|jdƒr@qn||ks_|j|dƒrtj|=qqWdS(s6Remove all references to package_name from sys.modulessastropy_helpers.testst.N(RRR(t isinstanceR t startswith(t package_nametk((sK/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/__init__.pytcleanup_import‘s(tost subprocessR Rt setuptoolsRtpytesttutilsRRtdirnamet__file__t PACKAGE_DIRR tTrueRRtfixtureR3R8R=RIRMRS(((sK/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/__init__.pyts    !! !sunpy-0.6.3/astropy_helpers/astropy_helpers/tests/coveragerc0000644000175000017500000000110412662554110025435 0ustar stuartstuart00000000000000[run] source = astropy_helpers omit = astropy_helpers/commands/_test_compat.py astropy_helpers/compat/* astropy_helpers/*/setup_package.py [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\(.*\): # Ignore branches that don't pertain to this version of Python pragma: py{ignore_python_version} sunpy-0.6.3/astropy_helpers/astropy_helpers/tests/__pycache__/0000755000175000017500000000000012675276745025631 5ustar stuartstuart00000000000000././@LongLink0000000000000000000000000000014700000000000011217 Lustar 00000000000000sunpy-0.6.3/astropy_helpers/astropy_helpers/tests/__pycache__/test_setup_helpers.cpython-27-PYTEST.pycsunpy-0.6.3/astropy_helpers/astropy_helpers/tests/__pycache__/test_setup_helpers.cpython-27-PYTEST.p0000644000175000017500000005755612646441444034700 0ustar stuartstuart00000000000000ó Nw–VF<c@s7ddlZddljjZddlZddlZddlZddl Z ddl m Z ddl m Z ddl mZmZmZddl Tdd „Zejd „ƒZejd „ƒZejd „ƒZd „Zd„Zd„Zd„Zejjddddgƒd„ƒZd„Zd„ZdS(i’’’’N(tdedenti(t setup_helpers(tget_package_infotregister_commandstadjust_compileri(t*tccCs|jdƒ}|jdƒjdƒ|dkrS|jddƒjtdƒƒn|dkr|jdd ƒjtd ƒƒn|dkr™dg}n3|dkr±d g}n|dkrĢdd g}ng|D](}d jtjj|ƒd |ƒ^qÓ}|jdd ƒjtdjdj|ƒƒƒƒ|jdƒjtdƒƒdt jkrpt jj dƒnt jj d dƒd„}|j |ƒ|S(s7Creates a simple test package with an extension module.ttest_pkgt_eva_s __init__.pyRtbothsunit01.csŠ #include #ifndef PY3K #if PY_MAJOR_VERSION >= 3 #define PY3K 1 #else #define PY3K 0 #endif #endif #if PY3K static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "unit01", NULL, -1, NULL }; PyMODINIT_FUNC PyInit_unit01(void) { return PyModule_Create(&moduledef); } #else PyMODINIT_FUNC initunit01(void) { Py_InitModule3("unit01", NULL, NULL); } #endif tpyxs unit02.pyxs0 print("Hello cruel angel.") s.Extension('_eva_.{0}', [join('_eva_', '{1}')])issetup_package.pys… from setuptools import Extension from os.path import join def get_extensions(): return [{0}] s, ssetup.pys” from os.path import join from setuptools import setup from astropy_helpers.setup_helpers import register_commands from astropy_helpers.setup_helpers import get_package_info from astropy_helpers.version_helpers import generate_version_py NAME = '_eva_' VERSION = '0.1' RELEASE = True cmdclassd = register_commands(NAME, VERSION, RELEASE) generate_version_py(NAME, VERSION, RELEASE, False, False) package_info = get_package_info() setup( name=NAME, version=VERSION, cmdclass=cmdclassd, **package_info ) tcSstdƒdS(NR(tcleanup_import(((sU/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_setup_helpers.pytfinalizels(Rsboth(spyxsboth( tmkdirtensuretjointwriteRtformattostpathtsplitexttsystremovetinsertt addfinalizer(ttmpdirtrequesttextension_typeRt extensionst extensiontextensions_listR ((sU/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_setup_helpers.pyt_extension_test_packages4         2   cCst||ddƒS(NRR (R (RR((sU/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_setup_helpers.pytextension_test_packagetscCst||ddƒS(NRR(R (RR((sU/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_setup_helpers.pytc_extension_test_packageyscCst||ddƒS(NRR (R (RR((sU/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_setup_helpers.pytpyx_extension_test_package~scCsJ|jdƒ}|jdƒjdƒ|jddƒ|jdddƒ|jdddƒjdƒtddtdt|ƒƒtt|ƒƒ}|d }t|ƒ}d }||k}|sut j d|fd||fƒid t j ƒkst j tƒrt jtƒnd d6t j|ƒd6t j|ƒd6t j|ƒd6}d i|d6}tt j|ƒƒ‚nd}}}}|d d} | j} d}| |k} | s4t j d!| fd"| |fƒit j| ƒd6t j| ƒd6t j|ƒd6} d#i| d6} tt j| ƒƒ‚nd} } } }dS($s¬ Regression test for https://github.com/astropy/astropy-helpers/pull/19 Ensures that Cython extensions in sub-packages are discovered and built only once. Rtyodatlukes __init__.pys dagobah.pyxsdef testfunc(): passs0.0tsrcdirt ext_modulesis==s0%(py4)s {%(py4)s = %(py0)s(%(py2)s) } == %(py7)stlentpy0tpy2tpy4tpy7R sassert %(py9)stpy9isyoda.luke.dagobahs,%(py3)s {%(py3)s = %(py1)s.name } == %(py6)stpy1tpy3tpy6sassert %(py8)stpy8N(s==(s0%(py4)s {%(py4)s = %(py0)s(%(py2)s) } == %(py7)ssassert %(py9)s(s==(s,%(py3)s {%(py3)s = %(py1)s.name } == %(py6)ssassert %(py8)s(RRRRRtFalsetstrRR(t @pytest_art_call_reprcomparet @py_builtinstlocalst_should_repr_global_namet _safereprtAssertionErrort_format_explanationtNonetname(RRt package_infot @py_assert1t @py_assert3t @py_assert6t @py_assert5t @py_format8t @py_format10t @py_assert0t @py_assert2t @py_assert4t @py_format7t @py_format9((sU/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_setup_helpers.pyttest_cython_autoextensionsƒs4   Œ  Uc Cs”|}|jdƒ}|jƒ9tddddj|ƒdj|jdƒƒgƒWdQX|jƒ&d dl}tjjtjj |j ƒƒ}|j}d }||ƒ}t |ƒ}||k} | r t j d f| fd f||fƒit j|ƒd 6t j|ƒd6dtjƒkp5t j|ƒrGt j|ƒndd6dtjƒkplt jt ƒr~t jt ƒndd6dtjƒkp£t j|ƒrµt j|ƒndd6t j|ƒd6t j|ƒd6} ddi| d6} tt j| ƒƒ‚nt} }}}}d dl}d dl}|j} | j} |j} | j}| |k}| rxt j d f|fdf| |fƒit j| ƒd6d tjƒkpĒt j|ƒrŁt j|ƒnd d6t j| ƒd6t j| ƒd6d tjƒkpt j|ƒr0t j|ƒnd d6t j|ƒd6}ddi|d6}tt j|ƒƒ‚nt} } }} }|j} | j} d }| |k}| rxt j d!f|fd"f| |fƒid tjƒkpžt j|ƒrt j|ƒnd d6t j| ƒd6t j| ƒd6t j|ƒd6}dd#i|d 6}tt j|ƒƒ‚nt} } }}WdQXdS($su Test ensuring that the compiler module is built and installed for packages that have extension modules. t install_tempssetup.pytinstalls#--single-version-externally-manageds--install-lib={0}s --record={0}s record.txtNi’’’’Rs==sj%(py0)s == %(py11)s {%(py11)s = %(py2)s(%(py9)s {%(py9)s = %(py5)s {%(py5)s = %(py3)s.join }(%(py7)s) }) }R-tpy11tdirnameR)R3R*R/tpy5R,R sassert %(py13)stpy13sŒ%(py4)s {%(py4)s = %(py2)s {%(py2)s = %(py0)s.version }.compiler } == %(py10)s {%(py10)s = %(py8)s {%(py8)s = %(py6)s._compiler }.compiler }R1R+R0tpy10sassert %(py12)stpy12tunknowns!=sM%(py4)s {%(py4)s = %(py2)s {%(py2)s = %(py0)s.version }.compiler } != %(py7)ssassert %(py9)s(Rtas_cwdt run_setupRRRRRtabspathRNt__file__R3R4R5R9R6R7R8R:R;R<t_eva_._compilert _eva_.versiontversiontcompilert _compiler(R"RRKRRNRGRAt @py_assert8t @py_assert10R?t @py_format12t @py_format14R@t @py_assert7t @py_assert9RBt @py_format11t @py_format13RCRD((sU/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_setup_helpers.pyttest_compiler_module›sV  "  !  ’   Ł  ’c Cs1|}ttjd<|jƒtdddgƒWdQXtjjdt|ƒƒzĮddl }t jj t jj |j jƒƒ}|j}d}||ƒ}t|ƒ}||k}| rütjd f|fd f||fƒitj|ƒd 6tj|ƒd 6d tjƒkp$tj|ƒr6tj|ƒnd d6dtjƒkp[tjtƒrmtjtƒndd6dtjƒkp’tj|ƒr¤tj|ƒndd6tj|ƒd6tj|ƒd6} ddi| d6} ttj| ƒƒ‚nt}}}}}Wdtjjt|ƒƒXdS(s  Regression test for https://github.com/astropy/astropy-helpers/pull/35 This tests the custom build_ext command installed by astropy_helpers when used with a project that has no Cython extensions (but does have one or more normal C extensions). t have_cythonssetup.pyt build_exts --inplaceNii’’’’Rs==sj%(py0)s == %(py11)s {%(py11)s = %(py2)s(%(py9)s {%(py9)s = %(py5)s {%(py5)s = %(py3)s.join }(%(py7)s) }) }R-RMRNR)R3R*RR/ROR,R sassert %(py13)sRP(R2Rt _module_stateRTRURRRR3t _eva_.unit01RRVRNtunit01RWRR4R5R9R6R7R8R:R;R<R( R"RRRNRGRAR]R^R?R_R`((sU/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_setup_helpers.pyttest_no_cython_buildext¹s(    $  ’c Cs»|}ttjd<|jƒ0tjtƒ}tdddgƒWdQXWdQXdjdj dt j ƒƒ}|j }t |ƒ}||k}|s©tjd|fd||fƒid tjƒksŲtj|ƒrētj|ƒnd d 6d tjƒkstjt ƒrtjt ƒnd d6dtjƒksFtj|ƒrUtj|ƒndd6tj|ƒd6tj|ƒd6}di|d6}ttj|ƒƒ‚nd}}}dS(sę Regression test for https://github.com/astropy/astropy-helpers/pull/181 Test failure mode when building a package that has Cython modules, but where Cython is not installed and the generated C files are missing. Rfssetup.pyRgs --inplaceNs%Could not find C/C++ file {0}.(c/cpp)s _eva_/unit02t/tinsK%(py0)s in %(py7)s {%(py7)s = %(py2)s(%(py5)s {%(py5)s = %(py3)s.value }) }tmsgR)R3R*texc_infoR/ROR,R sassert %(py9)sR-(Rm(sK%(py0)s in %(py7)s {%(py7)s = %(py2)s(%(py5)s {%(py5)s = %(py3)s.value }) }sassert %(py9)s(R2RRhRTtpytesttraisest SystemExitRURtreplaceRtseptvalueR3R4R5R6R7R8R9R:R;R<( R#RRoRnRGRAR?RCRD((sU/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_setup_helpers.pyttest_missing_cython_c_filesÕs   źtmodetcliscli-wtdirectcCsĢddl}tjj|jƒ}|jdƒ}|jdƒ|jdƒjdƒjtdƒƒ|jdƒ}|jdƒjd ƒ}|jd ƒjd ƒ|jd ƒjd ƒ|jdƒjdƒ|jdƒ}|jdƒjtdƒƒ|jdƒjtdƒƒ|jdƒjtdƒƒ|j ƒŒt j |dƒ|dkrjt ddgƒnX|dkrŒt dddgƒn6|dkrĀ|j ƒddl m}y|dddd gƒWnētk rø} | j} d!} | | k} | s§tjd+| fd,| | fƒid$tjƒksDtj| ƒrStj| ƒnd$d%6tj| ƒd&6tj| ƒd'6} d-i| d*6}ttj|ƒƒ‚nd} } } nXWdQXnWdQXdS(.s Test for build_sphinx i’’’’NRt mypackages __init__.pys} def test_function(): pass class A(): pass class B(A): pass tdocst _templatest autosummarysbase.rsts){% extends "autosummary_core/base.rst" %}s class.rsts*{% extends "autosummary_core/class.rst" %}s module.rsts+{% extends "autosummary_core/module.rst" %}sconf.pys# import sys sys.path.append("../") import warnings with warnings.catch_warnings(): # ignore matplotlib warning warnings.simplefilter("ignore") from astropy_helpers.sphinx.conf import * exclude_patterns.append('_templates') s index.rsts& .. automodapi:: mypackage ssetup.pysĀ from os.path import join from setuptools import setup, Extension from astropy_helpers.setup_helpers import register_commands, get_package_info NAME = 'mypackage' VERSION = 0.1 RELEASE = True cmdclassd = register_commands(NAME, VERSION, RELEASE) setup( name=NAME, version=VERSION, cmdclass=cmdclassd, **get_package_info() ) tastropy_helpersRxt build_sphinxscli-ws-wRy(tmains-b htmls-d _build/doctreest.s _build/htmlis==s,%(py2)s {%(py2)s = %(py0)s.code } == %(py5)stexcR)R*ROR sassert %(py7)sR,(s==(s,%(py2)s {%(py2)s = %(py0)s.code } == %(py5)ssassert %(py7)s(R~RRRNRWRRRRRTtshutiltcopytreeRUtsphinxR€RrtcodeR4R5R6R7R8R9R:R;R<(RRwR~tah_pathRR{R}tdocs_dirR€R‚R?RGR@t @py_format6RC((sU/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_setup_helpers.pyttest_build_sphinxķsL             |c Csž|jdƒ}|jdƒ|jddƒjƒ|jddƒjtdƒƒ|jdƒjtdƒƒ|jƒ'ztddgƒWd tdƒXWd QX|jƒ\}}td ƒj ƒ}||k}|s”t j d|fd||fƒid t j ƒkst j|ƒr)t j|ƒnd d6dt j ƒksQt j|ƒr`t j|ƒndd6}di|d6}tt j|ƒƒ‚nd }d S(s-A basic test for pre- and post-command hooks.Rt _welltall_s __init__.pyssetup_package.pys— def pre_build_hook(cmd_obj): print('Hello build!') def post_build_hook(cmd_obj): print('Goodbye build!') ssetup.pys” from os.path import join from setuptools import setup, Extension from astropy_helpers.setup_helpers import register_commands, get_package_info NAME = '_welltall_' VERSION = 0.1 RELEASE = True cmdclassd = register_commands(NAME, VERSION, RELEASE) setup( name=NAME, version=VERSION, cmdclass=cmdclassd ) tbuildNsŁ running build running pre_hook from _welltall_.setup_package for build command Hello build! running post_hook from _welltall_.setup_package for build command Goodbye build! Rms%(py0)s in %(py2)stwantR)tstdoutR*R sassert %(py4)sR+(Rm(s%(py0)s in %(py2)ssassert %(py4)s(RRRRRRTRUR t readouterrtstripR4R5R6R7R8R9R:R;R<( RtcapsysRRŽtstderrRR?t @py_format3t @py_format5((sU/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_setup_helpers.pyttest_command_hooks@s(     “cs ddlm‰m‰dtfd„ƒY‰|jdƒ}|jtdjdtj ƒƒƒ|j t j t j Bƒ|jdƒ}|jtd jdtj ƒƒƒ|j t j t j Bƒ|jd ƒ}|jtd jdtj ƒƒƒ|j t j t j Bƒd tjkrpd jtj t|ƒfƒ}d jtj t|ƒfƒ}d jtj t|ƒfƒ}ntj‡‡fd†ƒ‰tj‡‡fd†ƒ}tj‡‡‡‡fd†ƒ}||f}xT|D]L}|t|ƒƒtdƒWdQX|t|ƒƒtdƒWdQXqŚW|t|ƒƒó} tjtƒtdƒWdQX| j} t| ƒ} d} | | k} | sxtjd8| fd9| | fƒidtjƒksĪtjtƒrŻtjtƒndd6dtjƒkstj| ƒrtj| ƒndd6tj| ƒd6tj| ƒd6tj| ƒd6}d:i|d6}ttj|ƒƒ‚nd} } } } d }| jd!}||k} | stjd;| fd<||fƒitj|ƒd6tj|ƒd$6}d=i|d&6}ttj|ƒƒ‚nd}} }WdQX|t|ƒƒŃtdƒg}d'} t!j"} | | k} | }| r£t!j"d'}d(}||k}|}n|sītjd>| fd?| | fƒitj| ƒd6d*tjƒksūtjt!ƒr tjt!ƒnd*d6tj| ƒd+6}d,i|d-6}|j#|ƒ| rÆtjd@|fdA||fƒitj|ƒd/6tj|ƒd06}d1i|d26}|j#|ƒntj$|d!ƒi}dBi|d46}ttj|ƒƒ‚nd}}} } } }}}WdQX|d5ƒó} tjtƒtdƒWdQX| j} t| ƒ} d} | | k} | s^tjdC| fdD| | fƒidtjƒks“tjtƒrĆtjtƒndd6dtjƒksėtj| ƒrśtj| ƒndd6tj| ƒd6tj| ƒd6tj| ƒd6}dEi|d6}ttj|ƒƒ‚nd} } } } d6}| jd!}||k} | stjdF| fdG||fƒitj|ƒd6tj|ƒd$6}dHi|d&6}ttj|ƒƒ‚nd}} }WdQX|d5ƒó} tjtƒtdƒWdQX| j} t| ƒ} d} | | k} | s_ tjdI| fdJ| | fƒidtjƒksµtjtƒrÄtjtƒndd6dtjƒksģtj| ƒrūtj| ƒndd6tj| ƒd6tj| ƒd6tj| ƒd6}dKi|d6}ttj|ƒƒ‚nd} } } } d7}| jd!}||k} | s tjdL| fdM||fƒitj|ƒd6tj|ƒd$6}dNi|d&6}ttj|ƒƒ‚nd}} }WdQXdS(OsS Regression test for https://github.com/astropy/astropy-helpers/issues/182 i’’’’(t ccompilert sysconfigtMockLogcBseZd„Zd„ZRS(cSs g|_dS(N(tmessages(tself((sU/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_setup_helpers.pyt__init__scSs|jj|ƒdS(N(R™tappend(Rštmessage((sU/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_setup_helpers.pytwarn‚s(t__name__t __module__R›Rž(((sU/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_setup_helpers.pyR˜~s sgcc-goodsX #!{python} import sys print('gcc 4.10') sys.exit(0) tpythonsgcc-badsn #!{python} import sys print('i686-apple-darwin-llvm-gcc-4.2') sys.exit(0) sgcc-uglys> #!{python} import sys sys.exit(1) twint c3sIttjd<ˆƒ}ˆjtd|ƒ|Vˆjƒttjd¼stget_config_varcsˆS(N((tv(R[(sU/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_setup_helpers.pyRƽstget_distutils_build_optioncSsdS(NR ((topt((sU/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_setup_helpers.pyRÆæsRŖ(R¦RRtenvirontgetR<R§(R[told_ccR„(R–RØR—R©(R[sU/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_setup_helpers.pytcompiler_setter_with_sysconfigŗs          tastropyNis==sN%(py5)s {%(py5)s = %(py0)s(%(py3)s {%(py3)s = %(py1)s.messages }) } == %(py8)sR(R)R„R.R1R/ROR sassert %(py10)sRQswill fail to compile astropyiRms%(py1)s in %(py4)sR+sassert %(py6)sR0RŖtclangs/%(py3)s in %(py7)s {%(py7)s = %(py5)s.environ }RR,s%(py9)sR-s%(py12)s == %(py15)sRRtpy15s%(py17)stpy17sassert %(py20)stpy20tbogusscannot be found or executeds%The C compiler used to compile Python(s==(sN%(py5)s {%(py5)s = %(py0)s(%(py3)s {%(py3)s = %(py1)s.messages }) } == %(py8)ssassert %(py10)s(Rm(s%(py1)s in %(py4)ssassert %(py6)s(Rm(s/%(py3)s in %(py7)s {%(py7)s = %(py5)s.environ }(s==(s%(py12)s == %(py15)ssassert %(py20)s(s==(sN%(py5)s {%(py5)s = %(py0)s(%(py3)s {%(py3)s = %(py1)s.messages }) } == %(py8)ssassert %(py10)s(Rm(s%(py1)s in %(py4)ssassert %(py6)s(s==(sN%(py5)s {%(py5)s = %(py0)s(%(py3)s {%(py3)s = %(py1)s.messages }) } == %(py8)ssassert %(py10)s(Rm(s%(py1)s in %(py4)ssassert %(py6)s(%t distutilsR–R—tobjectRRRRRt executabletchmodtstattS_IRUSRtS_IEXECtplatformR3t contextlibtcontextmanagerRRpRqRrR™R(R4R5R6R7R8R9R:R;R<RR“Rœt_format_boolop(RØRtgoodtbadtuglyR¬R·tcompiler_setterstcompiler_setterR„RFRGRaRARIRcRER@R”RHR?t @py_assert11t @py_assert14t @py_assert13RCRDt @py_format16t @py_format18t @py_format19t @py_format21((R˜R–RØR—R©sU/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_setup_helpers.pyttest_adjust_compilerwsą   ! !    Ć E    | E(  Ć E  Ć E( t __builtin__R6t_pytest.assertion.rewritet assertiontrewriteR4RĘRƒRĀRttextwrapRR RRRRR RptfixtureR!R"R#RJReRkRvtmarkt parametrizeRŠR•RÕ(((sU/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_setup_helpers.pyts(       f    'S 7././@LongLink0000000000000000000000000000014600000000000011216 Lustar 00000000000000sunpy-0.6.3/astropy_helpers/astropy_helpers/tests/__pycache__/test_ah_bootstrap.cpython-27-PYTEST.pycsunpy-0.6.3/astropy_helpers/astropy_helpers/tests/__pycache__/test_ah_bootstrap.cpython-27-PYTEST.py0000644000175000017500000004205112632251735034651 0ustar stuartstuart00000000000000ó MKVą8c@s$ddlZddljjZddlZddlZddlZddl Z ddl m Z ddl Z ddl mZddlZddlTddlmZdZye e jƒjZWn dZnXd „Zd „Zd „Zd „Zd„Zd„Zd„Zd„Zdd„ZdS(i’’’’N(t StrictVersion(t PackageIndexi(t*i(tsilencesä#!/usr/bin/env python from __future__ import print_function import os import sys import ah_bootstrap # reset the name of the package installed by ah_boostrap to # _astropy_helpers_test_--this will prevent any confusion by pkg_resources with # any already installed packages named astropy_helpers # We also disable auto-upgrade by default ah_bootstrap.DIST_NAME = 'astropy-helpers-test' ah_bootstrap.PACKAGE_NAME = '_astropy_helpers_test_' ah_bootstrap.AUTO_UPGRADE = False ah_bootstrap.DOWNLOAD_IF_NEEDED = False try: ah_bootstrap.BOOTSTRAPPER = ah_bootstrap._Bootstrapper.main() ah_bootstrap.use_astropy_helpers({args}) finally: ah_bootstrap.DIST_NAME = 'astropy-helpers' ah_bootstrap.PACKAGE_NAME = 'astropy_helpers' ah_bootstrap.AUTO_UPGRADE = True ah_bootstrap.DOWNLOAD_IF_NEEDED = True # Kind of a hacky way to do this, but this assertion is specifically # for test_check_submodule_no_git # TODO: Rework the tests in this module so that it's easier to test specific # behaviors of ah_bootstrap for each test assert '--no-git' not in sys.argv import _astropy_helpers_test_ filename = os.path.abspath(_astropy_helpers_test_.__file__) filename = filename.replace('.pyc', '.py') # More consistent this way print(filename) ic Cs|jdƒ}ddl}|jƒštddgƒ|jdƒjtjddƒƒtdd dgƒtdd d t|ƒd gƒtdd d dgƒt j t|ƒƒtddddgƒt j dƒt dgƒ|j ƒ\}}|j ƒ}t jj|ƒ}t jjt|jdd d dƒƒƒ} || k} | s tjd| fd|| fƒidtjƒks“tj|ƒr¢tj|ƒndd6dtjƒksŹtj| ƒrŁtj| ƒndd6} di| d6} ttj| ƒƒ‚nd} WdQXdS(sA Tests importing _astropy_helpers_test_ from a submodule in a git repository. This tests actually performing a fresh clone of the repository without the submodule initialized, and that importing astropy_helpers in that context works transparently after calling `ah_boostrap.use_astropy_helpers`. torigi’’’’Ntgittinitssetup.pytargsttaddt submodulet_astropy_helpers_test_tcommits-mstest repositorytclones __init__.pys==s%(py0)s == %(py2)statpy0tbtpy2sassert %(py4)stpy4(s==(s%(py0)s == %(py2)ssassert %(py4)s(tmkdirt ah_bootstraptas_cwdtrun_cmdtjointwritet TEST_SETUP_PYtformattstrtostchdirt run_setupt readouterrtstriptpathtnormcaset @pytest_art_call_reprcomparet @py_builtinstlocalst_should_repr_global_namet _safereprtAssertionErrort_format_explanationtNone( ttmpdirt testpackagetcapsyst orig_repoRtstdouttstderrR!RRt @py_assert1t @py_format3t @py_format5((sT/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_ah_bootstrap.pyttest_bootstrap_from_submoduleBs2   "     “cCs8x!dD]}|j|dtƒqWt|||ƒdS(s£ Regression test for https://github.com/astropy/astropy/issues/2749 Runs test_bootstrap_from_submodule but with missing locale/language settings. tLC_ALLtLC_CTYPEtLANGtLANGUAGEtraisingN(sLC_ALLsLC_CTYPEsLANGsLANGUAGE(tdelenvtFalseR5(R,R-R.t monkeypatchtvarname((sT/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_ah_bootstrap.pyt'test_bootstrap_from_submodule_no_localeus cCsHx!dD]}|j|dtƒqW|jddƒt|||ƒdS( s[ Additional regression test for https://github.com/astropy/astropy/issues/2749 R6R7R8R9R:sUTF-8N(sLC_ALLsLC_CTYPEsLANGsLANGUAGE(R;R<tsetenvR5(R,R-R.R=R>((sT/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_ah_bootstrap.pyt(test_bootstrap_from_submodule_bad_locale„s c sā|jdƒ}ddl}|jƒµtddgƒd}|jdƒjtjd|ƒƒtdd dgƒtdd d t|ƒd gƒtdd d dgƒdt fd„ƒY‰‡fd†}|j j }||j _ z9yt ddgƒWnˆk rt jdƒnXWd||j _ X|j}|j}| } | sŹddidtjƒksxtj|ƒr‡tj|ƒndd6tj|ƒd6tj|ƒd6} ttj| ƒƒ‚nd}}} WdQXdS(sä Tests that when importing astropy_helpers from a submodule, it is still recognized as a submodule even when using the --no-git option. In particular this ensures that the auto-upgrade feature is not activated. Ri’’’’NRRsauto_upgrade=Truessetup.pyRR R R R s-mstest repositoryt UpgradeErrorcBseZRS((t__name__t __module__(((sT/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_ah_bootstrap.pyRB³scs ˆƒ‚dS(N((Rtkwargs(RB(sT/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_ah_bootstrap.pyt _do_upgrade¶ss--no-gits[Attempted to run auto-upgrade despite importing _astropy_helpers_test_ from a git submoduleRsQassert not %(py4)s {%(py4)s = %(py2)s {%(py2)s = %(py0)s.BOOTSTRAPPER }.use_git }RRRR(RRRRRRRRRt Exceptiont _BootstrapperRFRtpytesttfailt BOOTSTRAPPERtuse_gitR%R&R#R'R(R)R*R+( R,R-R/RRRFtorig_do_upgradeR2t @py_assert3t @py_assert5t @py_format6((RBsT/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_ah_bootstrap.pyttest_check_submodule_no_git”s6  "      ec CsĮddl}|jdƒ}|j|jdƒƒ|jƒ~|jdƒjtjddƒƒtdgƒ|j ƒ\}}|j ƒ}|r¤|dj ƒ}nd}t j j|ƒ}t j jt|jdddƒƒƒ} || k} | s±tjd| fd|| fƒid tjƒks7tj|ƒrFtj|ƒnd d 6d tjƒksntj| ƒr}tj| ƒnd d6} di| d6} ttj| ƒƒ‚nd} WdQXdS(s› Tests simply bundling a copy of the astropy_helpers source code in its entirety bundled directly in the source package and not in an archive. i’’’’NtsourceR ssetup.pyRRs __init__.pys==s%(py0)s == %(py2)sRRRRsassert %(py4)sR(s==(s%(py0)s == %(py2)ssassert %(py4)s(RRtcopyRRRRRRRt splitlinesR RR!R"RR#R$R%R&R'R(R)R*R+( R,R-R.RRRR0R1R!RRR2R3R4((sT/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_ah_bootstrap.pyttest_bootstrap_from_directoryĒs*  "   “c Csē|jdƒ}ddl}tƒ*tt|jdƒƒdddgƒWdQX|jdƒ}x$|jd ƒD]}|j|ƒqoW|jƒOd j t j j t|ƒƒƒ}|jdƒj tj d |ƒƒtdgƒ|jƒ\}} |jƒdjƒ} tƒ} | ssd"idtjƒksAtj| ƒrPtj| ƒndd6} ttj| ƒƒ‚n|j| dƒ} t j }|j}t| ƒ}||ƒ}|sĮd ditj|ƒd6dtjƒksńtjt ƒrtjt ƒndd6tj|ƒd6tj|ƒd6dtjƒksHtjtƒrWtjtƒndd6dtjƒkstj| ƒrŽtj| ƒndd6tj|ƒd6}ttj|ƒƒ‚nd}}}}t j j| ƒ}t j jt| jddƒƒƒ}||k}|s×tjd#|fd$||fƒidtjƒks]tj|ƒrltj|ƒndd6d tjƒks”tj|ƒr£tj|ƒnd d6}d%i|d6}ttj|ƒƒ‚nd}WdQXdS(&s~ Tests importing _astropy_helpers_test_ from a .tar.gz source archive shipped alongside the package that uses it. Ri’’’’Nssetup.pytsdists--dist-dir=dists--formats=gztartdists*.tar.gzs path={0!r}RRsassert %(py0)steggsRisassert %(py10)s {%(py10)s = %(py4)s {%(py4)s = %(py2)s {%(py2)s = %(py0)s.path }.isdir }(%(py8)s {%(py8)s = %(py5)s(%(py6)s) }) }tpy8RRRRtpy5teggtpy6tpy10R s __init__.pys==s%(py0)s == %(py2)sRRsassert %(py4)ssassert %(py0)s(s==(s%(py0)s == %(py2)ssassert %(py4)s(RRRRRRtvisitRSRRRR!tbasenameRRRRTR t_get_local_eggsR%R&R#R'R(R)R*tisdirR+R"R$(R,R-R.R/Rtdist_dirt dist_fileRR0R1R!RXt @py_format1R[R2RNt @py_assert7t @py_assert9t @py_format11RRR3R4((sT/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_ah_bootstrap.pyttest_bootstrap_from_archiveęsH   !"  A ó “c CsŠ|jdƒ}ddl}tƒ*tt|jdƒƒdddgƒWdQX|jdƒ}|jƒ_|jdƒjtj d d ƒƒ|jd ƒjt j d j d t|ƒƒƒƒtdgƒ|j ƒ\}}|j ƒdjƒ}tƒ} | s\d$idtjƒks*tj| ƒr9tj| ƒndd6} ttj| ƒƒ‚n|j| dƒ} tj} | j} t| ƒ}| |ƒ}|sŖdditj|ƒd6dtjƒksŚtjtƒrétjtƒndd6tj| ƒd6tj| ƒd6dtjƒks1tjtƒr@tjtƒndd6dtjƒkshtj| ƒrwtj| ƒndd6tj|ƒd6}ttj|ƒƒ‚nd} } }}tjj|ƒ}tjjt| jddƒƒƒ}||k} | sĄtjd%| fd&||fƒid!tjƒksFtj|ƒrUtj|ƒnd!d6d"tjƒks}tj|ƒrŒtj|ƒnd"d6}d'i|d6}ttj|ƒƒ‚nd} WdQXdS((s& Tests the case where astropy_helpers was not actually included in a package, or is otherwise missing, and we need to "download" it. This does not test actually downloading from the internet--this is normally done through setuptools' easy_install command which can also install from a source archive. From the point of view of ah_boostrap the two actions are equivalent, so we can just as easily simulate this by providing a setup.cfg giving the path to a source archive to "download" (as though it were a URL). RRi’’’’Nssetup.pyRVs--dist-dir=dists--formats=gztarRWRsdownload_if_needed=Trues setup.cfgsI [easy_install] find_links = {find_links} t find_linksRsassert %(py0)sRXRisassert %(py10)s {%(py10)s = %(py4)s {%(py4)s = %(py2)s {%(py2)s = %(py0)s.path }.isdir }(%(py8)s {%(py8)s = %(py5)s(%(py6)s) }) }RYRRRRRZR[R\R]R s __init__.pys==s%(py0)s == %(py2)sRRsassert %(py4)ssassert %(py0)s(s==(s%(py0)s == %(py2)ssassert %(py4)s(RRRRRRRRRRttextwraptdedentRRTR R`R%R&R#R'R(R)R*RR!RaR+R"R$(R,R-R.RRRRbR0R1R!RXRdR[R2RNReRfRgRRR3R4((sT/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_ah_bootstrap.pyttest_download_if_neededsH       A ó “c s÷t|jdƒƒ}|jdƒ}|jdƒ}|j|jdƒƒ|jƒ^tjddƒ}|jdƒj|ƒ|jdƒjtj d jd t |ƒƒƒƒWdQXt|jd ƒd d ƒ}t|jdƒd dƒ}g‰x•||gD]‡}t ƒ*t t |jdƒƒdddgƒWdQXˆj t |jdƒƒƒx-|jdƒD]} | j|jdƒƒqeWqžWddl} dtf‡fd†ƒY} | | _z,|jƒt dgƒ|jƒ\} } | jƒdjƒ}tƒ}|sgd3idtjƒks5tj|ƒrDtj|ƒndd6}ttj|ƒƒ‚n|j|dƒ}tj}|j}t |ƒ}||ƒ}|sµdditj|ƒd6dtjƒksåtjtƒrōtjtƒndd6tj|ƒd 6tj|ƒd!6d"tjƒks<tjt ƒrKtjt ƒnd"d#6d$tjƒksstj|ƒr‚tj|ƒnd$d%6tj|ƒd&6}ttj|ƒƒ‚nd}}}}tjj |ƒ}tjj t |jdd'ƒƒƒ}||k}|sĖtj!d4|fd5||fƒid*tjƒksQtj|ƒr`tj|ƒnd*d6d+tjƒksˆtj|ƒr—tj|ƒnd+d 6}d6i|d!6}ttj|ƒƒ‚nd}d-}t |ƒ}||k}|sŃtj!d7|fd8||fƒitj|ƒd06d"tjƒksGtjt ƒrVtjt ƒnd"d16d$tjƒks~tj|ƒrtj|ƒnd$d!6tj|ƒd%6}d9i|d6}ttj|ƒƒ‚nd}}}WdQXWdt| _XdS(:NRRRtdistsR Rsauto_upgrade=Truessetup.pys setup.cfgsI [easy_install] find_links = {find_links} Rit upgrade_1tversions0.2t upgrade_2s0.1.1RVs--dist-dir=dists--formats=gztarRWs*.tar.gzi’’’’tFakePackageIndexcs eZ‡fd†Zd„ZRS(cs tj|||Žˆ|_dS(N(Rt__init__tto_scan(tselfRRE(Rm(sT/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_ah_bootstrap.pyRrwscSsdS(N((Rtt requirement((sT/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_ah_bootstrap.pyt find_packages{s(RCRDRrRv((Rm(sT/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_ah_bootstrap.pyRqvsRsassert %(py0)sRXRisassert %(py10)s {%(py10)s = %(py4)s {%(py4)s = %(py2)s {%(py2)s = %(py0)s.path }.isdir }(%(py8)s {%(py8)s = %(py5)s(%(py6)s) }) }RYRRRRRZR[R\R]s __init__.pys==s%(py0)s == %(py2)sRRsassert %(py4)ssastropy_helpers_test-0.1.1-tins0%(py1)s in %(py6)s {%(py6)s = %(py3)s(%(py4)s) }tpy1tpy3sassert %(py8)ssassert %(py0)s(s==(s%(py0)s == %(py2)ssassert %(py4)s(Rw(s0%(py1)s in %(py6)s {%(py6)s = %(py3)s(%(py4)s) }sassert %(py8)s("R-RRSRRRRRRjRkRRRtappendR^RRRRTR R`R%R&R#R'R(R)R*RR!RaR+R"R$( R,R.torig_dirRRRbtsetup_pyt upgrade_dir_1t upgrade_dir_2t upgrade_dirRcRRqR0R1R!RXRdR[R2RNReRfRgRRR3R4t @py_assert0ROt @py_assert2t @py_format7t @py_format9((RmsT/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_ah_bootstrap.pyt test_upgradeKst "      A ó “ ³t.cCsGtddkr4tjtjj|ddƒƒ}ntjdƒ}|S(sj Helper utility used by some tests to get the list of egg archive files in a local directory. iis.eggss*.egg(tSETUPTOOLS_VERSIONtglobRR!R(R!RX((sT/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_ah_bootstrap.pyR`˜s$(iii( t __builtin__R%t_pytest.assertion.rewritet assertiontrewriteR#R‡RRjtsystdistutils.versionRt setuptoolstsetuptools.package_indexRRIRtutilsRRt __version__RoR†R5R?RARQRURhRlR„R`(((sT/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_ah_bootstrap.pyts2        &  3   3  . 7 Msunpy-0.6.3/astropy_helpers/astropy_helpers/tests/__pycache__/test_git_helpers.cpython-27-PYTEST.pyc0000644000175000017500000003017412632251735034637 0ustar stuartstuart00000000000000ó MKV¼c@s ddlZddljjZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Te jddkZeržeZneZe jdƒZdZdZejd „ƒZd „Zd „Zejjd d dgƒd„ƒZdS(i’’’’Ni(t*iis\d+\.\d+(?:\.\d+)?\.dev(\d+)sØ#!/usr/bin/env python from setuptools import setup NAME = '_eva_' VERSION = {version!r} RELEASE = 'dev' not in VERSION from astropy_helpers.git_helpers import get_git_devstr from astropy_helpers.version_helpers import generate_version_py if not RELEASE: VERSION += get_git_devstr(False) generate_version_py(NAME, VERSION, RELEASE, False, uses_git=not RELEASE) setup(name=NAME, version=VERSION, packages=['_eva_']) sœtry: from .version import version as __version__ from .version import githash as __githash__ except ImportError: __version__ = __githash__ = '' csd‡‡fd†}|S(Ns 42.42.devc sėˆjdƒ}|jdƒjtjd|ƒƒ|jdƒjdƒjtƒ|jƒ>tddgƒtddd gƒtdd d d gƒWdQXd tj kr¾tj j d ƒntj j dd ƒd„}ˆj |ƒ|S(Nt test_packagessetup.pytversiont_eva_s __init__.pytgittinittadds--alltcommits-ms test packageticSstdƒdS(NR(tcleanup_import(((sS/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_git_helpers.pytfinalizeFs( tmkdirtjointwritetTEST_VERSION_SETUP_PYtformattTEST_VERSION_INITtas_cwdtrun_cmdtsystpathtremovetinsertt addfinalizer(RRR (trequestttmpdir(sS/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_git_helpers.pytmake_test_package7s   ((RRR((RRsS/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_git_helpers.pytversion_test_package5sc Cs½|ƒ}|jƒ3tddgƒ|jƒ\}}|jƒ}tj|ƒ}| rĢtjdj||ƒƒdidt j ƒkp—tj |ƒr©tj |ƒndd6}t tj|ƒƒ‚nt|jdƒƒ}dd l} | j} | |k} | rßtjd f| fd f| |fƒid t j ƒkpNtj | ƒr`tj | ƒnd d6tj | ƒd 6dt j ƒkp•tj |ƒr§tj |ƒndd6} ddi| d6} t tj| ƒƒ‚nt} } tddƒWd QXtdddgƒtddddgƒdd l} tj| jƒWd QXtj| jjƒ}| rĆddidt j ƒkpŽtj |ƒr tj |ƒndd6}t tj|ƒƒ‚n|j}d}||ƒ}t|ƒ}d}||}||k}| rZtjd f|fdf||fƒitj |ƒd6dt j ƒkpbtj |ƒrttj |ƒndd6dt j ƒkp™tj tƒr«tj tƒndd6dt j ƒkpŠtj |ƒrātj |ƒndd 6tj |ƒd!6tj |ƒd"6tj |ƒd#6tj |ƒd$6}dd%i|d&6}t tj|ƒƒ‚nt}}}}}}}dd'lm}||d(t|ƒƒ}| j} | j}||k} | r«tjd f| fd)f||fƒid*t j ƒkp tj |ƒrtj |ƒnd*d6d t j ƒkpAtj | ƒrStj | ƒnd d 6tj | ƒd6tj |ƒd6} dd+i| d,6}t tj|ƒƒ‚nt} } }d S(-sTests that the commit number in the package's version string updates after git commits even without re-running setup.py. ssetup.pys --versionsCStdout did not match the version string pattern: {0} Stderr: {1}s >assert %(py0)stmtpy0ii’’’’Ns==s3%(py2)s {%(py2)s = %(py0)s.__version__ } == %(py4)sRtpy2Rtpy4Rsassert %(py6)stpy6s.testtwRRRs-mttestsassert %(py0)ssw%(py9)s {%(py9)s = %(py0)s(%(py7)s {%(py7)s = %(py3)s {%(py3)s = %(py1)s.group }(%(py5)s) }) } == (%(py11)s + %(py13)s)tpy9trevcounttpy11tinttpy1tpy3tpy5tpy7tpy13sassert %(py16)stpy16(tupdate_git_devstrRsL%(py0)s == %(py6)s {%(py6)s = %(py4)s {%(py4)s = %(py2)s.version }.version }t newversionsassert %(py8)stpy8(Rt run_setupt readouterrtstript_DEV_VERSION_REtmatcht @pytest_art_format_assertmsgRt @py_builtinstlocalst_should_repr_global_namet _safereprtAssertionErrort_format_explanationR&tgroupRt __version__t_call_reprcomparetNonetopenRt _eva_.versiontimptreloadRtastropy_helpers.git_helpersR-tstr(Rtcapsysttest_pkgtstdouttstderrRRt @py_format1R$Rt @py_assert1t @py_assert3t @py_format5t @py_format7t @py_assert2t @py_assert4t @py_assert6t @py_assert8t @py_assert12t @py_assert14t @py_assert10t @py_format15t @py_format17R-R.t @py_assert5t @py_format9((sS/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_git_helpers.pyttest_update_git_devstrPsf   Z  ©  E   ’! ¹c Cs |ƒ}|jƒtddgƒWdQXtjjdt|ƒƒz¦ddl}tj|j ƒ}| rŹddidt j ƒkp•t j |ƒr§t j|ƒndd 6}tt j|ƒƒ‚nt|jd ƒƒ}|jƒż|jd ƒ}|jƒtd d gƒddl}tj|jƒtj|jjƒ}| rŖddidt j ƒkput j |ƒr‡t j|ƒndd 6}tt j|ƒƒ‚n|j}d } || ƒ} t| ƒ} | |k} | r!t jdf| fdf| |fƒit j| ƒd6dt j ƒkp9t j |ƒrKt j|ƒndd6dt j ƒkppt j tƒr‚t jtƒndd 6dt j ƒkp§t j |ƒr¹t j|ƒndd6t j|ƒd6t j| ƒd6t j| ƒd6} ddi| d6}tt j|ƒƒ‚nt}} } } } t|jd ƒƒ}x^t|dƒD]L}dt|ƒ}|j|ƒtd d|gƒtd dddgƒq]Wddl}tj|jƒtj|jjƒ}| rBddidt j ƒkp t j |ƒrt j|ƒndd 6}tt j|ƒƒ‚n|j}d } || ƒ} t| ƒ} | |k} | r¹t jdf| fdf| |fƒit j| ƒd6dt j ƒkpŃt j |ƒrćt j|ƒndd6dt j ƒkpt j tƒrt jtƒndd 6dt j ƒkp?t j |ƒrQt j|ƒndd6t j|ƒd6t j| ƒd6t j| ƒd6} ddi| d6}tt j|ƒƒ‚nt}} } } } t|jd ƒƒ}WdQXWdtjjt|ƒƒXdS( s• Regression test for https://github.com/astropy/astropy-helpers/issues/114 and for https://github.com/astropy/astropy-helpers/issues/107 ssetup.pytbuildNii’’’’Rsassert %(py0)sRRittestrepoRRs==sj%(py9)s {%(py9)s = %(py0)s(%(py7)s {%(py7)s = %(py3)s {%(py3)s = %(py1)s.group }(%(py5)s) }) } == %(py11)sR#tcorrect_revcountR%R&R'R(R)R*sassert %(py13)sR+is.testRRs-ms A message(RR0RRRRFRR3R4R>R7R8R5R9R:R;R<R&R=R tchdirRRBRCRDRR?R@trangetensureR(RRRHRRRKR^R]RPRQRRRSRVt @py_format12t @py_format14tidxt test_filename((sS/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_git_helpers.pyt"test_version_update_in_other_repos„sr   E   E  ’  E  ’Rs1.0.devs1.0c Cs†||ƒ}|jƒ8tddgƒzµddl}|j}g}|}|rkt|tƒ} | }n| rŲdidtjƒkp–tj |ƒrØtj |ƒndd6} |j | ƒ|r•ditj | ƒd 6d tjƒkpśtj tƒr tj tƒnd d 6dtjƒkp1tj |ƒrCtj |ƒndd 6d tjƒkphtj tƒrztj tƒnd d6} |j | ƒntj |dƒi} ddi| d6} t tj| ƒƒ‚nt}}} tj}d}|||ƒ}| rĻddidtjƒkp3tj tƒrEtj tƒndd6tj |ƒd6tj |ƒd 6dtjƒkpŠtj |ƒrœtj |ƒndd 6tj |ƒd6}t tj|ƒƒ‚nt}}}WdtdƒXtddddgƒtjtjjddƒƒ}t|ƒ}d}||k}| r+tjdf|fd f||fƒid!tjƒkpŠtj tƒrœtj tƒnd!d6d"tjƒkpĮtj |ƒrÓtj |ƒnd"d#6tj |ƒd$6tj |ƒd6}dd%i|d 6} t tj| ƒƒ‚nt}}}|j|dƒ}WdQX|jd&ƒ}tjt|ƒd'd(ƒ}|jt|ƒƒ|jƒåtjd)ƒd}tj|ƒtddgƒz¢ddl}tj dƒ}t!j"d* d+d+fkrq|j#}|ƒ}|j$}t|ƒ}||ƒ}| rXdd,id&tjƒkpetj |ƒrwtj |ƒnd&d 6d-tjƒkpœtj |ƒr®tj |ƒnd-d6tj |ƒd6tj |ƒd 6tj |ƒd6d.tjƒkptj tƒrtj tƒnd.d6tj |ƒd/6tj |ƒd06}t tj|ƒƒ‚nt}}}}}n|j}||k}| rctjdf|fd1f||fƒidtjƒkpŅtj |ƒrätj |ƒndd6tj |ƒd6dtjƒkptj |ƒr+tj |ƒndd 6}dd2i|d6}t tj|ƒƒ‚nt}}WdtdƒXWdQXdS(3sĀ Test for https://github.com/astropy/astropy-helpers/issues/87 Ensures that packages installed with astropy_helpers have a correct copy of the git hash of the installed commit. ssetup.pyR\i’’’’Ns%(py2)stgithashRs.%(py8)s {%(py8)s = %(py4)s(%(py5)s, %(py6)s) }R/t isinstanceRR)t _text_typeR iRsassert %(py11)sR%s [0-9a-f]{40}sPassert %(py7)s {%(py7)s = %(py2)s {%(py2)s = %(py0)s.match }(%(py4)s, %(py5)s) }treRR*Rtsdists--dist-dir=dists--formats=gztartdists*.tar.gzis==s0%(py3)s {%(py3)s = %(py0)s(%(py1)s) } == %(py6)stlenttgzsR'R(sassert %(py8)st build_dirtmodesr:gzs_eva_-*iis§assert %(py12)s {%(py12)s = %(py6)s {%(py6)s = %(py4)s {%(py4)s = %(py2)s {%(py2)s = %(py0)s.get_filename }() }.startswith }(%(py10)s {%(py10)s = %(py7)s(%(py8)s) }) }tloaderRFtpy12tpy10s3%(py2)s {%(py2)s = %(py0)s.__githash__ } == %(py4)ssassert %(py6)s(%RR0Rt __githash__RhRiR7R8R5R9R:tappendt_format_boolopR;R<R@RjR4R tglobtosRR RmR?R ttarfileRARFt extractallR_tpkgutilt get_loaderRt version_infot get_filenamet startswith(RRRRGRHRRgRLt @py_assert0t @py_assert7t @py_format3RZt @py_format10RbRMRRt @py_format8RnRPRYRQROttgzRottftpkg_dirRqt @py_assert9t @py_assert11t @py_format13RN((sS/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_git_helpers.pyttest_installed_git_versionµsŠ     A æ ¬   ¹    ’ ©(t __builtin__R7t_pytest.assertion.rewritet assertiontrewriteR5RwRCRxR{RjRRyRR}tPY3RFRitunicodetcompileR3RRtpytesttfixtureRR[Rftmarkt parametrizeR‹(((sS/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/tests/test_git_helpers.pyts(            4 1sunpy-0.6.3/astropy_helpers/astropy_helpers/__init__.py0000644000175000017500000000345412662554110024353 0ustar stuartstuart00000000000000try: from .version import version as __version__ from .version import githash as __githash__ except ImportError: __version__ = '' __githash__ = '' # If we've made it as far as importing astropy_helpers, we don't need # ah_bootstrap in sys.modules anymore. Getting rid of it is actually necessary # if the package we're installing has a setup_requires of another package that # uses astropy_helpers (and possibly a different version at that) # See https://github.com/astropy/astropy/issues/3541 import sys if 'ah_bootstrap' in sys.modules: del sys.modules['ah_bootstrap'] # Note, this is repeated from ah_bootstrap.py, but is here too in case this # astropy-helpers was upgraded to from an older version that did not have this # check in its ah_bootstrap. # matplotlib can cause problems if it is imported from within a call of # run_setup(), because in some circumstances it will try to write to the user's # home directory, resulting in a SandboxViolation. See # https://github.com/matplotlib/matplotlib/pull/4165 # Making sure matplotlib, if it is available, is imported early in the setup # process can mitigate this (note importing matplotlib.pyplot has the same # issue) try: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot except: # Ignore if this fails for *any* reason* pass import os # Ensure that all module-level code in astropy or other packages know that # we're in setup mode: if ('__main__' in sys.modules and hasattr(sys.modules['__main__'], '__file__')): filename = os.path.basename(sys.modules['__main__'].__file__) if filename.rstrip('co') == 'setup.py': if sys.version_info[0] >= 3: import builtins else: import __builtin__ as builtins builtins._ASTROPY_SETUP_ = True del filename sunpy-0.6.3/astropy_helpers/astropy_helpers/setup_helpers.py0000644000175000017500000006310612662554110025476 0ustar stuartstuart00000000000000# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module contains a number of utilities for use during setup/build/packaging that are useful to astropy as a whole. """ from __future__ import absolute_import, print_function import collections import os import re import shutil import subprocess import sys import textwrap import traceback import warnings from distutils import log from distutils.dist import Distribution from distutils.errors import DistutilsOptionError, DistutilsModuleError from distutils.core import Extension from distutils.core import Command from distutils.command.sdist import sdist as DistutilsSdist from setuptools import find_packages as _find_packages from .distutils_helpers import * from .version_helpers import get_pkg_version_module from .utils import (silence, walk_skip_hidden, import_file, extends_doc, resolve_name, AstropyDeprecationWarning) from .commands.build_ext import generate_build_ext_command from .commands.build_py import AstropyBuildPy from .commands.install import AstropyInstall from .commands.install_lib import AstropyInstallLib from .commands.register import AstropyRegister from .commands.test import AstropyTest # These imports are not used in this module, but are included for backwards # compat with older versions of this module from .utils import get_numpy_include_path, write_if_different from .commands.build_ext import should_build_with_cython, get_compiler_version _module_state = { 'registered_commands': None, 'have_sphinx': False, 'package_cache': None, } try: import sphinx _module_state['have_sphinx'] = True except ValueError as e: # This can occur deep in the bowels of Sphinx's imports by way of docutils # and an occurrence of this bug: http://bugs.python.org/issue18378 # In this case sphinx is effectively unusable if 'unknown locale' in e.args[0]: log.warn( "Possible 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/") except ImportError: pass except SyntaxError: # occurs if markupsafe is recent version, which doesn't support Python 3.2 pass PY3 = sys.version_info[0] >= 3 # This adds a new keyword to the setup() function Distribution.skip_2to3 = [] def adjust_compiler(package): """ This function detects broken compilers and switches to another. If the environment variable CC is explicitly set, or a compiler is specified on the commandline, no override is performed -- the purpose here is to only override a default compiler. The specific compilers with problems are: * The default compiler in XCode-4.2, llvm-gcc-4.2, segfaults when compiling wcslib. The set of broken compilers can be updated by changing the compiler_mapping variable. It is a list of 2-tuples where the first in the pair is a regular expression matching the version of the broken compiler, and the second is the compiler to change to. """ warnings.warn( 'Direct use of the adjust_compiler function in setup.py is ' 'deprecated and can be removed from your setup.py. This ' 'functionality is now incorporated directly into the build_ext ' 'command.', AstropyDeprecationWarning) def get_debug_option(packagename): """ Determines if the build is in debug mode. Returns ------- debug : bool True if the current build was started with the debug option, False otherwise. """ try: current_debug = get_pkg_version_module(packagename, fromlist=['debug'])[0] except (ImportError, AttributeError): current_debug = None # Only modify the debug flag if one of the build commands was explicitly # run (i.e. not as a sub-command of something else) dist = get_dummy_distribution() if any(cmd in dist.commands for cmd in ['build', 'build_ext']): debug = bool(get_distutils_build_option('debug')) else: debug = bool(current_debug) if current_debug is not None and current_debug != debug: build_ext_cmd = dist.get_command_class('build_ext') build_ext_cmd.force_rebuild = True return debug def register_commands(package, version, release, srcdir='.'): if _module_state['registered_commands'] is not None: return _module_state['registered_commands'] if _module_state['have_sphinx']: from .commands.build_sphinx import AstropyBuildSphinx, AstropyBuildDocs else: AstropyBuildSphinx = AstropyBuildDocs = FakeBuildSphinx _module_state['registered_commands'] = registered_commands = { 'test': generate_test_command(package), # Use distutils' sdist because it respects package_data. # setuptools/distributes sdist requires duplication of information in # MANIFEST.in 'sdist': DistutilsSdist, # The exact form of the build_ext command depends on whether or not # we're building a release version 'build_ext': generate_build_ext_command(package, release), # We have a custom build_py to generate the default configuration file 'build_py': AstropyBuildPy, # Since install can (in some circumstances) be run without # first building, we also need to override install and # install_lib. See #2223 'install': AstropyInstall, 'install_lib': AstropyInstallLib, 'register': AstropyRegister, 'build_sphinx': AstropyBuildSphinx, 'build_docs': AstropyBuildDocs } # Need to override the __name__ here so that the commandline options are # presented as being related to the "build" command, for example; normally # this wouldn't be necessary since commands also have a command_name # attribute, but there is a bug in distutils' help display code that it # uses __name__ instead of command_name. Yay distutils! for name, cls in registered_commands.items(): cls.__name__ = name # Add a few custom options; more of these can be added by specific packages # later for option in [ ('use-system-libraries', "Use system libraries whenever possible", True)]: add_command_option('build', *option) add_command_option('install', *option) add_command_hooks(registered_commands, srcdir=srcdir) return registered_commands def add_command_hooks(commands, srcdir='.'): """ Look through setup_package.py modules for functions with names like ``pre__hook`` and ``post__hook`` where ```` is the name of a ``setup.py`` command (e.g. build_ext). If either hook is present this adds a wrapped version of that command to the passed in ``commands`` `dict`. ``commands`` may be pre-populated with other custom distutils command classes that should be wrapped if there are hooks for them (e.g. `AstropyBuildPy`). """ hook_re = re.compile(r'^(pre|post)_(.+)_hook$') # Distutils commands have a method of the same name, but it is not a # *classmethod* (which probably didn't exist when distutils was first # written) def get_command_name(cmdcls): if hasattr(cmdcls, 'command_name'): return cmdcls.command_name else: return cmdcls.__name__ packages = filter_packages(find_packages(srcdir)) dist = get_dummy_distribution() hooks = collections.defaultdict(dict) for setuppkg in iter_setup_packages(srcdir, packages): for name, obj in vars(setuppkg).items(): match = hook_re.match(name) if not match: continue hook_type = match.group(1) cmd_name = match.group(2) cmd_cls = dist.get_command_class(cmd_name) if hook_type not in hooks[cmd_name]: hooks[cmd_name][hook_type] = [] hooks[cmd_name][hook_type].append((setuppkg.__name__, obj)) for cmd_name, cmd_hooks in hooks.items(): commands[cmd_name] = generate_hooked_command( cmd_name, dist.get_command_class(cmd_name), cmd_hooks) def generate_hooked_command(cmd_name, cmd_cls, hooks): """ Returns a generated subclass of ``cmd_cls`` that runs the pre- and post-command hooks for that command before and after the ``cmd_cls.run`` method. """ def run(self, orig_run=cmd_cls.run): self.run_command_hooks('pre_hooks') orig_run(self) self.run_command_hooks('post_hooks') return type(cmd_name, (cmd_cls, object), {'run': run, 'run_command_hooks': run_command_hooks, 'pre_hooks': hooks.get('pre', []), 'post_hooks': hooks.get('post', [])}) def run_command_hooks(cmd_obj, hook_kind): """Run hooks registered for that command and phase. *cmd_obj* is a finalized command object; *hook_kind* is either 'pre_hook' or 'post_hook'. """ hooks = getattr(cmd_obj, hook_kind, None) if not hooks: return for modname, hook in hooks: if isinstance(hook, str): try: hook_obj = resolve_name(hook) except ImportError as exc: raise DistutilsModuleError( 'cannot find hook {0}: {1}'.format(hook, err)) else: hook_obj = hook if not callable(hook_obj): raise DistutilsOptionError('hook {0!r} is not callable' % hook) log.info('running {0} from {1} for {2} command'.format( hook_kind.rstrip('s'), modname, cmd_obj.get_command_name())) try : hook_obj(cmd_obj) except Exception as exc: log.error('{0} command hook {1} raised an exception: %s\n'.format( hook_obj.__name__, cmd_obj.get_command_name())) log.error(traceback.format_exc()) sys.exit(1) def generate_test_command(package_name): """ Creates a custom 'test' command for the given package which sets the command's ``package_name`` class attribute to the name of the package being tested. """ return type(package_name.title() + 'Test', (AstropyTest,), {'package_name': package_name}) def update_package_files(srcdir, extensions, package_data, packagenames, package_dirs): """ 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. """ info = get_package_info(srcdir) extensions.extend(info['ext_modules']) package_data.update(info['package_data']) packagenames = list(set(packagenames + info['packages'])) package_dirs.update(info['package_dir']) def get_package_info(srcdir='.', exclude=()): """ 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. - ``get_entry_points()`` returns a dict formatted as required by the ``entry_points`` argument to ``setup()``. - ``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`. """ ext_modules = [] packages = [] package_data = {} package_dir = {} skip_2to3 = [] # Use the find_packages tool to locate all packages and modules packages = filter_packages(find_packages(srcdir, exclude=exclude)) # For each of the setup_package.py modules, extract any # information that is needed to install them. The build options # are extracted first, so that their values will be available in # subsequent calls to `get_extensions`, etc. for setuppkg in iter_setup_packages(srcdir, packages): if hasattr(setuppkg, 'get_build_options'): options = setuppkg.get_build_options() for option in options: add_command_option('build', *option) if hasattr(setuppkg, 'get_external_libraries'): libraries = setuppkg.get_external_libraries() for library in libraries: add_external_library(library) if hasattr(setuppkg, 'requires_2to3'): requires_2to3 = setuppkg.requires_2to3() else: requires_2to3 = True if not requires_2to3: skip_2to3.append( os.path.dirname(setuppkg.__file__)) for setuppkg in iter_setup_packages(srcdir, packages): # get_extensions must include any Cython extensions by their .pyx # filename. if hasattr(setuppkg, 'get_extensions'): ext_modules.extend(setuppkg.get_extensions()) if hasattr(setuppkg, 'get_package_data'): package_data.update(setuppkg.get_package_data()) # Locate any .pyx files not already specified, and add their extensions in. # The default include dirs include numpy to facilitate numerical work. ext_modules.extend(get_cython_extensions(srcdir, packages, ext_modules, ['numpy'])) # Now remove extensions that have the special name 'skip_cython', as they # exist Only to indicate that the cython extensions shouldn't be built for i, ext in reversed(list(enumerate(ext_modules))): if ext.name == 'skip_cython': del ext_modules[i] # On Microsoft compilers, we need to pass the '/MANIFEST' # commandline argument. This was the default on MSVC 9.0, but is # now required on MSVC 10.0, but it doesn't seem to hurt to add # it unconditionally. if get_compiler_option() == 'msvc': for ext in ext_modules: ext.extra_link_args.append('/MANIFEST') return { 'ext_modules': ext_modules, 'packages': packages, 'package_dir': package_dir, 'package_data': package_data, 'skip_2to3': skip_2to3 } def iter_setup_packages(srcdir, packages): """ 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. """ for packagename in packages: package_parts = packagename.split('.') package_path = os.path.join(srcdir, *package_parts) setup_package = os.path.relpath( os.path.join(package_path, 'setup_package.py')) if os.path.isfile(setup_package): module = import_file(setup_package, name=packagename + '.setup_package') yield module def iter_pyx_files(package_dir, package_name): """ 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. """ for dirpath, dirnames, filenames in walk_skip_hidden(package_dir): for fn in filenames: if fn.endswith('.pyx'): fullfn = os.path.relpath(os.path.join(dirpath, fn)) # Package must match file name extmod = '.'.join([package_name, fn[:-4]]) yield (extmod, fullfn) break # Don't recurse into subdirectories def get_cython_extensions(srcdir, packages, prevextensions=tuple(), extincludedirs=None): """ 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`). """ # Vanilla setuptools and old versions of distribute include Cython files # as .c files in the sources, not .pyx, so we cannot simply look for # existing .pyx sources in the previous sources, but we should also check # for .c files with the same remaining filename. So we look for .pyx and # .c files, and we strip the extension. prevsourcepaths = [] ext_modules = [] for ext in prevextensions: for s in ext.sources: if s.endswith(('.pyx', '.c', '.cpp')): sourcepath = os.path.realpath(os.path.splitext(s)[0]) prevsourcepaths.append(sourcepath) for package_name in packages: package_parts = package_name.split('.') package_path = os.path.join(srcdir, *package_parts) for extmod, pyxfn in iter_pyx_files(package_path, package_name): sourcepath = os.path.realpath(os.path.splitext(pyxfn)[0]) if sourcepath not in prevsourcepaths: ext_modules.append(Extension(extmod, [pyxfn], include_dirs=extincludedirs)) return ext_modules class DistutilsExtensionArgs(collections.defaultdict): """ 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. """ def __init__(self, *args, **kwargs): def default_factory(): return [] super(DistutilsExtensionArgs, self).__init__( default_factory, *args, **kwargs) def update(self, other): for key, val in other.items(): self[key].extend(val) def pkg_config(packages, default_libraries, executable='pkg-config'): """ 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 """ flag_map = {'-I': 'include_dirs', '-L': 'library_dirs', '-l': 'libraries', '-D': 'define_macros', '-U': 'undef_macros'} command = "{0} --libs --cflags {1}".format(executable, ' '.join(packages)), result = DistutilsExtensionArgs() try: pipe = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE) output = pipe.communicate()[0].strip() except subprocess.CalledProcessError as e: lines = [ "{0} failed. This may cause the build to fail below.".format(executable), " command: {0}".format(e.cmd), " returncode: {0}".format(e.returncode), " output: {0}".format(e.output) ] log.warn('\n'.join(lines)) result['libraries'].extend(default_libraries) else: if pipe.returncode != 0: lines = [ "pkg-config could not lookup up package(s) {0}.".format( ", ".join(packages)), "This may cause the build to fail below." ] log.warn('\n'.join(lines)) result['libraries'].extend(default_libraries) else: for token in output.split(): # It's not clear what encoding the output of # pkg-config will come to us in. It will probably be # some combination of pure ASCII (for the compiler # flags) and the filesystem encoding (for any argument # that includes directories or filenames), but this is # just conjecture, as the pkg-config documentation # doesn't seem to address it. arg = token[:2].decode('ascii') value = token[2:].decode(sys.getfilesystemencoding()) if arg in flag_map: if arg == '-D': value = tuple(value.split('=', 1)) result[flag_map[arg]].append(value) else: result['extra_compile_args'].append(value) return result def add_external_library(library): """ 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`. """ for command in ['build', 'build_ext', 'install']: add_command_option(command, str('use-system-' + library), 'Use the system {0} library'.format(library), is_bool=True) def use_system_library(library): """ 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. """ return ( get_distutils_build_or_install_option('use_system_{0}'.format(library)) or get_distutils_build_or_install_option('use_system_libraries')) @extends_doc(_find_packages) def find_packages(where='.', exclude=(), invalidate_cache=False): """ This version of ``find_packages`` caches previous results to speed up subsequent calls. Use ``invalide_cache=True`` to ignore cached results from previous ``find_packages`` calls, and repeat the package search. """ if not invalidate_cache and _module_state['package_cache'] is not None: return _module_state['package_cache'] packages = _find_packages(where=where, exclude=exclude) _module_state['package_cache'] = packages return packages def filter_packages(packagenames): """ Removes some packages from the package list that shouldn't be installed on the current version of Python. """ if PY3: exclude = '_py2' else: exclude = '_py3' return [x for x in packagenames if not x.endswith(exclude)] class FakeBuildSphinx(Command): """ A dummy build_sphinx command that is called if Sphinx is not installed and displays a relevant error message """ #user options inherited from sphinx.setup_command.BuildDoc user_options = [ ('fresh-env', 'E', '' ), ('all-files', 'a', ''), ('source-dir=', 's', ''), ('build-dir=', None, ''), ('config-dir=', 'c', ''), ('builder=', 'b', ''), ('project=', None, ''), ('version=', None, ''), ('release=', None, ''), ('today=', None, ''), ('link-index', 'i', ''), ] #user options appended in astropy.setup_helpers.AstropyBuildSphinx user_options.append(('warnings-returncode', 'w','')) user_options.append(('clean-docs', 'l', '')) user_options.append(('no-intersphinx', 'n', '')) user_options.append(('open-docs-in-browser', 'o','')) def initialize_options(self): try: raise RuntimeError("Sphinx must be installed for build_sphinx") except: log.error('error : Sphinx must be installed for build_sphinx') sys.exit(1) sunpy-0.6.3/astropy_helpers/astropy_helpers/test_helpers.pyc0000644000175000017500000000114012662555021025450 0ustar stuartstuart00000000000000ó HŲŹVc@`sRddlmZmZmZmZddlZddlmZejde ƒdS(i(tabsolute_importtdivisiontprint_functiontunicode_literalsNi(t AstropyTestu‘The astropy_helpers.test_helpers module is deprecated as of version 1.1.0; the AstropyTest command can be found in astropy_helpers.commands.test.( t __future__RRRRtwarningst commands.testRtwarntDeprecationWarning(((sI/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/test_helpers.pyts"  sunpy-0.6.3/astropy_helpers/astropy_helpers/compat/0000755000175000017500000000000012675276744023541 5ustar stuartstuart00000000000000sunpy-0.6.3/astropy_helpers/astropy_helpers/compat/__init__.py0000644000175000017500000000056012622602515025630 0ustar stuartstuart00000000000000def _fix_user_options(options): """ This is for Python 2.x and 3.x compatibility. distutils expects Command options to all be byte strings on Python 2 and Unicode strings on Python 3. """ def to_str_or_none(x): if x is None: return None return str(x) return [tuple(to_str_or_none(x) for x in y) for y in options] sunpy-0.6.3/astropy_helpers/astropy_helpers/compat/_subprocess_py2/0000755000175000017500000000000012675276744026662 5ustar stuartstuart00000000000000sunpy-0.6.3/astropy_helpers/astropy_helpers/compat/_subprocess_py2/__init__.py0000644000175000017500000000243212622602515030751 0ustar stuartstuart00000000000000from __future__ import absolute_import from subprocess import * def check_output(*popenargs, **kwargs): r"""Run command with arguments and return its output as a byte string. If the exit code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and output in the output attribute. The arguments are the same as for the Popen constructor. Example:: >>> check_output(["ls", "-l", "/dev/null"]) 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n' The stdout argument is not allowed as it is used internally. To capture standard error in the result, use stderr=STDOUT.:: >>> check_output(["/bin/sh", "-c", ... "ls -l non_existent_file ; exit 0"], ... stderr=STDOUT) 'ls: non_existent_file: No such file or directory\n' """ if 'stdout' in kwargs: raise ValueError('stdout argument not allowed, it will be overridden.') process = Popen(stdout=PIPE, *popenargs, **kwargs) output, unused_err = process.communicate() retcode = process.poll() if retcode: cmd = kwargs.get("args") if cmd is None: cmd = popenargs[0] raise CalledProcessError(retcode, cmd) return output sunpy-0.6.3/astropy_helpers/astropy_helpers/compat/__init__.pyc0000644000175000017500000000175412622602515026001 0ustar stuartstuart00000000000000ó MKVc@s d„ZdS(cs6d„‰g|D]"}t‡fd†|Dƒƒ^qS(s¢ This is for Python 2.x and 3.x compatibility. distutils expects Command options to all be byte strings on Python 2 and Unicode strings on Python 3. cSs|dkrdSt|ƒS(N(tNonetstr(tx((sL/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/compat/__init__.pytto_str_or_nones c3s|]}ˆ|ƒVqdS(N((t.0R(R(sL/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/compat/__init__.pys s(ttuple(toptionsty((RsL/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/compat/__init__.pyt_fix_user_optionss N(R(((sL/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/compat/__init__.pytssunpy-0.6.3/astropy_helpers/astropy_helpers/compat/subprocess.py0000644000175000017500000000105012622602515026254 0ustar stuartstuart00000000000000""" A replacement wrapper around the subprocess module that adds check_output (which was only added to Python in 2.7. Instead of importing subprocess, other modules should use this as follows:: from astropy.utils.compat import subprocess This module is safe to import from anywhere within astropy. """ from __future__ import absolute_import, print_function import subprocess # python2.7 and later provide a check_output method if not hasattr(subprocess, 'check_output'): from ._subprocess_py2 import check_output from subprocess import * sunpy-0.6.3/astropy_helpers/astropy_helpers/compat/__pycache__/0000755000175000017500000000000012675276744025751 5ustar stuartstuart00000000000000sunpy-0.6.3/astropy_helpers/astropy_helpers/compat/__pycache__/__init__.cpython-35.pyc0000644000175000017500000000167712643740130032124 0ustar stuartstuart00000000000000 MKVpć@sdd„ZdS)cs#dd„‰‡fdd†|DƒS)z¢ This is for Python 2.x and 3.x compatibility. distutils expects Command options to all be byte strings on Python 2 and Unicode strings on Python 3. cSs|dkrdSt|ƒS)N)Śstr)Śx©rśL/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/compat/__init__.pyŚto_str_or_nones z)_fix_user_options..to_str_or_nonecs/g|]%}t‡fdd†|Dƒƒ‘qS)c3s|]}ˆ|ƒVqdS)Nr)Ś.0r)rrrś sz/_fix_user_options...)Śtuple)rŚy)rrrś s z%_fix_user_options..r)Śoptionsr)rrŚ_fix_user_optionss r N)r rrrrŚssunpy-0.6.3/astropy_helpers/astropy_helpers/test_helpers.py0000644000175000017500000000077312662554110025316 0ustar stuartstuart00000000000000from __future__ import (absolute_import, division, print_function, unicode_literals) import warnings from .commands.test import AstropyTest # Leaving this module here for now, but really it needn't exist # (and it's doubtful that any code depends on it anymore) warnings.warn('The astropy_helpers.test_helpers module is deprecated as ' 'of version 1.1.0; the AstropyTest command can be found in ' 'astropy_helpers.commands.test.', DeprecationWarning) sunpy-0.6.3/astropy_helpers/astropy_helpers/commands/0000755000175000017500000000000012675276744024057 5ustar stuartstuart00000000000000sunpy-0.6.3/astropy_helpers/astropy_helpers/commands/src/0000755000175000017500000000000012675276744024646 5ustar stuartstuart00000000000000sunpy-0.6.3/astropy_helpers/astropy_helpers/commands/src/compiler.c0000644000175000017500000000573112622602515026607 0ustar stuartstuart00000000000000#include /*************************************************************************** * Macros for determining the compiler version. * * These are borrowed from boost, and majorly abridged to include only * the compilers we care about. ***************************************************************************/ #ifndef PY3K #if PY_MAJOR_VERSION >= 3 #define PY3K 1 #else #define PY3K 0 #endif #endif #define STRINGIZE(X) DO_STRINGIZE(X) #define DO_STRINGIZE(X) #X #if defined __clang__ /* Clang C++ emulates GCC, so it has to appear early. */ # define COMPILER "Clang version " __clang_version__ #elif defined(__INTEL_COMPILER) || defined(__ICL) || defined(__ICC) || defined(__ECC) /* Intel */ # if defined(__INTEL_COMPILER) # define INTEL_VERSION __INTEL_COMPILER # elif defined(__ICL) # define INTEL_VERSION __ICL # elif defined(__ICC) # define INTEL_VERSION __ICC # elif defined(__ECC) # define INTEL_VERSION __ECC # endif # define COMPILER "Intel C compiler version " STRINGIZE(INTEL_VERSION) #elif defined(__GNUC__) /* gcc */ # define COMPILER "GCC version " __VERSION__ #elif defined(__SUNPRO_CC) /* Sun Workshop Compiler */ # define COMPILER "Sun compiler version " STRINGIZE(__SUNPRO_CC) #elif defined(_MSC_VER) /* Microsoft Visual C/C++ Must be last since other compilers define _MSC_VER for compatibility as well */ # if _MSC_VER < 1200 # define COMPILER_VERSION 5.0 # elif _MSC_VER < 1300 # define COMPILER_VERSION 6.0 # elif _MSC_VER == 1300 # define COMPILER_VERSION 7.0 # elif _MSC_VER == 1310 # define COMPILER_VERSION 7.1 # elif _MSC_VER == 1400 # define COMPILER_VERSION 8.0 # elif _MSC_VER == 1500 # define COMPILER_VERSION 9.0 # elif _MSC_VER == 1600 # define COMPILER_VERSION 10.0 # else # define COMPILER_VERSION _MSC_VER # endif # define COMPILER "Microsoft Visual C++ version " STRINGIZE(COMPILER_VERSION) #else /* Fallback */ # define COMPILER "Unknown compiler" #endif /*************************************************************************** * Module-level ***************************************************************************/ struct module_state { /* The Sun compiler can't handle empty structs */ #if defined(__SUNPRO_C) || defined(_MSC_VER) int _dummy; #endif }; #if PY3K static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "_compiler", NULL, sizeof(struct module_state), NULL, NULL, NULL, NULL, NULL }; #define INITERROR return NULL PyMODINIT_FUNC PyInit__compiler(void) #else #define INITERROR return PyMODINIT_FUNC init_compiler(void) #endif { PyObject* m; #if PY3K m = PyModule_Create(&moduledef); #else m = Py_InitModule3("_compiler", NULL, NULL); #endif if (m == NULL) INITERROR; PyModule_AddStringConstant(m, "compiler", COMPILER); #if PY3K return m; #endif } sunpy-0.6.3/astropy_helpers/astropy_helpers/commands/install_lib.pyc0000644000175000017500000000173012622602515027046 0ustar stuartstuart00000000000000ó MKVc@s:ddlmZddlmZdefd„ƒYZdS(i’’’’(t install_libi(t_get_platlib_dirtAstropyInstallLibcBs%eZejZejZd„ZRS(cCs5|jdƒ}t|ƒ}||_tj|ƒdS(Ntbuild(tget_finalized_commandRt build_dirtSetuptoolsInstallLibtfinalize_options(tselft build_cmdt platlib_dir((sQ/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/commands/install_lib.pyR s  (t__name__t __module__Rt user_optionstboolean_optionsR(((sQ/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/commands/install_lib.pyRs  N(tsetuptools.command.install_libRRtutilsRR(((sQ/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/commands/install_lib.pytssunpy-0.6.3/astropy_helpers/astropy_helpers/commands/_dummy.py0000644000175000017500000000557412662554110025714 0ustar stuartstuart00000000000000""" Provides a base class for a 'dummy' setup.py command that has no functionality (probably due to a missing requirement). This dummy command can raise an exception when it is run, explaining to the user what dependencies must be met to use this command. The reason this is at all tricky is that we want the command to be able to provide this message even when the user passes arguments to the command. If we don't know ahead of time what arguments the command can take, this is difficult, because distutils does not allow unknown arguments to be passed to a setup.py command. This hacks around that restriction to provide a useful error message even when a user passes arguments to the dummy implementation of a command. Use this like: try: from some_dependency import SetupCommand except ImportError: from ._dummy import _DummyCommand class SetupCommand(_DummyCommand): description = \ 'Implementation of SetupCommand from some_dependency; ' 'some_dependency must be installed to run this command' # This is the message that will be raised when a user tries to # run this command--define it as a class attribute. error_msg = \ "The 'setup_command' command requires the some_dependency " "package to be installed and importable." """ import sys from setuptools import Command from distutils.errors import DistutilsArgError from textwrap import dedent class _DummyCommandMeta(type): """ Causes an exception to be raised on accessing attributes of a command class so that if ``./setup.py command_name`` is run with additional command-line options we can provide a useful error message instead of the default that tells users the options are unrecognized. """ def __init__(cls, name, bases, members): if bases == (Command, object): # This is the _DummyCommand base class, presumably return if not hasattr(cls, 'description'): raise TypeError( "_DummyCommand subclass must have a 'description' " "attribute.") if not hasattr(cls, 'error_msg'): raise TypeError( "_DummyCommand subclass must have an 'error_msg' " "attribute.") def __getattribute__(cls, attr): if attr in ('description', 'error_msg'): # Allow cls.description to work so that `./setup.py # --help-commands` still works return super(_DummyCommandMeta, cls).__getattribute__(attr) raise DistutilsArgError(cls.error_msg) if sys.version_info[0] < 3: exec(dedent(""" class _DummyCommand(Command, object): __metaclass__ = _DummyCommandMeta """)) else: exec(dedent(""" class _DummyCommand(Command, object, metaclass=_DummyCommandMeta): pass """)) sunpy-0.6.3/astropy_helpers/astropy_helpers/commands/setup_package.py0000644000175000017500000000016712622602515027225 0ustar stuartstuart00000000000000from os.path import join def get_package_data(): return {'astropy_helpers.commands': [join('src', 'compiler.c')]} sunpy-0.6.3/astropy_helpers/astropy_helpers/commands/_test_compat.py0000644000175000017500000002666212662554110027104 0ustar stuartstuart00000000000000""" Old implementation of ``./setup.py test`` command. This has been moved to astropy.tests as of Astropy v1.1.0, but a copy of the implementation is kept here for backwards compatibility. """ from __future__ import absolute_import, unicode_literals import inspect import os import shutil import subprocess import sys import tempfile from setuptools import Command from ..compat import _fix_user_options PY3 = sys.version_info[0] == 3 class AstropyTest(Command, object): description = 'Run the tests for this package' user_options = [ ('package=', 'P', "The 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', 'Specify 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', "Enable 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', 'Enable PEP8 checking and disable regular tests. ' 'Requires the pytest-pep8 plugin.'), ('pdb', 'd', 'Start the interactive Python debugger on errors.'), ('coverage', 'c', 'Create a coverage report. Requires the coverage package.'), ('open-files', 'o', 'Fail if any tests leave files open. Requires the ' 'psutil package.'), ('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=', None, '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', None, "Don't test the documentation .rst files."), ('repeat=', None, 'How many times to repeat each test (can be used to check for ' 'sporadic failures).'), ('temp-root=', None, 'The root directory in which to create the temporary testing files. ' 'If unspecified the system default is used (e.g. /tmp) as explained ' 'in the documentation for tempfile.mkstemp.') ] user_options = _fix_user_options(user_options) package_name = '' def initialize_options(self): self.package = None self.test_path = None self.verbose_results = False self.plugins = None self.pastebin = None self.args = None self.remote_data = False self.pep8 = False self.pdb = False self.coverage = False self.open_files = False self.parallel = 0 self.docs_path = None self.skip_docs = False self.repeat = None self.temp_root = None def finalize_options(self): # Normally we would validate the options here, but that's handled in # run_tests pass # Most of the test runner arguments have the same name as attributes on # this command class, with one exception (for now) _test_runner_arg_attr_map = { 'verbose': 'verbose_results' } def generate_testing_command(self): """ Build a Python script to run the tests. """ cmd_pre = '' # Commands to run before the test function cmd_post = '' # Commands to run after the test function if self.coverage: pre, post = self._generate_coverage_commands() cmd_pre += pre cmd_post += post def get_attr(arg): attr = self._test_runner_arg_attr_map.get(arg, arg) return getattr(self, attr) test_args = filter(lambda arg: hasattr(self, arg), self._get_test_runner_args()) test_args = ', '.join('{0}={1!r}'.format(arg, get_attr(arg)) for arg in test_args) if PY3: set_flag = "import builtins; builtins._ASTROPY_TEST_ = True" else: set_flag = "import __builtin__; __builtin__._ASTROPY_TEST_ = True" cmd = ('{cmd_pre}{0}; import {1.package_name}, sys; result = ' '{1.package_name}.test({test_args}); {cmd_post}' 'sys.exit(result)') return cmd.format(set_flag, self, cmd_pre=cmd_pre, cmd_post=cmd_post, test_args=test_args) def _validate_required_deps(self): """ This method checks that any required modules are installed before running the tests. """ try: import astropy except ImportError: raise ImportError( "The 'test' command requires the astropy package to be " "installed and importable.") def run(self): """ Run the tests! """ # Ensure there is a doc path if self.docs_path is None: if os.path.exists('docs'): self.docs_path = os.path.abspath('docs') # Build a testing install of the package self._build_temp_install() # Ensure all required packages are installed self._validate_required_deps() # Run everything in a try: finally: so that the tmp dir gets deleted. try: # Construct this modules testing command cmd = self.generate_testing_command() # Run the tests in a subprocess--this is necessary since # new extension modules may have appeared, and this is the # easiest way to set up a new environment # On Python 3.x prior to 3.3, the creation of .pyc files # is not atomic. py.test jumps through some hoops to make # this work by parsing import statements and carefully # importing files atomically. However, it can't detect # when __import__ is used, so its carefulness still fails. # The solution here (admittedly a bit of a hack), is to # turn off the generation of .pyc files altogether by # passing the `-B` switch to `python`. This does mean # that each core will have to compile .py file to bytecode # itself, rather than getting lucky and borrowing the work # already done by another core. Compilation is an # insignificant fraction of total testing time, though, so # it's probably not worth worrying about. retcode = subprocess.call([sys.executable, '-B', '-c', cmd], cwd=self.testing_path, close_fds=False) finally: # Remove temporary directory shutil.rmtree(self.tmp_dir) raise SystemExit(retcode) def _build_temp_install(self): """ 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 """ self.reinitialize_command('build', inplace=True) self.run_command('build') build_cmd = self.get_finalized_command('build') new_path = os.path.abspath(build_cmd.build_lib) # On OSX the default path for temp files is under /var, but in most # cases on OSX /var is actually a symlink to /private/var; ensure we # dereference that link, because py.test is very sensitive to relative # paths... tmp_dir = tempfile.mkdtemp(prefix=self.package_name + '-test-', dir=self.temp_root) self.tmp_dir = os.path.realpath(tmp_dir) self.testing_path = os.path.join(self.tmp_dir, os.path.basename(new_path)) shutil.copytree(new_path, self.testing_path) new_docs_path = os.path.join(self.tmp_dir, os.path.basename(self.docs_path)) shutil.copytree(self.docs_path, new_docs_path) self.docs_path = new_docs_path shutil.copy('setup.cfg', self.tmp_dir) def _generate_coverage_commands(self): """ This method creates the post and pre commands if coverage is to be generated """ if self.parallel != 0: raise ValueError( "--coverage can not be used with --parallel") try: import coverage except ImportError: raise ImportError( "--coverage requires that the coverage package is " "installed.") # Don't use get_pkg_data_filename here, because it # requires importing astropy.config and thus screwing # up coverage results for those packages. coveragerc = os.path.join( self.testing_path, self.package_name, 'tests', 'coveragerc') # We create a coveragerc that is specific to the version # of Python we're running, so that we can mark branches # as being specifically for Python 2 or Python 3 with open(coveragerc, 'r') as fd: coveragerc_content = fd.read() if PY3: ignore_python_version = '2' else: ignore_python_version = '3' coveragerc_content = coveragerc_content.replace( "{ignore_python_version}", ignore_python_version).replace( "{packagename}", self.package_name) tmp_coveragerc = os.path.join(self.tmp_dir, 'coveragerc') with open(tmp_coveragerc, 'wb') as tmp: tmp.write(coveragerc_content.encode('utf-8')) cmd_pre = ( 'import coverage; ' 'cov = coverage.coverage(data_file="{0}", config_file="{1}"); ' 'cov.start();'.format( os.path.abspath(".coverage"), tmp_coveragerc)) cmd_post = ( 'cov.stop(); ' 'from astropy.tests.helper import _save_coverage; ' '_save_coverage(cov, result, "{0}", "{1}");'.format( os.path.abspath('.'), self.testing_path)) return cmd_pre, cmd_post def _get_test_runner_args(self): """ A hack to determine what arguments are supported by the package's test() function. In the future there should be a more straightforward API to determine this (really it should be determined by the ``TestRunner`` class for whatever version of Astropy is in use). """ if PY3: import builtins builtins._ASTROPY_TEST_ = True else: import __builtin__ __builtin__._ASTROPY_TEST_ = True try: pkg = __import__(self.package_name) if not hasattr(pkg, 'test'): raise ImportError( 'package {0} does not have a {0}.test() function as ' 'required by the Astropy test runner'.format(package_name)) argspec = inspect.getargspec(pkg.test) return argspec.args finally: if PY3: del builtins._ASTROPY_TEST_ else: del __builtin__._ASTROPY_TEST_ sunpy-0.6.3/astropy_helpers/astropy_helpers/commands/__init__.py0000644000175000017500000000000012622602515026133 0ustar stuartstuart00000000000000sunpy-0.6.3/astropy_helpers/astropy_helpers/commands/install.pyc0000644000175000017500000000167612622602515026231 0ustar stuartstuart00000000000000ó MKVc@s:ddlmZddlmZdefd„ƒYZdS(i’’’’(tinstalli(t_get_platlib_dirtAstropyInstallcBs%eZejZejZd„ZRS(cCs5|jdƒ}t|ƒ}||_tj|ƒdS(Ntbuild(tget_finalized_commandRt build_libtSetuptoolsInstalltfinalize_options(tselft build_cmdt platlib_dir((sM/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/commands/install.pyR s  (t__name__t __module__Rt user_optionstboolean_optionsR(((sM/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/commands/install.pyRs  N(tsetuptools.command.installRRtutilsRR(((sM/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/commands/install.pytssunpy-0.6.3/astropy_helpers/astropy_helpers/commands/_test_compat.pyc0000644000175000017500000002733712645420753027255 0ustar stuartstuart00000000000000ó z!–Vc@@s“dZddlmZmZddlZddlZddlZddlZddlZddl Z ddl m Z ddl m Z ejddkZde efd „ƒYZdS( u» Old implementation of ``./setup.py test`` command. This has been moved to astropy.tests as of Astropy v1.1.0, but a copy of the implementation is kept here for backwards compatibility. i(tabsolute_importtunicode_literalsN(tCommandi(t_fix_user_optionsit AstropyTestcB@s«eZdZd8d9d:d;d<d=d>d?d@dAdBdCdEdFdGdHgZeeƒZd-Zd.„Zd/„Zid0d16Z d2„Z d3„Z d4„Z d5„Z d6„Zd7„ZRS(IuRun the tests for this packageupackage=uPuwThe name of a specific package to test, e.g. 'io.fits' or 'utils'. If nothing is specified, all default tests are run.u test-path=utuHSpecify 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.uverbose-resultsuVu#Turn on verbose output from pytest.uplugins=upu&Plugins to enable when running pytest.u pastebin=ubu8Enable pytest pastebin output. Either 'all' or 'failed'.uargs=uau,Additional arguments to be passed to pytest.u remote-datauRu$Run tests that download remote data.upep8u8uPEnable PEP8 checking and disable regular tests. Requires the pytest-pep8 plugin.updbudu0Start the interactive Python debugger on errors.ucoverageucu8Create a coverage report. Requires the coverage package.u open-filesuouAFail if any tests leave files open. Requires the psutil package.u parallel=uju–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.u docs-path=uŒThe path to the documentation .rst files. If not provided, and the current directory contains a directory called "docs", that will be used.u skip-docsu(Don't test the documentation .rst files.urepeat=uPHow many times to repeat each test (can be used to check for sporadic failures).u temp-root=u°The root directory in which to create the temporary testing files. If unspecified the system default is used (e.g. /tmp) as explained in the documentation for tempfile.mkstemp.ucC@s”d|_d|_t|_d|_d|_d|_t|_t|_ t|_ t|_ t|_ d|_ d|_t|_d|_d|_dS(Ni(tNonetpackaget test_pathtFalsetverbose_resultstpluginstpastebintargst remote_datatpep8tpdbtcoveraget open_filestparallelt docs_patht skip_docstrepeatt temp_root(tself((sR/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/commands/_test_compat.pytinitialize_optionsNs                cC@sdS(N((R((sR/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/commands/_test_compat.pytfinalize_options`suverbose_resultsuverbosec @sĒd}d}ˆjr>ˆjƒ\}}||7}||7}n‡fd†‰t‡fd†ˆjƒƒ}dj‡fd†|Dƒƒ}tr™d}nd}d}|j|ˆd |d |d |ƒS( u9 Build a Python script to run the tests. uc@s"ˆjj||ƒ}tˆ|ƒS(N(t_test_runner_arg_attr_maptgettgetattr(targtattr(R(sR/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/commands/_test_compat.pytget_attrxsc@s tˆ|ƒS(N(thasattr(R(R(sR/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/commands/_test_compat.pyt|su, c3@s'|]}dj|ˆ|ƒƒVqdS(u {0}={1!r}N(tformat(t.0R(R(sR/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/commands/_test_compat.pys su/import builtins; builtins._ASTROPY_TEST_ = Trueu5import __builtin__; __builtin__._ASTROPY_TEST_ = Trueus{cmd_pre}{0}; import {1.package_name}, sys; result = {1.package_name}.test({test_args}); {cmd_post}sys.exit(result)tcmd_pretcmd_postt test_args(Rt_generate_coverage_commandstfiltert_get_test_runner_argstjointPY3R"(RR$R%tpretpostR&tset_flagtcmd((RRsR/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/commands/_test_compat.pytgenerate_testing_commandks"     cC@s4yddl}Wntk r/tdƒ‚nXdS(un This method checks that any required modules are installed before running the tests. iNuOThe 'test' command requires the astropy package to be installed and importable.(tastropyt ImportError(RR1((sR/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/commands/_test_compat.pyt_validate_required_depsŽs  cC@s±|jdkr<tjjdƒr<tjjdƒ|_q<n|jƒ|jƒz=|jƒ}t j t j dd|gd|j dtƒ}Wdtj|jƒXt|ƒ‚dS(u Run the tests! udocsu-Bu-ctcwdt close_fdsN(RRtostpathtexiststabspatht_build_temp_installR3R0t subprocesstcalltsyst executablet testing_pathRtshutiltrmtreettmp_dirt SystemExit(RR/tretcode((sR/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/commands/_test_compat.pytrunšs   cC@s|jddtƒ|jdƒ|jdƒ}tjj|jƒ}tj d|j dd|j ƒ}tjj |ƒ|_ tjj|j tjj|ƒƒ|_tj||jƒtjj|j tjj|jƒƒ}tj|j|ƒ||_tjd|j ƒdS(uĖ 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 ubuildtinplacetprefixu-test-tdiru setup.cfgN(treinitialize_commandtTruet run_commandtget_finalized_commandR6R7R9t build_libttempfiletmkdtempt package_nameRtrealpathRBR*tbasenameR?R@tcopytreeRtcopy(Rt build_cmdtnew_pathRBt new_docs_path((sR/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/commands/_test_compat.pyR:Čs  ' c C@sX|jdkrtdƒ‚nyddl}Wntk rMtdƒ‚nXtjj|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(uf This method creates the post and pre commands if coverage is to be generated iu*--coverage can not be used with --parallelNu;--coverage requires that the coverage package is installed.utestsu coveragercuru2u3u{ignore_python_version}u {packagename}uwbuutf-8uZimport coverage; cov = coverage.coverage(data_file="{0}", config_file="{1}"); cov.start();u .coverageugcov.stop(); from astropy.tests.helper import _save_coverage; _save_coverage(cov, result, "{0}", "{1}");u.(Rt ValueErrorRR2R6R7R*R?RPtopentreadR+treplaceRBtwritetencodeR"R9( RRt coveragerctfdtcoveragerc_contenttignore_python_versionttmp_coveragercttmpR$R%((sR/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/commands/_test_compat.pyR'äs4      cC@s£trddl}t|_nddl}t|_zSt|jƒ}t|dƒsltdj tƒƒ‚nt j |j ƒ}|j SWdtr˜|`n|`XdS(u0 A hack to determine what arguments are supported by the package's test() function. In the future there should be a more straightforward API to determine this (really it should be determined by the ``TestRunner`` class for whatever version of Astropy is in use). iNutestuVpackage {0} does not have a {0}.test() function as required by the Astropy test runner(R+tbuiltinsRJt_ASTROPY_TEST_t __builtin__t __import__RPR R2R"tinspectt getargspecttestR (RRdRftpkgtargspec((sR/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/commands/_test_compat.pyR)s       (upackage=uPuwThe name of a specific package to test, e.g. 'io.fits' or 'utils'. If nothing is specified, all default tests are run.(u test-path=utuHSpecify 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.(uverbose-resultsuVu#Turn on verbose output from pytest.(uplugins=upu&Plugins to enable when running pytest.(u pastebin=ubu8Enable pytest pastebin output. Either 'all' or 'failed'.(uargs=uau,Additional arguments to be passed to pytest.(u remote-datauRu$Run tests that download remote data.(upep8u8uPEnable PEP8 checking and disable regular tests. Requires the pytest-pep8 plugin.(updbudu0Start the interactive Python debugger on errors.(ucoverageucu8Create a coverage report. Requires the coverage package.(u open-filesuouAFail if any tests leave files open. Requires the psutil package.(u parallel=uju–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.N(u docs-path=NuŒThe path to the documentation .rst files. If not provided, and the current directory contains a directory called "docs", that will be used.(u skip-docsNu(Don't test the documentation .rst files.(urepeat=NuPHow many times to repeat each test (can be used to check for sporadic failures).(u temp-root=Nu°The root directory in which to create the temporary testing files. If unspecified the system default is used (e.g. /tmp) as explained in the documentation for tempfile.mkstemp.(t__name__t __module__t descriptionRt user_optionsRRPRRRR0R3RER:R'R)(((sR/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/commands/_test_compat.pyRsV      # .  3(t__doc__t __future__RRRhR6R@R;R=RNt setuptoolsRtcompatRt version_infoR+tobjectR(((sR/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/commands/_test_compat.pyts      sunpy-0.6.3/astropy_helpers/astropy_helpers/commands/test.py0000644000175000017500000000251412662554110025370 0ustar stuartstuart00000000000000""" Different implementations of the ``./setup.py test`` command depending on what's locally available. If Astropy v1.1.0.dev or later is available it should be possible to import AstropyTest from ``astropy.tests.command``. If ``astropy`` can be imported but not ``astropy.tests.command`` (i.e. an older version of Astropy), we can use the backwards-compat implementation of the command. If Astropy can't be imported at all then there is a skeleton implementation that allows users to at least discover the ``./setup.py test`` command and learn that they need Astropy to run it. """ # Previously these except statements caught only ImportErrors, but there are # some other obscure exceptional conditions that can occur when importing # astropy.tests (at least on older versions) that can cause these imports to # fail try: import astropy try: from astropy.tests.command import AstropyTest except Exception: from ._test_compat import AstropyTest except Exception: # No astropy at all--provide the dummy implementation from ._dummy import _DummyCommand class AstropyTest(_DummyCommand): command_name = 'test' description = 'Run the tests for this package' error_msg = ( "The 'test' command requires the astropy package to be " "installed and importable.") sunpy-0.6.3/astropy_helpers/astropy_helpers/commands/register.py0000644000175000017500000000454712622602515026244 0ustar stuartstuart00000000000000from setuptools.command.register import register as SetuptoolsRegister class AstropyRegister(SetuptoolsRegister): """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. """ user_options = SetuptoolsRegister.user_options + [ ('hidden', None, 'mark this release as hidden on PyPI by default') ] boolean_options = SetuptoolsRegister.boolean_options + ['hidden'] def initialize_options(self): SetuptoolsRegister.initialize_options(self) self.hidden = False def build_post_data(self, action): data = SetuptoolsRegister.build_post_data(self, action) if action == 'submit' and self.hidden: data['_pypi_hidden'] = '1' return data def _set_config(self): # The original register command is buggy--if you use .pypirc with a # server-login section *at all* the repository you specify with the -r # option will be overwritten with either the repository in .pypirc or # with the default, # If you do not have a .pypirc using the -r option will just crash. # Way to go distutils # If we don't set self.repository back to a default value _set_config # can crash if there was a user-supplied value for this option; don't # worry, we'll get the real value back afterwards self.repository = 'pypi' SetuptoolsRegister._set_config(self) options = self.distribution.get_option_dict('register') if 'repository' in options: source, value = options['repository'] # Really anything that came from setup.cfg or the command line # should override whatever was in .pypirc self.repository = value sunpy-0.6.3/astropy_helpers/astropy_helpers/commands/install.py0000644000175000017500000000074612622602515026063 0ustar stuartstuart00000000000000from setuptools.command.install import install as SetuptoolsInstall from ..utils import _get_platlib_dir class AstropyInstall(SetuptoolsInstall): user_options = SetuptoolsInstall.user_options[:] boolean_options = SetuptoolsInstall.boolean_options[:] def finalize_options(self): build_cmd = self.get_finalized_command('build') platlib_dir = _get_platlib_dir(build_cmd) self.build_lib = platlib_dir SetuptoolsInstall.finalize_options(self) sunpy-0.6.3/astropy_helpers/astropy_helpers/commands/build_py.pyc0000644000175000017500000000322512622602515026362 0ustar stuartstuart00000000000000ó MKVc@s:ddlmZddlmZdefd„ƒYZdS(i’’’’(tbuild_pyi(t_get_platlib_dirtAstropyBuildPycBs:eZejZejZd„Zed„Zd„ZRS(cCsG|jdƒ}t|ƒ}||_||_||_tj|ƒdS(Ntbuild(tget_finalized_commandRt build_purelibt build_libtSetuptoolsBuildPytfinalize_options(tselft build_cmdt platlib_dir((sN/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/commands/build_py.pyR s     cCs||jj}g}xP|D]H}x?|D]*}|t|jƒdj|ƒr&Pq&q&W|j|ƒqWtj|||ƒdS(Ni(t distributiont skip_2to3tlenRt startswithtappendRtrun_2to3(R tfilestdoctestsR tfiltered_filestfilenametpackage((sN/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/commands/build_py.pyRs    cCstj|ƒdS(N(Rtrun(R ((sN/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/commands/build_py.pyR%s( t__name__t __module__Rt user_optionstboolean_optionsRtFalseRR(((sN/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/commands/build_py.pyRs     N(tsetuptools.command.build_pyRRtutilsRR(((sN/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/commands/build_py.pytssunpy-0.6.3/astropy_helpers/astropy_helpers/commands/build_sphinx.pyc0000644000175000017500000001717312662555020027254 0ustar stuartstuart00000000000000ó HŲŹVc@s’ddlmZddlZddlZddlZddlZddlZddlZddlZddl Z ddl m Z ddl m Z ddlZddlmZddlmZejdd kZd efd „ƒYZd efd „ƒYZdS(i’’’’(tprint_functionN(tlog(tDistutilsOptionError(tBuildDoci(t minversioniitAstropyBuildSphinxcBsĄeZdZdZejZejdƒejdƒejdƒejdƒejZejdƒejdƒejdƒejd ƒej dej ƒZ d„Z d„Z d„ZRS(sÉ A version of the ``build_sphinx`` command that uses the version of Astropy that is built by the setup ``build`` command, rather than whatever is installed on the system. To build docs against the installed version, run ``make html`` in the ``astropy/docs`` directory. This also automatically creates the docs/_static directories--this is needed because GitHub won't create the _static dir because it has no tracked files. s2Build Sphinx documentation for Astropy environmentswarnings-returncodetwsĪParses the sphinx output and sets the return code to 1 if there are any warnings. Note that this will cause the sphinx log to only update when it completes, rather than continuously as is normally the case.s clean-docstls_Completely clean previous builds, including automodapi-generated files before building new onessno-intersphinxtns0Skip intersphinx, even if conf.py says to use itsopen-docs-in-browsertos\Open the docs in a browser (using the webbrowser module) if the build finishes successfully.sself\.([^\d\W][\w]+)cCs5tj|ƒt|_t|_t|_t|_dS(N(tSphinxBuildDoctinitialize_optionstFalset clean_docstno_intersphinxtopen_docs_in_browsertwarnings_returncode(tself((sR/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/commands/build_sphinx.pyR <s     cCsĄ|jrÆtjj|jdƒg}|jdkrC|jdƒn|j|jƒxY|D]N}tjj|ƒr“t j d|ƒt j |ƒqZt j d|dƒqZWnt j|ƒdS(Ntapis docs/_buildsCleaning directory sNot cleaning directory s' because not present or not a directory(R tostpathtjoint source_dirt build_dirtNonetappendtisdirRtinfotshutiltrmtreeR tfinalize_options(Rtdirstormtd((sR/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/commands/build_sphinx.pyRCs  cCsšddl}tr%ddlm}nddlm}d}|jdk rŚtjj |jƒ\}}|dkrŒtjj |ƒ\}}ntjj |dƒ}tjj |ƒrŹt d|dƒ‚n|j |ƒn|jdƒ}d|_|jdƒ|jdƒ}tjj|jƒ}tjd ƒ} tjj| jƒ} tjtjƒ\} } tjd ƒjd |d | d |jƒ} | tjdj | dƒƒ7} |jj | ƒ} xwtdt | ƒdƒD]]}| |}t!||ƒ}|j"dƒr!t#tjj|ƒƒ| |dkrW|j?rz|j@d!krDtjj|jAƒ}tjj |d"ƒ}d#||ƒ}|jB|ƒqTt(j;d$ƒqzn#t(j;d%t7|j>ƒƒ|j>}|dk r–t*jC|ƒndS(&Ni’’’’(t pathname2urltt_statics-Attempted to build_sphinx in a location wheres is a file. Must be a directory.tbuilditastropy_helperssŗ from sphinx.setup_command import * os.chdir({srcdir!r}) sys.path.insert(0, {build_cmd_path!r}) sys.path.insert(0, {ah_path!r}) tbuild_cmd_pathtah_pathtsrcdiriit_dirs1.3s%from __future__ import print_functionsconfoverrides = {}s*confoverrides = {'intersphinx_mapping':{}}s<Starting subprocess of {0} with python code: {1} [CODE END])s-ctstdintstdouttstderrs sutf-8sbuild succeeded.tTRAVISttruesrThe build_sphinx travis build FAILED because sphinx issued documentation warnings (scroll up to see the warnings).sYbuild_sphinx returning a non-zero exit code because sphinx issued documentation warnings.thtmls index.htmlsfile://sMopen-docs-in-browser option was given, but the builder is not html! Ignoring.s8Sphinx Documentation subprocess failed with return code (Dt webbrowsertPY3turllib.requestR!turllibRRRRtsplitRtisfileRtmkpathtreinitialize_commandtinplacet run_commandtget_finalized_commandtabspatht build_libtpkgutilt get_importertinspecttgetsourcelinesR trunttextwraptdedenttformatRt_self_iden_rextrangetlentgetattrtendswithtreprRtsphinxRtreplaceRtdebugtsyst executableRt subprocesstPopentPIPEtSTDOUTR+titertreadlinetstriptprinttdecodetstrtwaittenvirontgettwarnt communicatetencodet returncodeRtbuildertbuilder_target_dirtopentexit(RR0R!tretcodetbasedirtsubdirt staticdirt build_cmdR&t ah_importerR'trunlinest runlinenot subproccodetitidentvaltproctlinetmsgtabsdirt index_pathtfileurl((sR/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/commands/build_sphinx.pyRAVs”                         (swarnings-returncodeRsĪParses the sphinx output and sets the return code to 1 if there are any warnings. Note that this will cause the sphinx log to only update when it completes, rather than continuously as is normally the case.(s clean-docsRs_Completely clean previous builds, including automodapi-generated files before building new ones(sno-intersphinxRs0Skip intersphinx, even if conf.py says to use it(sopen-docs-in-browserR s\Open the docs in a browser (using the webbrowser module) if the build finishes successfully.(t__name__t __module__t__doc__t descriptionR t user_optionsRtboolean_optionstretcompiletUNICODERER RRA(((sR/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/commands/build_sphinx.pyRs(         tAstropyBuildDocscBseZdZRS(s!alias to the build_sphinx command(RwRxRz(((sR/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/commands/build_sphinx.pyR€čs(t __future__RR?RR=R}RRPRNRBt distutilsRt distutils.cmdRRKtsphinx.setup_commandRR tutilsRt version_infoR1RR€(((sR/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/commands/build_sphinx.pyts          Šsunpy-0.6.3/astropy_helpers/astropy_helpers/commands/setup_package.pyc0000644000175000017500000000062212622602515027364 0ustar stuartstuart00000000000000ó MKVc@sddlmZd„ZdS(i’’’’(tjoincCsitddƒgd6S(Ntsrcs compiler.csastropy_helpers.commands(R(((s)astropy_helpers/commands/setup_package.pytget_package_datasN(tos.pathRR(((s)astropy_helpers/commands/setup_package.pytssunpy-0.6.3/astropy_helpers/astropy_helpers/commands/build_ext.py0000644000175000017500000004566512662554110026406 0ustar stuartstuart00000000000000import errno import os import re import shlex import shutil import subprocess import sys import textwrap from distutils import log, ccompiler, sysconfig from distutils.cmd import Command from distutils.core import Extension from distutils.ccompiler import get_default_compiler from setuptools.command.build_ext import build_ext as SetuptoolsBuildExt from ..utils import get_numpy_include_path, invalidate_caches, classproperty from ..version_helpers import get_pkg_version_module def should_build_with_cython(package, release=None): """Returns 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`. """ try: version_module = __import__(package + '.cython_version', fromlist=['release', 'cython_version']) except ImportError: version_module = None if release is None and version_module is not None: try: release = version_module.release except AttributeError: pass try: cython_version = version_module.cython_version except AttributeError: cython_version = 'unknown' # Only build with Cython if, of course, Cython is installed, we're in a # development version (i.e. not release) or the Cython-generated source # files haven't been created yet (cython_version == 'unknown'). The latter # case can happen even when release is True if checking out a release tag # from the repository have_cython = False try: import Cython have_cython = True except ImportError: pass if have_cython and (not release or cython_version == 'unknown'): return cython_version else: return False _compiler_versions = {} def get_compiler_version(compiler): if compiler in _compiler_versions: return _compiler_versions[compiler] # Different flags to try to get the compiler version # TODO: It might be worth making this configurable to support # arbitrary odd compilers; though all bets may be off in such # cases anyway flags = ['--version', '--Version', '-version', '-Version', '-v', '-V'] def try_get_version(flag): process = subprocess.Popen( shlex.split(compiler, posix=('win' not in sys.platform)) + [flag], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = process.communicate() if process.returncode != 0: return 'unknown' output = stdout.strip().decode('latin-1') # Safest bet if not output: # Some compilers return their version info on stderr output = stderr.strip().decode('latin-1') if not output: output = 'unknown' return output for flag in flags: version = try_get_version(flag) if version != 'unknown': break # Cache results to speed up future calls _compiler_versions[compiler] = version return version # TODO: I think this can be reworked without having to create the class # programmatically. def generate_build_ext_command(packagename, release): """ Creates a custom 'build_ext' command that allows for manipulating some of the C extension options at build time. We use a function to build the class since the base class for build_ext may be different depending on certain build-time parameters (for example, we may use Cython's build_ext instead of the default version in distutils). Uses the default distutils.command.build_ext by default. """ class build_ext(SetuptoolsBuildExt, object): package_name = packagename is_release = release _user_options = SetuptoolsBuildExt.user_options[:] _boolean_options = SetuptoolsBuildExt.boolean_options[:] _help_options = SetuptoolsBuildExt.help_options[:] force_rebuild = False _broken_compiler_mapping = [ ('i686-apple-darwin[0-9]*-llvm-gcc-4.2', 'clang') ] # Warning: Spaghetti code ahead. # During setup.py, the setup_helpers module needs the ability to add # items to a command's user_options list. At this stage we don't know # whether or not we can build with Cython, and so don't know for sure # what base class will be used for build_ext; nevertheless we want to # be able to provide a list to add options into. # # Later, once setup() has been called we should have all build # dependencies included via setup_requires available. distutils needs # to be able to access the user_options as a *class* attribute before # the class has been initialized, but we do need to be able to # enumerate the options for the correct base class at that point @classproperty def user_options(cls): from distutils import core if core._setup_distribution is None: # We haven't gotten into setup() yet, and the Distribution has # not yet been initialized return cls._user_options return cls._final_class.user_options @classproperty def boolean_options(cls): # Similar to user_options above from distutils import core if core._setup_distribution is None: # We haven't gotten into setup() yet, and the Distribution has # not yet been initialized return cls._boolean_options return cls._final_class.boolean_options @classproperty def help_options(cls): # Similar to user_options above from distutils import core if core._setup_distribution is None: # We haven't gotten into setup() yet, and the Distribution has # not yet been initialized return cls._help_options return cls._final_class.help_options @classproperty(lazy=True) def _final_class(cls): """ Late determination of what the build_ext base class should be, depending on whether or not Cython is available. """ uses_cython = should_build_with_cython(cls.package_name, cls.is_release) if uses_cython: # We need to decide late on whether or not to use Cython's # build_ext (since Cython may not be available earlier in the # setup.py if it was brought in via setup_requires) from Cython.Distutils import build_ext as base_cls else: base_cls = SetuptoolsBuildExt # Create and return an instance of a new class based on this class # using one of the above possible base classes def merge_options(attr): base = getattr(base_cls, attr) ours = getattr(cls, '_' + attr) all_base = set(opt[0] for opt in base) return base + [opt for opt in ours if opt[0] not in all_base] boolean_options = (base_cls.boolean_options + [opt for opt in cls._boolean_options if opt not in base_cls.boolean_options]) members = dict(cls.__dict__) members.update({ 'user_options': merge_options('user_options'), 'help_options': merge_options('help_options'), 'boolean_options': boolean_options, 'uses_cython': uses_cython, }) # Update the base class for the original build_ext command build_ext.__bases__ = (base_cls, object) # Create a new class for the existing class, but now with the # appropriate base class depending on whether or not to use Cython. # Ensure that object is one of the bases to make a new-style class. return type(cls.__name__, (build_ext,), members) def __new__(cls, *args, **kwargs): # By the time the command is actually instantialized, the # Distribution instance for the build has been instantiated, which # means setup_requires has been processed--now we can determine # what base class we can use for the actual build, and return an # instance of a build_ext command that uses that base class (right # now the options being Cython.Distutils.build_ext, or the stock # setuptools build_ext) new_cls = super(build_ext, cls._final_class).__new__( cls._final_class) # Since the new cls is not a subclass of the original cls, we must # manually call its __init__ new_cls.__init__(*args, **kwargs) return new_cls def finalize_options(self): # Add a copy of the _compiler.so module as well, but only if there # are in fact C modules to compile (otherwise there's no reason to # include a record of the compiler used) # Note, self.extensions may not be set yet, but # self.distribution.ext_modules is where any extension modules # passed to setup() can be found self._adjust_compiler() extensions = self.distribution.ext_modules if extensions: src_path = os.path.relpath( os.path.join(os.path.dirname(__file__), 'src')) shutil.copy2(os.path.join(src_path, 'compiler.c'), os.path.join(self.package_name, '_compiler.c')) ext = Extension(self.package_name + '._compiler', [os.path.join(self.package_name, '_compiler.c')]) extensions.insert(0, ext) super(build_ext, self).finalize_options() # Generate if self.uses_cython: try: from Cython import __version__ as cython_version except ImportError: # This shouldn't happen if we made it this far cython_version = None if (cython_version is not None and cython_version != self.uses_cython): self.force_rebuild = True # Update the used cython version self.uses_cython = cython_version # Regardless of the value of the '--force' option, force a rebuild # if the debug flag changed from the last build if self.force_rebuild: self.force = True def run(self): # For extensions that require 'numpy' in their include dirs, # replace 'numpy' with the actual paths np_include = get_numpy_include_path() for extension in self.extensions: if 'numpy' in extension.include_dirs: idx = extension.include_dirs.index('numpy') extension.include_dirs.insert(idx, np_include) extension.include_dirs.remove('numpy') self._check_cython_sources(extension) super(build_ext, self).run() # Update cython_version.py if building with Cython try: cython_version = get_pkg_version_module( packagename, fromlist=['cython_version'])[0] except (AttributeError, ImportError): cython_version = 'unknown' if self.uses_cython and self.uses_cython != cython_version: package_dir = os.path.relpath(packagename) cython_py = os.path.join(package_dir, 'cython_version.py') with open(cython_py, 'w') as f: f.write('# Generated file; do not modify\n') f.write('cython_version = {0!r}\n'.format(self.uses_cython)) if os.path.isdir(self.build_lib): # The build/lib directory may not exist if the build_py # command was not previously run, which may sometimes be # the case self.copy_file(cython_py, os.path.join(self.build_lib, cython_py), preserve_mode=False) invalidate_caches() def _adjust_compiler(self): """ This function detects broken compilers and switches to another. If the environment variable CC is explicitly set, or a compiler is specified on the commandline, no override is performed -- the purpose here is to only override a default compiler. The specific compilers with problems are: * The default compiler in XCode-4.2, llvm-gcc-4.2, segfaults when compiling wcslib. The set of broken compilers can be updated by changing the compiler_mapping variable. It is a list of 2-tuples where the first in the pair is a regular expression matching the version of the broken compiler, and the second is the compiler to change to. """ if 'CC' in os.environ: # Check that CC is not set to llvm-gcc-4.2 c_compiler = os.environ['CC'] try: version = get_compiler_version(c_compiler) except OSError: msg = textwrap.dedent( """ The C compiler set by the CC environment variable: {compiler:s} cannot be found or executed. """.format(compiler=c_compiler)) log.warn(msg) sys.exit(1) for broken, fixed in self._broken_compiler_mapping: if re.match(broken, version): msg = textwrap.dedent( """Compiler specified by CC environment variable ({compiler:s}:{version:s}) will fail to compile {pkg:s}. Please set CC={fixed:s} and try again. You can do this, for example, by running: CC={fixed:s} python setup.py where is the command you ran. """.format(compiler=c_compiler, version=version, pkg=self.package_name, fixed=fixed)) log.warn(msg) sys.exit(1) # If C compiler is set via CC, and isn't broken, we are good to go. We # should definitely not try accessing the compiler specified by # ``sysconfig.get_config_var('CC')`` lower down, because this may fail # if the compiler used to compile Python is missing (and maybe this is # why the user is setting CC). For example, the official Python 2.7.3 # MacOS X binary was compiled with gcc-4.2, which is no longer available # in XCode 4. return if self.compiler is not None: # At this point, self.compiler will be set only if a compiler # was specified in the command-line or via setup.cfg, in which # case we don't do anything return compiler_type = ccompiler.get_default_compiler() if compiler_type == 'unix': # We have to get the compiler this way, as this is the one that is # used if os.environ['CC'] is not set. It is actually read in from # the Python Makefile. Note that this is not necessarily the same # compiler as returned by ccompiler.new_compiler() c_compiler = sysconfig.get_config_var('CC') try: version = get_compiler_version(c_compiler) except OSError: msg = textwrap.dedent( """ 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 """.format(compiler=c_compiler)) log.warn(msg) sys.exit(1) for broken, fixed in self._broken_compiler_mapping: if re.match(broken, version): os.environ['CC'] = fixed break def _check_cython_sources(self, extension): """ Where relevant, make sure that the .c files associated with .pyx modules are present (if building without Cython installed). """ # Determine the compiler we'll be using if self.compiler is None: compiler = get_default_compiler() else: compiler = self.compiler # Replace .pyx with C-equivalents, unless c files are missing for jdx, src in enumerate(extension.sources): base, ext = os.path.splitext(src) pyxfn = base + '.pyx' cfn = base + '.c' cppfn = base + '.cpp' if not os.path.isfile(pyxfn): continue if self.uses_cython: extension.sources[jdx] = pyxfn else: if os.path.isfile(cfn): extension.sources[jdx] = cfn elif os.path.isfile(cppfn): extension.sources[jdx] = cppfn else: msg = ( 'Could not find C/C++ file {0}.(c/cpp) for Cython ' 'file {1} when building extension {2}. Cython ' 'must be installed to build from a git ' 'checkout.'.format(base, pyxfn, extension.name)) raise IOError(errno.ENOENT, msg, cfn) # Current versions of Cython use deprecated Numpy API features # the use of which produces a few warnings when compiling. # These additional flags should squelch those warnings. # TODO: Feel free to remove this if/when a Cython update # removes use of the deprecated Numpy API if compiler == 'unix': extension.extra_compile_args.extend([ '-Wp,-w', '-Wno-unused-function']) return build_ext sunpy-0.6.3/astropy_helpers/astropy_helpers/commands/build_py.py0000644000175000017500000000265612622602515026226 0ustar stuartstuart00000000000000from setuptools.command.build_py import build_py as SetuptoolsBuildPy from ..utils import _get_platlib_dir class AstropyBuildPy(SetuptoolsBuildPy): user_options = SetuptoolsBuildPy.user_options[:] boolean_options = SetuptoolsBuildPy.boolean_options[:] def finalize_options(self): # Update build_lib settings from the build command to always put # build files in platform-specific subdirectories of build/, even # for projects with only pure-Python source (this is desirable # specifically for support of multiple Python version). build_cmd = self.get_finalized_command('build') platlib_dir = _get_platlib_dir(build_cmd) build_cmd.build_purelib = platlib_dir build_cmd.build_lib = platlib_dir self.build_lib = platlib_dir SetuptoolsBuildPy.finalize_options(self) def run_2to3(self, files, doctests=False): # Filter the files to exclude things that shouldn't be 2to3'd skip_2to3 = self.distribution.skip_2to3 filtered_files = [] for filename in files: for package in skip_2to3: if filename[len(self.build_lib) + 1:].startswith(package): break else: filtered_files.append(filename) SetuptoolsBuildPy.run_2to3(self, filtered_files, doctests) def run(self): # first run the normal build_py SetuptoolsBuildPy.run(self) sunpy-0.6.3/astropy_helpers/astropy_helpers/commands/register.pyc0000644000175000017500000000457312622602515026406 0ustar stuartstuart00000000000000ó MKVc@s*ddlmZdefd„ƒYZdS(i’’’’(tregistertAstropyRegistercBsIeZdZejdgZejdgZd„Zd„Zd„Z RS(sé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. thiddens.mark this release as hidden on PyPI by defaultcCstj|ƒt|_dS(N(tSetuptoolsRegistertinitialize_optionstFalseR(tself((sN/home/stuart/GitHub/sunpy/astropy_helpers/astropy_helpers/commands/register.pyRs cCs8tj||ƒ}|dkr4|jr4d|d