Skip to content

Commit

Permalink
Merge pull request #53 from plone/jensens-py-codestyle
Browse files Browse the repository at this point in the history
Codestyle, pyupgrade, no six
  • Loading branch information
jensens authored Aug 25, 2022
2 parents fffe83a + 9ed5927 commit 1725dd8
Show file tree
Hide file tree
Showing 22 changed files with 494 additions and 425 deletions.
154 changes: 89 additions & 65 deletions bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,20 @@
use the -c option to specify an alternate configuration file.
"""

from optparse import OptionParser

import os
import shutil
import sys
import tempfile

from optparse import OptionParser

__version__ = '2015-07-01'
__version__ = "2015-07-01"
# See zc.buildout's changelog if this version is up to date.

tmpeggs = tempfile.mkdtemp(prefix='bootstrap-')
tmpeggs = tempfile.mkdtemp(prefix="bootstrap-")

usage = '''\
usage = """\
[DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options]
Bootstraps a buildout-based project.
Expand All @@ -40,36 +41,50 @@
Note that by using --find-links to point to local resources, you can keep
this script from going over the network.
'''
"""

parser = OptionParser(usage=usage)
parser.add_option("--version",
action="store_true", default=False,
help=("Return bootstrap.py version."))
parser.add_option("-t", "--accept-buildout-test-releases",
dest='accept_buildout_test_releases',
action="store_true", default=False,
help=("Normally, if you do not specify a --buildout-version, "
"the bootstrap script and buildout gets the newest "
"*final* versions of zc.buildout and its recipes and "
"extensions for you. If you use this flag, "
"bootstrap and buildout will get the newest releases "
"even if they are alphas or betas."))
parser.add_option("-c", "--config-file",
help=("Specify the path to the buildout configuration "
"file to be used."))
parser.add_option("-f", "--find-links",
help=("Specify a URL to search for buildout releases"))
parser.add_option("--allow-site-packages",
action="store_true", default=False,
help=("Let bootstrap.py use existing site packages"))
parser.add_option("--buildout-version",
help="Use a specific zc.buildout version")
parser.add_option("--setuptools-version",
help="Use a specific setuptools version")
parser.add_option("--setuptools-to-dir",
help=("Allow for re-use of existing directory of "
"setuptools versions"))
parser.add_option(
"--version",
action="store_true",
default=False,
help=("Return bootstrap.py version."),
)
parser.add_option(
"-t",
"--accept-buildout-test-releases",
dest="accept_buildout_test_releases",
action="store_true",
default=False,
help=(
"Normally, if you do not specify a --buildout-version, "
"the bootstrap script and buildout gets the newest "
"*final* versions of zc.buildout and its recipes and "
"extensions for you. If you use this flag, "
"bootstrap and buildout will get the newest releases "
"even if they are alphas or betas."
),
)
parser.add_option(
"-c",
"--config-file",
help=("Specify the path to the buildout configuration " "file to be used."),
)
parser.add_option(
"-f", "--find-links", help=("Specify a URL to search for buildout releases")
)
parser.add_option(
"--allow-site-packages",
action="store_true",
default=False,
help=("Let bootstrap.py use existing site packages"),
)
parser.add_option("--buildout-version", help="Use a specific zc.buildout version")
parser.add_option("--setuptools-version", help="Use a specific setuptools version")
parser.add_option(
"--setuptools-to-dir",
help=("Allow for re-use of existing directory of " "setuptools versions"),
)

options, args = parser.parse_args()
if options.version:
Expand All @@ -86,37 +101,38 @@
from urllib2 import urlopen

ez = {}
if os.path.exists('ez_setup.py'):
exec(open('ez_setup.py').read(), ez)
if os.path.exists("ez_setup.py"):
exec(open("ez_setup.py").read(), ez)
else:
exec(urlopen('https://bootstrap.pypa.io/ez_setup.py').read(), ez)
exec(urlopen("https://bootstrap.pypa.io/ez_setup.py").read(), ez)

if not options.allow_site_packages:
# ez_setup imports site, which adds site packages
# this will remove them from the path to ensure that incompatible versions
# of setuptools are not in the path
import site

# inside a virtualenv, there is no 'getsitepackages'.
# We can't remove these reliably
if hasattr(site, 'getsitepackages'):
if hasattr(site, "getsitepackages"):
for sitepackage_path in site.getsitepackages():
# Strip all site-packages directories from sys.path that
# are not sys.prefix; this is because on Windows
# sys.prefix is a site-package directory.
if sitepackage_path != sys.prefix:
sys.path[:] = [x for x in sys.path
if sitepackage_path not in x]
sys.path[:] = [x for x in sys.path if sitepackage_path not in x]

setup_args = dict(to_dir=tmpeggs, download_delay=0)

if options.setuptools_version is not None:
setup_args['version'] = options.setuptools_version
setup_args["version"] = options.setuptools_version
if options.setuptools_to_dir is not None:
setup_args['to_dir'] = options.setuptools_to_dir
setup_args["to_dir"] = options.setuptools_to_dir

ez['use_setuptools'](**setup_args)
import setuptools
ez["use_setuptools"](**setup_args)
import pkg_resources
import setuptools


# This does not (always?) update the default working set. We will
# do it.
Expand All @@ -129,43 +145,49 @@

ws = pkg_resources.working_set

setuptools_path = ws.find(
pkg_resources.Requirement.parse('setuptools')).location
setuptools_path = ws.find(pkg_resources.Requirement.parse("setuptools")).location

# Fix sys.path here as easy_install.pth added before PYTHONPATH
cmd = [sys.executable, '-c',
'import sys; sys.path[0:0] = [%r]; ' % setuptools_path +
'from setuptools.command.easy_install import main; main()',
'-mZqNxd', tmpeggs]
cmd = [
sys.executable,
"-c",
"import sys; sys.path[0:0] = [%r]; " % setuptools_path
+ "from setuptools.command.easy_install import main; main()",
"-mZqNxd",
tmpeggs,
]

find_links = os.environ.get(
'bootstrap-testing-find-links',
options.find_links or
('http://downloads.buildout.org/'
if options.accept_buildout_test_releases else None)
)
"bootstrap-testing-find-links",
options.find_links
or (
"http://downloads.buildout.org/"
if options.accept_buildout_test_releases
else None
),
)
if find_links:
cmd.extend(['-f', find_links])
cmd.extend(["-f", find_links])

requirement = 'zc.buildout'
requirement = "zc.buildout"
version = options.buildout_version
if version is None and not options.accept_buildout_test_releases:
# Figure out the most recent final version of zc.buildout.
import setuptools.package_index
_final_parts = '*final-', '*final'

_final_parts = "*final-", "*final"

def _final_version(parsed_version):
try:
return not parsed_version.is_prerelease
except AttributeError:
# Older setuptools
for part in parsed_version:
if (part[:1] == '*') and (part not in _final_parts):
if (part[:1] == "*") and (part not in _final_parts):
return False
return True

index = setuptools.package_index.PackageIndex(
search_path=[setuptools_path])
index = setuptools.package_index.PackageIndex(search_path=[setuptools_path])
if find_links:
index.add_find_links((find_links,))
req = pkg_resources.Requirement.parse(requirement)
Expand All @@ -184,13 +206,14 @@ def _final_version(parsed_version):
best.sort()
version = best[-1].version
if version:
requirement = '=='.join((requirement, version))
requirement = "==".join((requirement, version))
cmd.append(requirement)

import subprocess


if subprocess.call(cmd) != 0:
raise Exception(
"Failed to execute command:\n%s" % repr(cmd)[1:-1])
raise Exception("Failed to execute command:\n%s" % repr(cmd)[1:-1])

######################################################################
# Import and run buildout
Expand All @@ -199,12 +222,13 @@ def _final_version(parsed_version):
ws.require(requirement)
import zc.buildout.buildout

if not [a for a in args if '=' not in a]:
args.append('bootstrap')

if not [a for a in args if "=" not in a]:
args.append("bootstrap")

# if -c was provided, we push it back into args for buildout' main function
if options.config_file is not None:
args[0:0] = ['-c', options.config_file]
args[0:0] = ["-c", options.config_file]

zc.buildout.buildout.main(args)
shutil.rmtree(tmpeggs)
2 changes: 2 additions & 0 deletions news/53.bgfix
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
isort, black, pyupgrade, manual six removal.
[jensens]
3 changes: 1 addition & 2 deletions plone/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
# -*- coding: utf-8 -*-
__import__('pkg_resources').declare_namespace(__name__)
__import__("pkg_resources").declare_namespace(__name__)
1 change: 0 additions & 1 deletion plone/outputfilters/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
def apply_filters(filters, data):
by_order = lambda x: x.order
filters = sorted(filters, key=by_order)
Expand Down
4 changes: 1 addition & 3 deletions plone/outputfilters/browser/captioned_image.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
# -*- coding: utf-8 -*-
from Products.Five import BrowserView
from zope.cachedescriptors.property import Lazy as lazy_property


class CaptionedImageView(BrowserView):
"""Captioned image template.
"""
"""Captioned image template."""

@lazy_property
def template(self):
Expand Down
29 changes: 14 additions & 15 deletions plone/outputfilters/browser/resolveuid.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
from Acquisition import aq_base
from Products.CMFCore.utils import getToolByName
from zExceptions import NotFound
Expand All @@ -16,9 +15,8 @@

@deprecate("Please use plone.app.uuid.utils.uuidToURL instead.")
def uuidToURL(uuid):
"""Resolves a UUID to a URL via the UID index of portal_catalog.
"""
catalog = getToolByName(getSite(), 'portal_catalog')
"""Resolves a UUID to a URL via the UID index of portal_catalog."""
catalog = getToolByName(getSite(), "portal_catalog")
res = catalog.unrestrictedSearchResults(UID=uuid)
if res:
return res[0].getURL()
Expand All @@ -29,9 +27,8 @@ def uuidToURL(uuid):
"But be aware that this does an extra security check."
)
def uuidToObject(uuid):
"""Resolves a UUID to an object via the UID index of portal_catalog.
"""
catalog = getToolByName(getSite(), 'portal_catalog')
"""Resolves a UUID to an object via the UID index of portal_catalog."""
catalog = getToolByName(getSite(), "portal_catalog")
res = catalog.unrestrictedSearchResults(UID=uuid)
if res:
return res[0]._unrestrictedGetObject()
Expand All @@ -40,31 +37,33 @@ def uuidToObject(uuid):
try:
from plone.uuid.interfaces import IUUID
except ImportError:

def uuidFor(obj):
return obj.UID()

else:

def uuidFor(obj):
uuid = IUUID(obj, None)
if uuid is None and hasattr(aq_base(obj), 'UID'):
if uuid is None and hasattr(aq_base(obj), "UID"):
uuid = obj.UID()
return uuid


@implementer(IPublishTraverse)
class ResolveUIDView(BrowserView):
"""Resolve a URL like /resolveuid/<uuid> to a normalized URL.
"""
"""Resolve a URL like /resolveuid/<uuid> to a normalized URL."""

subpath = None

def publishTraverse(self, request, name):
self.uuid = name
traverse_subpath = self.request['TraversalRequestNameStack']
traverse_subpath = self.request["TraversalRequestNameStack"]
if traverse_subpath:
traverse_subpath = list(traverse_subpath)
traverse_subpath.reverse()
self.subpath = traverse_subpath
self.request['TraversalRequestNameStack'] = []
self.request["TraversalRequestNameStack"] = []
return self

def __call__(self):
Expand All @@ -74,11 +73,11 @@ def __call__(self):
raise NotFound("The link you followed is broken")

if self.subpath:
url = '/'.join([url] + self.subpath)
url = "/".join([url] + self.subpath)

if self.request.QUERY_STRING:
url += '?' + self.request.QUERY_STRING
url += "?" + self.request.QUERY_STRING

self.request.response.redirect(url, status=301)

return ''
return ""
7 changes: 3 additions & 4 deletions plone/outputfilters/filters/example.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
# -*- coding: utf-8 -*-
from plone.outputfilters.interfaces import IFilter
from zope.interface import implementer

import re


@implementer(IFilter)
class EmDashAdder(object):
class EmDashAdder:
order = 1000

def __init__(self, context, request):
Expand All @@ -15,7 +14,7 @@ def __init__(self, context, request):
def is_enabled(self):
return True

pattern = re.compile(r'--')
pattern = re.compile(r"--")

def __call__(self, data):
return self.pattern.sub(u'—', data)
return self.pattern.sub("—", data)
Loading

0 comments on commit 1725dd8

Please sign in to comment.