Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code reformat #454

Merged
merged 3 commits into from Jun 12, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.rst
@@ -1,3 +1,9 @@
Release 1.12.0, 12 Giu 2018

* Implementation of pixel weights for map2alm that makes transform exact <https://github.com/healpy/healpy/pull/442>
* Change default output FITS column names to agree with other HEALPix packages <https://github.com/healpy/healpy/pull/446>
* Reformatted the Python code with black, this made a huge changeset <https://github.com/healpy/healpy/pull/454>

Release 1.11.0, 8 Aug 2017

* Remove NSIDE restriction to be a power of 2 for RING <https://github.com/healpy/healpy/pull/377>
Expand Down
152 changes: 87 additions & 65 deletions ez_setup.py
Expand Up @@ -49,10 +49,10 @@ def _install(archive_filename, install_args=()):
"""Install Setuptools."""
with archive_context(archive_filename):
# 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.')
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

Expand All @@ -61,12 +61,12 @@ def _build_egg(egg, archive_filename, to_dir):
"""Build Setuptools egg."""
with archive_context(archive_filename):
# building an egg
log.warn('Building a Setuptools egg in %s', to_dir)
_python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir)
log.warn("Building a Setuptools egg in %s", to_dir)
_python_cmd("setup.py", "-q", "bdist_egg", "--dist-dir", to_dir)
# returning the result
log.warn(egg)
if not os.path.exists(egg):
raise IOError('Could not build the egg.')
raise IOError("Could not build the egg.")


class ContextualZipFile(zipfile.ZipFile):
Expand All @@ -81,7 +81,7 @@ def __exit__(self, type, value, traceback):

def __new__(cls, *args, **kwargs):
"""Construct a ZipFile or ContextualZipFile as appropriate."""
if hasattr(zipfile.ZipFile, '__exit__'):
if hasattr(zipfile.ZipFile, "__exit__"):
return zipfile.ZipFile(*args, **kwargs)
return super(ContextualZipFile, cls).__new__(cls)

Expand All @@ -94,7 +94,7 @@ def archive_context(filename):
The unzipped target is cleaned up after.
"""
tmpdir = tempfile.mkdtemp()
log.warn('Extracting in %s', tmpdir)
log.warn("Extracting in %s", tmpdir)
old_wd = os.getcwd()
try:
os.chdir(tmpdir)
Expand All @@ -104,7 +104,7 @@ def archive_context(filename):
# going in the directory
subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
os.chdir(subdir)
log.warn('Now working in %s', subdir)
log.warn("Now working in %s", subdir)
yield

finally:
Expand All @@ -114,26 +114,32 @@ def archive_context(filename):

def _do_download(version, download_base, to_dir, download_delay):
"""Download Setuptools."""
egg = os.path.join(to_dir, 'setuptools-%s-py%d.%d.egg'
% (version, sys.version_info[0], sys.version_info[1]))
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):
archive = download_setuptools(version, download_base,
to_dir, download_delay)
archive = download_setuptools(version, download_base, to_dir, download_delay)
_build_egg(egg, archive, 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']
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=DEFAULT_SAVE_DIR, download_delay=15):
version=DEFAULT_VERSION,
download_base=DEFAULT_URL,
to_dir=DEFAULT_SAVE_DIR,
download_delay=15,
):
"""
Ensure that a setuptools version is installed.

Expand All @@ -144,11 +150,12 @@ def use_setuptools(

# prior to importing, capture the module state for
# representative modules.
rep_modules = 'pkg_resources', 'setuptools'
rep_modules = "pkg_resources", "setuptools"
imported = set(sys.modules).intersection(rep_modules)

try:
import pkg_resources

pkg_resources.require("setuptools>=" + version)
# a suitable version is already installed
return
Expand All @@ -175,24 +182,23 @@ def _conflict_bail(VC_err, version):
Setuptools was imported prior to invocation, so it is
unsafe to unload it. Bail out.
"""
conflict_tmpl = textwrap.dedent("""
conflict_tmpl = textwrap.dedent(
"""
The required version of setuptools (>={version}) is not available,
and can't be installed while this script is running. Please
install a more recent version first, using
'easy_install -U setuptools'.

(Currently using {VC_err.args[0]!r})
""")
"""
)
msg = conflict_tmpl.format(**locals())
sys.stderr.write(msg)
sys.exit(2)


def _unload_pkg_resources():
del_modules = [
name for name in sys.modules
if name.startswith('pkg_resources')
]
del_modules = [name for name in sys.modules if name.startswith("pkg_resources")]
for mod_name in del_modules:
del sys.modules[mod_name]

Expand Down Expand Up @@ -222,60 +228,61 @@ def download_file_powershell(url, target):
ps_cmd = (
"[System.Net.WebRequest]::DefaultWebProxy.Credentials = "
"[System.Net.CredentialCache]::DefaultCredentials; "
"(new-object System.Net.WebClient).DownloadFile(%(url)r, %(target)r)"
% vars()
"(new-object System.Net.WebClient).DownloadFile(%(url)r, %(target)r)" % vars()
)
cmd = [
'powershell',
'-Command',
ps_cmd,
]
cmd = ["powershell", "-Command", ps_cmd]
_clean_check(cmd, target)


def has_powershell():
"""Determine if Powershell is available."""
if platform.system() != 'Windows':
if platform.system() != "Windows":
return False
cmd = ['powershell', '-Command', 'echo test']
with open(os.path.devnull, 'wb') as devnull:
cmd = ["powershell", "-Command", "echo test"]
with open(os.path.devnull, "wb") as devnull:
try:
subprocess.check_call(cmd, stdout=devnull, stderr=devnull)
except Exception:
return False
return True


download_file_powershell.viable = has_powershell


def download_file_curl(url, target):
cmd = ['curl', url, '--silent', '--output', target]
cmd = ["curl", url, "--silent", "--output", target]
_clean_check(cmd, target)


def has_curl():
cmd = ['curl', '--version']
with open(os.path.devnull, 'wb') as devnull:
cmd = ["curl", "--version"]
with open(os.path.devnull, "wb") as devnull:
try:
subprocess.check_call(cmd, stdout=devnull, stderr=devnull)
except Exception:
return False
return True


download_file_curl.viable = has_curl


def download_file_wget(url, target):
cmd = ['wget', url, '--quiet', '--output-document', target]
cmd = ["wget", url, "--quiet", "--output-document", target]
_clean_check(cmd, target)


def has_wget():
cmd = ['wget', '--version']
with open(os.path.devnull, 'wb') as devnull:
cmd = ["wget", "--version"]
with open(os.path.devnull, "wb") as devnull:
try:
subprocess.check_call(cmd, stdout=devnull, stderr=devnull)
except Exception:
return False
return True


download_file_wget.viable = has_wget


Expand All @@ -291,6 +298,8 @@ def download_file_insecure(url, target):
# Write all the data in one block to avoid creating a partial file.
with open(target, "wb") as dst:
dst.write(data)


download_file_insecure.viable = lambda: True


Expand All @@ -306,9 +315,12 @@ def get_best_downloader():


def download_setuptools(
version=DEFAULT_VERSION, download_base=DEFAULT_URL,
to_dir=DEFAULT_SAVE_DIR, delay=15,
downloader_factory=get_best_downloader):
version=DEFAULT_VERSION,
download_base=DEFAULT_URL,
to_dir=DEFAULT_SAVE_DIR,
delay=15,
downloader_factory=get_best_downloader,
):
"""
Download setuptools from a specified location and return its filename.

Expand Down Expand Up @@ -339,46 +351,55 @@ def _build_install_args(options):

Returns list of command line arguments.
"""
return ['--user'] if options.user_install else []
return ["--user"] if options.user_install else []


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)')
"--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",
"--download-base",
dest="download_base",
metavar="URL",
default=DEFAULT_URL,
help='alternative URL from where to download the setuptools package')
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'
"--insecure",
dest="downloader_factory",
action="store_const",
const=lambda: download_file_insecure,
default=get_best_downloader,
help="Use internal, non-validating downloader",
)
parser.add_option(
'--version', help="Specify which version to download",
default=DEFAULT_VERSION,
"--version", help="Specify which version to download", default=DEFAULT_VERSION
)
parser.add_option(
'--to-dir',
help="Directory to save (and re-use) package",
default=DEFAULT_SAVE_DIR,
"--to-dir",
help="Directory to save (and re-use) package",
default=DEFAULT_SAVE_DIR,
)
options, args = parser.parse_args()
# positional arguments are ignored
return options


def _download_args(options):
"""Return args for download_setuptools function from cmdline args."""
return dict(
version=options.version,
download_base=options.download_base,
downloader_factory=options.downloader_factory,
to_dir=options.to_dir,
)
"""Return args for download_setuptools function from cmdline args."""
return dict(
version=options.version,
download_base=options.download_base,
downloader_factory=options.downloader_factory,
to_dir=options.to_dir,
)


def main():
Expand All @@ -387,5 +408,6 @@ def main():
archive = download_setuptools(**_download_args(options))
return _install(archive, _build_install_args(options))

if __name__ == '__main__':

if __name__ == "__main__":
sys.exit(main())