string_formatting

This commit is contained in:
Deepak Sharma 2020-01-29 22:54:26 +05:30
parent b6ecc3917e
commit d31cf696e8
33 changed files with 128 additions and 112 deletions

View File

@ -56,7 +56,7 @@ class Command(CommandContextMixIn):
super(Command, self).__init__() super(Command, self).__init__()
parser_kw = { parser_kw = {
'usage': self.usage, 'usage': self.usage,
'prog': '%s %s' % (get_prog(), name), 'prog': '{} {}'.format(get_prog(), name),
'formatter': UpdatingDefaultsHelpFormatter(), 'formatter': UpdatingDefaultsHelpFormatter(),
'add_help_option': False, 'add_help_option': False,
'name': name, 'name': name,
@ -69,7 +69,7 @@ class Command(CommandContextMixIn):
self.parser = ConfigOptionParser(**parser_kw) self.parser = ConfigOptionParser(**parser_kw)
# Commands should add options to this option group # Commands should add options to this option group
optgroup_name = '%s Options' % self.name.capitalize() optgroup_name = '{} Options'.format(self.name.capitalize())
self.cmd_opts = optparse.OptionGroup(self.parser, optgroup_name) self.cmd_opts = optparse.OptionGroup(self.parser, optgroup_name)
# Add the general options # Add the general options

View File

@ -851,12 +851,12 @@ def _handle_merge_hash(option, opt_str, value, parser):
try: try:
algo, digest = value.split(':', 1) algo, digest = value.split(':', 1)
except ValueError: except ValueError:
parser.error('Arguments to %s must be a hash name ' parser.error('Arguments to {} must be a hash name '
'followed by a value, like --hash=sha256:abcde...' % 'followed by a value, like --hash=sha256:'
opt_str) 'abcde...'.format(opt_str))
if algo not in STRONG_HASHES: if algo not in STRONG_HASHES:
parser.error('Allowed hash algorithms for %s are %s.' % parser.error('Allowed hash algorithms for {} are {}.'.format(
(opt_str, ', '.join(STRONG_HASHES))) opt_str, ', '.join(STRONG_HASHES)))
parser.values.hashes.setdefault(algo, []).append(digest) parser.values.hashes.setdefault(algo, []).append(digest)

View File

@ -59,7 +59,7 @@ def main(args=None):
try: try:
cmd_name, cmd_args = parse_command(args) cmd_name, cmd_args = parse_command(args)
except PipError as exc: except PipError as exc:
sys.stderr.write("ERROR: %s" % exc) sys.stderr.write("ERROR: {}".format(exc))
sys.stderr.write(os.linesep) sys.stderr.write(os.linesep)
sys.exit(1) sys.exit(1)

View File

@ -86,9 +86,9 @@ def parse_command(args):
if cmd_name not in commands_dict: if cmd_name not in commands_dict:
guess = get_similar_commands(cmd_name) guess = get_similar_commands(cmd_name)
msg = ['unknown command "%s"' % cmd_name] msg = ['unknown command "{}"'.format(cmd_name)]
if guess: if guess:
msg.append('maybe you meant "%s"' % guess) msg.append('maybe you meant "{}"'.format(guess))
raise CommandError(' - '.join(msg)) raise CommandError(' - '.join(msg))

View File

@ -33,7 +33,7 @@ class PrettyHelpFormatter(optparse.IndentedHelpFormatter):
def format_option_strings(self, option): def format_option_strings(self, option):
return self._format_option_strings(option, ' <%s>', ', ') return self._format_option_strings(option, ' <%s>', ', ')
def _format_option_strings(self, option, mvarfmt=' <%s>', optsep=', '): def _format_option_strings(self, option, mvarfmt=' <{}>', optsep=', '):
""" """
Return a comma-separated list of option strings and metavars. Return a comma-separated list of option strings and metavars.
@ -52,7 +52,7 @@ class PrettyHelpFormatter(optparse.IndentedHelpFormatter):
if option.takes_value(): if option.takes_value():
metavar = option.metavar or option.dest.lower() metavar = option.metavar or option.dest.lower()
opts.append(mvarfmt % metavar.lower()) opts.append(mvarfmt.format(metavar.lower()))
return ''.join(opts) return ''.join(opts)
@ -66,7 +66,8 @@ class PrettyHelpFormatter(optparse.IndentedHelpFormatter):
Ensure there is only one newline between usage and the first heading Ensure there is only one newline between usage and the first heading
if there is no description. if there is no description.
""" """
msg = '\nUsage: %s\n' % self.indent_lines(textwrap.dedent(usage), " ") msg = '\nUsage: {}\n'.format(
self.indent_lines(textwrap.dedent(usage), " "))
return msg return msg
def format_description(self, description): def format_description(self, description):
@ -82,7 +83,7 @@ class PrettyHelpFormatter(optparse.IndentedHelpFormatter):
description = description.rstrip() description = description.rstrip()
# dedent, then reindent # dedent, then reindent
description = self.indent_lines(textwrap.dedent(description), " ") description = self.indent_lines(textwrap.dedent(description), " ")
description = '%s:\n%s\n' % (label, description) description = '{}:\n{}\n'.format(label, description)
return description return description
else: else:
return '' return ''
@ -150,7 +151,7 @@ class ConfigOptionParser(CustomOptionParser):
try: try:
return option.check_value(key, val) return option.check_value(key, val)
except optparse.OptionValueError as exc: except optparse.OptionValueError as exc:
print("An error occurred during configuration: %s" % exc) print("An error occurred during configuration: {}".format(exc))
sys.exit(3) sys.exit(3)
def _get_ordered_configuration_items(self): def _get_ordered_configuration_items(self):
@ -249,7 +250,7 @@ class ConfigOptionParser(CustomOptionParser):
def error(self, msg): def error(self, msg):
self.print_usage(sys.stderr) self.print_usage(sys.stderr)
self.exit(UNKNOWN_ERROR, "%s\n" % msg) self.exit(UNKNOWN_ERROR, "{}\n".format(msg))
def invalid_config_error_message(action, key, val): def invalid_config_error_message(action, key, val):

View File

@ -92,5 +92,5 @@ class CompletionCommand(Command):
print(BASE_COMPLETION % {'script': script, 'shell': options.shell}) print(BASE_COMPLETION % {'script': script, 'shell': options.shell})
else: else:
sys.stderr.write( sys.stderr.write(
'ERROR: You must pass %s\n' % ' or '.join(shell_options) 'ERROR: You must pass {}\n' .format(' or '.join(shell_options))
) )

View File

@ -65,7 +65,7 @@ class FreezeCommand(Command):
dest='freeze_all', dest='freeze_all',
action='store_true', action='store_true',
help='Do not skip these packages in the output:' help='Do not skip these packages in the output:'
' %s' % ', '.join(DEV_PKGS)) ' {}'.format(', '.join(DEV_PKGS)))
self.cmd_opts.add_option( self.cmd_opts.add_option(
'--exclude-editable', '--exclude-editable',
dest='exclude_editable', dest='exclude_editable',

View File

@ -34,8 +34,8 @@ class HashCommand(Command):
choices=STRONG_HASHES, choices=STRONG_HASHES,
action='store', action='store',
default=FAVORITE_HASH, default=FAVORITE_HASH,
help='The hash algorithm to use: one of %s' % help='The hash algorithm to use: one of {}'.format(
', '.join(STRONG_HASHES)) ', '.join(STRONG_HASHES)))
self.parser.insert_option_group(0, self.cmd_opts) self.parser.insert_option_group(0, self.cmd_opts)
def run(self, options, args): def run(self, options, args):

View File

@ -29,9 +29,9 @@ class HelpCommand(Command):
if cmd_name not in commands_dict: if cmd_name not in commands_dict:
guess = get_similar_commands(cmd_name) guess = get_similar_commands(cmd_name)
msg = ['unknown command "%s"' % cmd_name] msg = ['unknown command "{}"'.format(cmd_name)]
if guess: if guess:
msg.append('maybe you meant "%s"' % guess) msg.append('maybe you meant "{}"'.format(guess))
raise CommandError(' - '.join(msg)) raise CommandError(' - '.join(msg))

View File

@ -255,8 +255,8 @@ class HashMismatch(HashError):
self.gots = gots self.gots = gots
def body(self): def body(self):
return ' %s:\n%s' % (self._requirement_name(), return ' {}:\n{}'.format(self._requirement_name(),
self._hash_comparison()) self._hash_comparison())
def _hash_comparison(self): def _hash_comparison(self):
""" """
@ -277,10 +277,10 @@ class HashMismatch(HashError):
lines = [] lines = []
for hash_name, expecteds in iteritems(self.allowed): for hash_name, expecteds in iteritems(self.allowed):
prefix = hash_then_or(hash_name) prefix = hash_then_or(hash_name)
lines.extend((' Expected %s %s' % (next(prefix), e)) lines.extend((' Expected {} {}'.format(next(prefix), e))
for e in expecteds) for e in expecteds)
lines.append(' Got %s\n' % lines.append(' Got {}\n'.format(
self.gots[hash_name].hexdigest()) self.gots[hash_name].hexdigest()))
return '\n'.join(lines) return '\n'.join(lines)

View File

@ -354,7 +354,7 @@ def _get_html_page(link, session=None):
reason += str(exc) reason += str(exc)
_handle_get_page_fail(link, reason, meth=logger.info) _handle_get_page_fail(link, reason, meth=logger.info)
except requests.ConnectionError as exc: except requests.ConnectionError as exc:
_handle_get_page_fail(link, "connection error: %s" % exc) _handle_get_page_fail(link, "connection error: {}".format(exc))
except requests.Timeout: except requests.Timeout:
_handle_get_page_fail(link, "timed out") _handle_get_page_fail(link, "timed out")
else: else:

View File

@ -177,9 +177,10 @@ class LinkEvaluator(object):
if not ext: if not ext:
return (False, 'not a file') return (False, 'not a file')
if ext not in SUPPORTED_EXTENSIONS: if ext not in SUPPORTED_EXTENSIONS:
return (False, 'unsupported archive format: %s' % ext) return (False, 'unsupported archive format: {}'.format(ext))
if "binary" not in self._formats and ext == WHEEL_EXTENSION: if "binary" not in self._formats and ext == WHEEL_EXTENSION:
reason = 'No binaries permitted for %s' % self.project_name reason = 'No binaries permitted for {}'.format(
self.project_name)
return (False, reason) return (False, reason)
if "macosx10" in link.path and ext == '.zip': if "macosx10" in link.path and ext == '.zip':
return (False, 'macosx10 one') return (False, 'macosx10 one')
@ -189,7 +190,8 @@ class LinkEvaluator(object):
except InvalidWheelFilename: except InvalidWheelFilename:
return (False, 'invalid wheel filename') return (False, 'invalid wheel filename')
if canonicalize_name(wheel.name) != self._canonical_name: if canonicalize_name(wheel.name) != self._canonical_name:
reason = 'wrong project name (not %s)' % self.project_name reason = 'wrong project name (not {})'.format(
self.project_name)
return (False, reason) return (False, reason)
supported_tags = self._target_python.get_tags() supported_tags = self._target_python.get_tags()
@ -208,16 +210,16 @@ class LinkEvaluator(object):
# This should be up by the self.ok_binary check, but see issue 2700. # This should be up by the self.ok_binary check, but see issue 2700.
if "source" not in self._formats and ext != WHEEL_EXTENSION: if "source" not in self._formats and ext != WHEEL_EXTENSION:
return (False, 'No sources permitted for %s' % self.project_name) reason = 'No sources permitted for {}'.format(self.project_name)
return (False, reason)
if not version: if not version:
version = _extract_version_from_fragment( version = _extract_version_from_fragment(
egg_info, self._canonical_name, egg_info, self._canonical_name,
) )
if not version: if not version:
return ( reason = 'Missing project version for {}'.format(self.project_name)
False, 'Missing project version for %s' % self.project_name, return (False, reason)
)
match = self._py_version_re.search(version) match = self._py_version_re.search(version)
if match: if match:
@ -524,8 +526,8 @@ class CandidateEvaluator(object):
wheel = Wheel(link.filename) wheel = Wheel(link.filename)
if not wheel.supported(valid_tags): if not wheel.supported(valid_tags):
raise UnsupportedWheel( raise UnsupportedWheel(
"%s is not a supported wheel for this platform. It " "{} is not a supported wheel for this platform. It "
"can't be sorted." % wheel.filename "can't be sorted.".format(wheel.filename)
) )
if self._prefer_binary: if self._prefer_binary:
binary_preference = 1 binary_preference = 1
@ -924,7 +926,8 @@ class PackageFinder(object):
) )
raise DistributionNotFound( raise DistributionNotFound(
'No matching distribution found for %s' % req 'No matching distribution found for {}'.format(
req)
) )
best_installed = False best_installed = False

View File

@ -66,12 +66,12 @@ class Link(KeyBasedCompareMixin):
def __str__(self): def __str__(self):
# type: () -> str # type: () -> str
if self.requires_python: if self.requires_python:
rp = ' (requires-python:%s)' % self.requires_python rp = ' (requires-python:{})'.format(self.requires_python)
else: else:
rp = '' rp = ''
if self.comes_from: if self.comes_from:
return '%s (from %s)%s' % (redact_auth_from_url(self._url), return '{} (from {}){}'.format(
self.comes_from, rp) redact_auth_from_url(self._url), self.comes_from, rp)
else: else:
return redact_auth_from_url(str(self._url)) return redact_auth_from_url(str(self._url))

View File

@ -30,7 +30,7 @@ class Wheel(object):
wheel_info = self.wheel_file_re.match(filename) wheel_info = self.wheel_file_re.match(filename)
if not wheel_info: if not wheel_info:
raise InvalidWheelFilename( raise InvalidWheelFilename(
"%s is not a valid wheel filename." % filename "{} is not a valid wheel filename.".format(filename)
) )
self.filename = filename self.filename = filename
self.name = wheel_info.group('name').replace('_', '-') self.name = wheel_info.group('name').replace('_', '-')

View File

@ -215,7 +215,7 @@ class MultiDomainBasicAuth(AuthBase):
# Factored out to allow for easy patching in tests # Factored out to allow for easy patching in tests
def _prompt_for_password(self, netloc): def _prompt_for_password(self, netloc):
username = ask_input("User for %s: " % netloc) username = ask_input("User for {}: ".format(netloc))
if not username: if not username:
return None, None return None, None
auth = get_keyring_auth(netloc, username) auth = get_keyring_auth(netloc, username)

View File

@ -89,7 +89,7 @@ def build_wheel_legacy(
destination_dir=tempd, destination_dir=tempd,
) )
spin_message = 'Building wheel for %s (setup.py)' % (name,) spin_message = 'Building wheel for {} (setup.py)'.format(name)
with open_spinner(spin_message) as spinner: with open_spinner(spin_message) as spinner:
logger.debug('Destination directory: %s', tempd) logger.debug('Destination directory: %s', tempd)

View File

@ -60,7 +60,7 @@ def freeze(
skip_match = re.compile(skip_regex).search skip_match = re.compile(skip_regex).search
for link in find_links: for link in find_links:
yield '-f %s' % link yield '-f {}'.format(link)
installations = {} # type: Dict[str, FrozenRequirement] installations = {} # type: Dict[str, FrozenRequirement]
for dist in get_installed_distributions(local_only=local_only, for dist in get_installed_distributions(local_only=local_only,
skip=(), skip=(),
@ -261,5 +261,5 @@ class FrozenRequirement(object):
def __str__(self): def __str__(self):
req = self.req req = self.req
if self.editable: if self.editable:
req = '-e %s' % req req = '-e {}'.format(req)
return '\n'.join(list(self.comments) + [str(req)]) + '\n' return '\n'.join(list(self.comments) + [str(req)]) + '\n'

View File

@ -504,11 +504,11 @@ def install_unpacked_wheel(
if os.environ.get("ENSUREPIP_OPTIONS", "") != "altinstall": if os.environ.get("ENSUREPIP_OPTIONS", "") != "altinstall":
scripts_to_generate.append( scripts_to_generate.append(
'pip%s = %s' % (sys.version_info[0], pip_script) 'pip{} = {}'.format(sys.version_info[0], pip_script)
) )
scripts_to_generate.append( scripts_to_generate.append(
'pip%s = %s' % (get_major_minor_version(), pip_script) 'pip{} = {}'.format(get_major_minor_version(), pip_script)
) )
# Delete any other versioned pip entry points # Delete any other versioned pip entry points
pip_ep = [k for k in console if re.match(r'pip(\d(\.\d)?)?$', k)] pip_ep = [k for k in console if re.match(r'pip(\d(\.\d)?)?$', k)]
@ -522,7 +522,7 @@ def install_unpacked_wheel(
) )
scripts_to_generate.append( scripts_to_generate.append(
'easy_install-%s = %s' % ( 'easy_install-{} = {}'.format(
get_major_minor_version(), easy_install_script get_major_minor_version(), easy_install_script
) )
) )

View File

@ -48,18 +48,17 @@ def install_given_reqs(
""" """
if to_install: if to_install:
msg = 'Installing collected packages: {}'.format( logger.info(
', '.join([req.name for req in to_install]) 'Installing collected packages: %s',
', '.join([req.name for req in to_install]),
) )
logger.info(msg)
installed = [] installed = []
with indent_log(): with indent_log():
for requirement in to_install: for requirement in to_install:
if requirement.should_reinstall: if requirement.should_reinstall:
logger.info('Attempting uninstall: {}'.format( logger.info('Attempting uninstall: %s', requirement.name)
requirement.name))
with indent_log(): with indent_log():
uninstalled_pathset = requirement.uninstall( uninstalled_pathset = requirement.uninstall(
auto_confirm=True auto_confirm=True

View File

@ -137,16 +137,17 @@ def parse_editable(editable_req):
vc_type = url.split('+', 1)[0].lower() vc_type = url.split('+', 1)[0].lower()
if not vcs.get_backend(vc_type): if not vcs.get_backend(vc_type):
error_message = 'For --editable=%s only ' % editable_req + \ error_message = 'For --editable={} only '.format(
', '.join([backend.name + '+URL' for backend in vcs.backends]) + \ editable_req + ', '.join(
' is currently supported' [backend.name + '+URL' for backend in vcs.backends]) +
' is currently supported')
raise InstallationError(error_message) raise InstallationError(error_message)
package_name = Link(url).egg_fragment package_name = Link(url).egg_fragment
if not package_name: if not package_name:
raise InstallationError( raise InstallationError(
"Could not detect requirement name for '%s', please specify one " "Could not detect requirement name for '{}', please specify one "
"with #egg=your_package_name" % editable_req "with #egg=your_package_name".format(editable_req)
) )
return package_name, url, None return package_name, url, None
@ -166,16 +167,18 @@ def deduce_helpful_msg(req):
with open(req, 'r') as fp: with open(req, 'r') as fp:
# parse first line only # parse first line only
next(parse_requirements(fp.read())) next(parse_requirements(fp.read()))
msg += " The argument you provided " + \ msg += (
"(%s) appears to be a" % (req) + \ "The argument you provided "
" requirements file. If that is the" + \ "({}) appears to be a"
" case, use the '-r' flag to install" + \ " requirements file. If that is the"
" case, use the '-r' flag to install"
" the packages specified within it." " the packages specified within it."
).format(req)
except RequirementParseError: except RequirementParseError:
logger.debug("Cannot parse '%s' as requirements \ logger.debug("Cannot parse '%s' as requirements \
file" % (req), exc_info=True) file" % (req), exc_info=True)
else: else:
msg += " File '%s' does not exist." % (req) msg += " File '{}' does not exist.".format(req)
return msg return msg
@ -201,7 +204,7 @@ def parse_req_from_editable(editable_req):
try: try:
req = Requirement(name) req = Requirement(name)
except InvalidRequirement: except InvalidRequirement:
raise InstallationError("Invalid requirement: '%s'" % name) raise InstallationError("Invalid requirement: '{}'".format(name))
else: else:
req = None req = None
@ -415,7 +418,7 @@ def install_req_from_req_string(
try: try:
req = Requirement(req_string) req = Requirement(req_string)
except InvalidRequirement: except InvalidRequirement:
raise InstallationError("Invalid requirement: '%s'" % req_string) raise InstallationError("Invalid requirement: '{}'".format(req_string))
domains_not_allowed = [ domains_not_allowed = [
PyPI.file_storage_domain, PyPI.file_storage_domain,
@ -427,7 +430,7 @@ def install_req_from_req_string(
raise InstallationError( raise InstallationError(
"Packages installed from PyPI cannot depend on packages " "Packages installed from PyPI cannot depend on packages "
"which are not also hosted on PyPI.\n" "which are not also hosted on PyPI.\n"
"%s depends on %s " % (comes_from.name, req) "{} depends on {} ".format(comes_from.name, req)
) )
return InstallRequirement( return InstallRequirement(

View File

@ -183,7 +183,7 @@ def handle_line(
""" """
# preserve for the nested code path # preserve for the nested code path
line_comes_from = '%s %s (line %s)' % ( line_comes_from = '{} {} (line {})'.format(
'-c' if line.constraint else '-r', line.filename, line.lineno, '-c' if line.constraint else '-r', line.filename, line.lineno,
) )
@ -329,7 +329,7 @@ class RequirementsFileParser(object):
args_str, opts = self._line_parser(line) args_str, opts = self._line_parser(line)
except OptionParsingError as e: except OptionParsingError as e:
# add offending line # add offending line
msg = 'Invalid requirement: %s\n%s' % (line, e.msg) msg = 'Invalid requirement: {}\n{}'.format(line, e.msg)
raise RequirementsFileParseError(msg) raise RequirementsFileParseError(msg)
yield ParsedLine( yield ParsedLine(
@ -520,8 +520,9 @@ def get_file_content(url, session, comes_from=None):
elif scheme == 'file': elif scheme == 'file':
if comes_from and comes_from.startswith('http'): if comes_from and comes_from.startswith('http'):
raise InstallationError( raise InstallationError(
'Requirements file %s references URL %s, which is local' 'Requirements file {} references URL {}, '
% (comes_from, url)) 'which is local'.format(comes_from, url)
)
path = url.split(':', 1)[1] path = url.split(':', 1)[1]
path = path.replace('\\', '/') path = path.replace('\\', '/')
@ -538,7 +539,7 @@ def get_file_content(url, session, comes_from=None):
content = auto_decode(f.read()) content = auto_decode(f.read())
except IOError as exc: except IOError as exc:
raise InstallationError( raise InstallationError(
'Could not open requirements file: %s' % str(exc) 'Could not open requirements file: {}'.format(exc)
) )
return url, content return url, content

View File

@ -195,25 +195,25 @@ class InstallRequirement(object):
if self.req: if self.req:
s = str(self.req) s = str(self.req)
if self.link: if self.link:
s += ' from %s' % redact_auth_from_url(self.link.url) s += ' from {}'.format(redact_auth_from_url(self.link.url))
elif self.link: elif self.link:
s = redact_auth_from_url(self.link.url) s = redact_auth_from_url(self.link.url)
else: else:
s = '<InstallRequirement>' s = '<InstallRequirement>'
if self.satisfied_by is not None: if self.satisfied_by is not None:
s += ' in %s' % display_path(self.satisfied_by.location) s += ' in {}'.format(display_path(self.satisfied_by.location))
if self.comes_from: if self.comes_from:
if isinstance(self.comes_from, six.string_types): if isinstance(self.comes_from, six.string_types):
comes_from = self.comes_from # type: Optional[str] comes_from = self.comes_from # type: Optional[str]
else: else:
comes_from = self.comes_from.from_path() comes_from = self.comes_from.from_path()
if comes_from: if comes_from:
s += ' (from %s)' % comes_from s += ' (from {})'.format(comes_from)
return s return s
def __repr__(self): def __repr__(self):
# type: () -> str # type: () -> str
return '<%s object: %s editable=%r>' % ( return '<{} object: {} editable={!r}>'.format(
self.__class__.__name__, str(self), self.editable) self.__class__.__name__, str(self), self.editable)
def format_debug(self): def format_debug(self):
@ -452,8 +452,8 @@ class InstallRequirement(object):
dist_in_site_packages(existing_dist)): dist_in_site_packages(existing_dist)):
raise InstallationError( raise InstallationError(
"Will not install to the user site because it will " "Will not install to the user site because it will "
"lack sys.path precedence to %s in %s" % "lack sys.path precedence to {} in {}".format(
(existing_dist.project_name, existing_dist.location) existing_dist.project_name, existing_dist.location)
) )
else: else:
self.should_reinstall = True self.should_reinstall = True
@ -483,7 +483,7 @@ class InstallRequirement(object):
@property @property
def setup_py_path(self): def setup_py_path(self):
# type: () -> str # type: () -> str
assert self.source_dir, "No source dir for %s" % self assert self.source_dir, "No source dir for {}".format(self)
setup_py = os.path.join(self.unpacked_source_directory, 'setup.py') setup_py = os.path.join(self.unpacked_source_directory, 'setup.py')
# Python2 __file__ should not be unicode # Python2 __file__ should not be unicode
@ -495,7 +495,7 @@ class InstallRequirement(object):
@property @property
def pyproject_toml_path(self): def pyproject_toml_path(self):
# type: () -> str # type: () -> str
assert self.source_dir, "No source dir for %s" % self assert self.source_dir, "No source dir for {}".format(self)
return make_pyproject_path(self.unpacked_source_directory) return make_pyproject_path(self.unpacked_source_directory)
def load_pyproject_toml(self): def load_pyproject_toml(self):
@ -654,8 +654,8 @@ class InstallRequirement(object):
vcs_backend.export(self.source_dir, url=hidden_url) vcs_backend.export(self.source_dir, url=hidden_url)
else: else:
assert 0, ( assert 0, (
'Unexpected version control type (in %s): %s' 'Unexpected version control type (in {}): {}'.format(
% (self.link, vc_type)) self.link, vc_type))
# Top-level Actions # Top-level Actions
def uninstall(self, auto_confirm=False, verbose=False): def uninstall(self, auto_confirm=False, verbose=False):
@ -710,13 +710,15 @@ class InstallRequirement(object):
assert self.source_dir assert self.source_dir
create_archive = True create_archive = True
archive_name = '%s-%s.zip' % (self.name, self.metadata["version"]) archive_name = '{}-{}.zip'.format(self.name, self.metadata["version"])
archive_path = os.path.join(build_dir, archive_name) archive_path = os.path.join(build_dir, archive_name)
if os.path.exists(archive_path): if os.path.exists(archive_path):
response = ask_path_exists( response = ask_path_exists(
'The file %s exists. (i)gnore, (w)ipe, (b)ackup, (a)bort ' % 'The file {} exists. (i)gnore, (w)ipe, '
display_path(archive_path), ('i', 'w', 'b', 'a')) '(b)ackup, (a)bort '.format(
display_path(archive_path)),
('i', 'w', 'b', 'a'))
if response == 'i': if response == 'i':
create_archive = False create_archive = False
elif response == 'w': elif response == 'w':

View File

@ -108,8 +108,8 @@ class RequirementSet(object):
tags = pep425tags.get_supported() tags = pep425tags.get_supported()
if (self.check_supported_wheels and not wheel.supported(tags)): if (self.check_supported_wheels and not wheel.supported(tags)):
raise InstallationError( raise InstallationError(
"%s is not a supported wheel on this platform." % "{} is not a supported wheel on this platform.".format(
wheel.filename wheel.filename)
) )
# This next bit is really a sanity check. # This next bit is really a sanity check.
@ -138,8 +138,8 @@ class RequirementSet(object):
) )
if has_conflicting_requirement: if has_conflicting_requirement:
raise InstallationError( raise InstallationError(
"Double requirement given: %s (already in %s, name=%r)" "Double requirement given: {} (already in {}, name={!r})"
% (install_req, existing_req, install_req.name) .format(install_req, existing_req, install_req.name)
) )
# When no existing requirement exists, add the requirement as a # When no existing requirement exists, add the requirement as a
@ -164,9 +164,9 @@ class RequirementSet(object):
if does_not_satisfy_constraint: if does_not_satisfy_constraint:
self.reqs_to_cleanup.append(install_req) self.reqs_to_cleanup.append(install_req)
raise InstallationError( raise InstallationError(
"Could not satisfy constraints for '%s': " "Could not satisfy constraints for '{}': "
"installation from path or url cannot be " "installation from path or url cannot be "
"constrained to a version" % install_req.name, "constrained to a version".format(install_req.name)
) )
# If we're now installing a constraint, mark the existing # If we're now installing a constraint, mark the existing
# object for real installation. # object for real installation.

View File

@ -60,7 +60,7 @@ def get_requirement_tracker():
TempDirectory(kind='req-tracker') TempDirectory(kind='req-tracker')
).path ).path
ctx.enter_context(update_env_context_manager(PIP_REQ_TRACKER=root)) ctx.enter_context(update_env_context_manager(PIP_REQ_TRACKER=root))
logger.debug("Initialized build tracking at {}".format(root)) logger.debug("Initialized build tracking at %s", root)
with RequirementTracker(root) as tracker: with RequirementTracker(root) as tracker:
yield tracker yield tracker
@ -111,7 +111,8 @@ class RequirementTracker(object):
if e.errno != errno.ENOENT: if e.errno != errno.ENOENT:
raise raise
else: else:
message = '%s is already being built: %s' % (req.link, contents) message = '{} is already being built: {}'.format(
req.link, contents)
raise LookupError(message) raise LookupError(message)
# If we're here, req should really not be building already. # If we're here, req should really not be building already.

View File

@ -540,8 +540,9 @@ class UninstallPathSet(object):
with open(develop_egg_link, 'r') as fh: with open(develop_egg_link, 'r') as fh:
link_pointer = os.path.normcase(fh.readline().strip()) link_pointer = os.path.normcase(fh.readline().strip())
assert (link_pointer == dist.location), ( assert (link_pointer == dist.location), (
'Egg-link %s does not match installed location of %s ' 'Egg-link {} does not match installed location of {} '
'(at %s)' % (link_pointer, dist.project_name, dist.location) '(at {})'.format(
link_pointer, dist.project_name, dist.location)
) )
paths_to_remove.add(develop_egg_link) paths_to_remove.add(develop_egg_link)
easy_install_pth = os.path.join(os.path.dirname(develop_egg_link), easy_install_pth = os.path.join(os.path.dirname(develop_egg_link),
@ -586,7 +587,8 @@ class UninstallPthEntries(object):
# type: (str) -> None # type: (str) -> None
if not os.path.isfile(pth_file): if not os.path.isfile(pth_file):
raise UninstallationError( raise UninstallationError(
"Cannot remove entries from nonexistent file %s" % pth_file "Cannot remove entries from nonexistent file {}".format(
pth_file)
) )
self.file = pth_file self.file = pth_file
self.entries = set() # type: Set[str] self.entries = set() # type: Set[str]

View File

@ -184,7 +184,8 @@ def get_path_uid(path):
else: else:
# raise OSError for parity with os.O_NOFOLLOW above # raise OSError for parity with os.O_NOFOLLOW above
raise OSError( raise OSError(
"%s is a symlink; Will not return uid for symlinks" % path "{} is a symlink; Will not return uid for symlinks".format(
path)
) )
return file_uid return file_uid

View File

@ -73,7 +73,9 @@ class Hashes(object):
try: try:
gots[hash_name] = hashlib.new(hash_name) gots[hash_name] = hashlib.new(hash_name)
except (ValueError, TypeError): except (ValueError, TypeError):
raise InstallationError('Unknown hash name: %s' % hash_name) raise InstallationError(
'Unknown hash name: {}'.format(hash_name)
)
for chunk in chunks: for chunk in chunks:
for hash in itervalues(gots): for hash in itervalues(gots):

View File

@ -120,7 +120,7 @@ def get_prog():
try: try:
prog = os.path.basename(sys.argv[0]) prog = os.path.basename(sys.argv[0])
if prog in ('__main__.py', '-c'): if prog in ('__main__.py', '-c'):
return "%s -m pip" % sys.executable return "{} -m pip".format(sys.executable)
else: else:
return prog return prog
except (AttributeError, TypeError, IndexError): except (AttributeError, TypeError, IndexError):
@ -228,8 +228,8 @@ def _check_no_input(message):
"""Raise an error if no input is allowed.""" """Raise an error if no input is allowed."""
if os.environ.get('PIP_NO_INPUT'): if os.environ.get('PIP_NO_INPUT'):
raise Exception( raise Exception(
'No input was expected ($PIP_NO_INPUT set); question: %s' % 'No input was expected ($PIP_NO_INPUT set); question: {}'.format(
message message)
) )
@ -242,8 +242,8 @@ def ask(message, options):
response = response.strip().lower() response = response.strip().lower()
if response not in options: if response not in options:
print( print(
'Your response (%r) was not one of the expected responses: ' 'Your response ({!r}) was not one of the expected responses: '
'%s' % (response, ', '.join(options)) '{}'.format(response, ', '.join(options))
) )
else: else:
return response return response

View File

@ -242,14 +242,14 @@ def call_subprocess(
raise InstallationError(exc_msg) raise InstallationError(exc_msg)
elif on_returncode == 'warn': elif on_returncode == 'warn':
subprocess_logger.warning( subprocess_logger.warning(
'Command "%s" had error code %s in %s', 'Command "{}" had error code {} in {}'.format(
command_desc, proc.returncode, cwd, command_desc, proc.returncode, cwd)
) )
elif on_returncode == 'ignore': elif on_returncode == 'ignore':
pass pass
else: else:
raise ValueError('Invalid value: on_returncode=%s' % raise ValueError('Invalid value: on_returncode={!r}'.format(
repr(on_returncode)) on_returncode))
return ''.join(all_output) return ''.join(all_output)

View File

@ -153,7 +153,7 @@ class DownloadProgressMixin(object):
@property @property
def pretty_eta(self): def pretty_eta(self):
if self.eta: if self.eta:
return "eta %s" % self.eta_td return "eta {}".format(self.eta_td)
return "" return ""
def iter(self, it): def iter(self, it):
@ -399,7 +399,7 @@ class NonInteractiveSpinner(SpinnerInterface):
# type: (str) -> None # type: (str) -> None
if self._finished: if self._finished:
return return
self._update("finished with status '%s'" % (final_status,)) self._update("finished with status '{}'".format(final_status))
self._finished = True self._finished = True

View File

@ -215,8 +215,8 @@ def check_compatibility(version, name):
""" """
if version[0] > VERSION_COMPATIBLE[0]: if version[0] > VERSION_COMPATIBLE[0]:
raise UnsupportedWheel( raise UnsupportedWheel(
"%s's Wheel-Version (%s) is not compatible with this version " "{}'s Wheel-Version ({}) is not compatible with this version "
"of pip" % (name, '.'.join(map(str, version))) "of pip".format(name, '.'.join(map(str, version)))
) )
elif version > VERSION_COMPATIBLE: elif version > VERSION_COMPATIBLE:
logger.warning( logger.warning(

View File

@ -574,7 +574,8 @@ class VersionControl(object):
self.name, self.name,
url, url,
) )
response = ask_path_exists('What to do? %s' % prompt[0], prompt[1]) response = ask_path_exists('What to do? {}'.format(
prompt[0]), prompt[1])
if response == 'a': if response == 'a':
sys.exit(-1) sys.exit(-1)