Python 2.6 `str.format()` compatibility fixes.

pull/33268/merge
Matt Clay 7 years ago
parent 95ff8f1a90
commit 797664d9cb

@ -97,7 +97,7 @@ class ProxmoxAPI(object):
raise Exception('Missing mandatory parameter --password (or PROXMOX_PASSWORD).')
def auth(self):
request_path = '{}api2/json/access/ticket'.format(self.options.url)
request_path = '{0}api2/json/access/ticket'.format(self.options.url)
request_params = urlencode({
'username': self.options.username,
@ -112,9 +112,9 @@ class ProxmoxAPI(object):
}
def get(self, url, data=None):
request_path = '{}{}'.format(self.options.url, url)
request_path = '{0}{1}'.format(self.options.url, url)
headers = {'Cookie': 'PVEAuthCookie={}'.format(self.credentials['ticket'])}
headers = {'Cookie': 'PVEAuthCookie={0}'.format(self.credentials['ticket'])}
request = open_url(request_path, data=data, headers=headers)
response = json.load(request)
@ -124,10 +124,10 @@ class ProxmoxAPI(object):
return ProxmoxNodeList(self.get('api2/json/nodes'))
def vms_by_type(self, node, type):
return ProxmoxVMList(self.get('api2/json/nodes/{}/{}'.format(node, type)))
return ProxmoxVMList(self.get('api2/json/nodes/{0}/{1}'.format(node, type)))
def vm_description_by_type(self, node, vm, type):
return self.get('api2/json/nodes/{}/{}/{}/config'.format(node, type, vm))
return self.get('api2/json/nodes/{0}/{1}/{2}/config'.format(node, type, vm))
def node_qemu(self, node):
return self.vms_by_type(node, 'qemu')
@ -145,7 +145,7 @@ class ProxmoxAPI(object):
return ProxmoxPoolList(self.get('api2/json/pools'))
def pool(self, poolid):
return ProxmoxPool(self.get('api2/json/pools/{}'.format(poolid)))
return ProxmoxPool(self.get('api2/json/pools/{0}'.format(poolid)))
def main_list(options):

@ -173,7 +173,7 @@ def main():
config = yaml.safe_load(stream)
break
if not config:
sys.stderr.write("No config file found at {}\n".format(config_files))
sys.stderr.write("No config file found at {0}\n".format(config_files))
sys.exit(1)
client, auth_creds = stack_auth(config['stacki']['auth'])
header = stack_build_header(auth_creds)

@ -91,8 +91,8 @@ def main():
sys.stderr.write('Passwords do not match\n')
sys.exit(1)
else:
sys.stdout.write('{}\n'.format(keyring.get_password(keyname,
username)))
sys.stdout.write('{0}\n'.format(keyring.get_password(keyname,
username)))
sys.exit(0)

@ -77,15 +77,15 @@ def main():
print("UP ***********")
for host, result in callback.host_ok.items():
print('{} >>> {}'.format(host, result._result['stdout']))
print('{0} >>> {1}'.format(host, result._result['stdout']))
print("FAILED *******")
for host, result in callback.host_failed.items():
print('{} >>> {}'.format(host, result._result['msg']))
print('{0} >>> {1}'.format(host, result._result['msg']))
print("DOWN *********")
for host, result in callback.host_unreachable.items():
print('{} >>> {}'.format(host, result._result['msg']))
print('{0} >>> {1}'.format(host, result._result['msg']))
if __name__ == '__main__':
main()

@ -48,6 +48,6 @@ if __name__ == '__main__':
finally:
os.chdir(orig_dir)
except:
print("Problem occurred. Patch saved in: {}".format(patchfilename))
print("Problem occurred. Patch saved in: {0}".format(patchfilename))
else:
os.remove(patchfilename)

@ -113,11 +113,11 @@ def insert_metadata(module_data, new_metadata, insertion_line, targets=('ANSIBLE
pretty_metadata = pformat(new_metadata, width=1).split('\n')
new_lines = []
new_lines.append('{} = {}'.format(assignments, pretty_metadata[0]))
new_lines.append('{0} = {1}'.format(assignments, pretty_metadata[0]))
if len(pretty_metadata) > 1:
for line in pretty_metadata[1:]:
new_lines.append('{}{}'.format(' ' * (len(assignments) - 1 + len(' = {')), line))
new_lines.append('{0}{1}'.format(' ' * (len(assignments) - 1 + len(' = {')), line))
old_lines = module_data.split('\n')
lines = old_lines[:insertion_line] + new_lines + old_lines[insertion_line:]
@ -209,7 +209,7 @@ def write_metadata(filename, new_metadata, version=None, overwrite=False):
raise
# Probably non-python modules. These should all have python
# documentation files where we can place the data
raise ParseError('Could not add metadata to {}'.format(filename))
raise ParseError('Could not add metadata to {0}'.format(filename))
if current_metadata is None:
# No current metadata so we can just add it
@ -219,7 +219,7 @@ def write_metadata(filename, new_metadata, version=None, overwrite=False):
# These aren't new-style modules
return
raise Exception('Module file {} had no ANSIBLE_METADATA or DOCUMENTATION'.format(filename))
raise Exception('Module file {0} had no ANSIBLE_METADATA or DOCUMENTATION'.format(filename))
module_data = insert_metadata(module_data, new_metadata, start_line, targets=('ANSIBLE_METADATA',))
@ -363,7 +363,7 @@ def add_from_csv(csv_file, version=None, overwrite=False):
for module_name, new_metadata in parse_assigned_metadata(csv_file):
filename = module_loader.find_plugin(module_name, mod_type='.py')
if filename is None:
diagnostic_messages.append('Unable to find the module file for {}'.format(module_name))
diagnostic_messages.append('Unable to find the module file for {0}'.format(module_name))
continue
try:

@ -80,7 +80,7 @@ class DimensionDataModule(object):
# Region and location are common to all Dimension Data modules.
region = self.module.params['region']
self.region = 'dd-{}'.format(region)
self.region = 'dd-{0}'.format(region)
self.location = self.module.params['location']
libcloud.security.VERIFY_SSL_CERT = self.module.params['validate_certs']

@ -227,7 +227,7 @@ def search_by_attributes(service, **kwargs):
# Check if 'list' method support search(look for search parameter):
if 'search' in inspect.getargspec(service.list)[0]:
res = service.list(
search=' and '.join('{}={}'.format(k, v) for k, v in kwargs.items())
search=' and '.join('{0}={1}'.format(k, v) for k, v in kwargs.items())
)
else:
res = [
@ -712,7 +712,7 @@ class BaseModule(object):
if entity is None:
self._module.fail_json(
msg="Entity not found, can't run action '{}'.".format(
msg="Entity not found, can't run action '{0}'.".format(
action
)
)

@ -105,7 +105,7 @@ def uldap():
def construct():
try:
secret_file = open('/etc/ldap.secret', 'r')
bind_dn = 'cn=admin,{}'.format(base_dn())
bind_dn = 'cn=admin,{0}'.format(base_dn())
except IOError: # pragma: no cover
secret_file = open('/etc/machine.secret', 'r')
bind_dn = config_registry()["ldap/hostdn"]

@ -36,7 +36,7 @@ class CallbackModule(CallbackBase):
self.play = None
def v2_on_any(self, *args, **kwargs):
self._display.display("--- play: {} task: {} ---".format(getattr(self.play, 'name', None), self.task))
self._display.display("--- play: {0} task: {1} ---".format(getattr(self.play, 'name', None), self.task))
self._display.display(" --- ARGS ")
for i, a in enumerate(args):

@ -141,7 +141,7 @@ class CallbackModule(CallbackBase):
response = open_url(url, data=data, headers=headers, method='POST')
return response.read()
except Exception as ex:
self._display.warning('Could not submit message to hipchat: {}'.format(ex))
self._display.warning('Could not submit message to hipchat: {0}'.format(ex))
def send_msg_v1(self, msg, msg_format='text', color='yellow', notify=False):
"""Method for sending a message to HipChat"""
@ -159,7 +159,7 @@ class CallbackModule(CallbackBase):
response = open_url(url, data=urlencode(params))
return response.read()
except Exception as ex:
self._display.warning('Could not submit message to hipchat: {}'.format(ex))
self._display.warning('Could not submit message to hipchat: {0}'.format(ex))
def v2_playbook_on_play_start(self, play):
"""Display Playbook and play start messages"""

@ -282,7 +282,7 @@ class CallbackModule(CallbackBase):
def emit(self, record):
msg = record.rstrip('\n')
msg = "{} {}".format(self.token, msg)
msg = "{0} {1}".format(self.token, msg)
self._appender.put(msg)
self._display.vvvv("Sent event to logentries")

@ -71,7 +71,7 @@ def colorize(msg, color):
if DONT_COLORIZE:
return msg
else:
return '{}{}{}'.format(COLORS[color], msg, COLORS['endc'])
return '{0}{1}{2}'.format(COLORS[color], msg, COLORS['endc'])
class CallbackModule(CallbackBase):
@ -104,15 +104,15 @@ class CallbackModule(CallbackBase):
line_length = 120
if self.last_skipped:
print()
msg = colorize("# {} {}".format(task_name,
'*' * (line_length - len(task_name))), 'bold')
msg = colorize("# {0} {1}".format(task_name,
'*' * (line_length - len(task_name))), 'bold')
print(msg)
def _indent_text(self, text, indent_level):
lines = text.splitlines()
result_lines = []
for l in lines:
result_lines.append("{}{}".format(' ' * indent_level, l))
result_lines.append("{0}{1}".format(' ' * indent_level, l))
return '\n'.join(result_lines)
def _print_diff(self, diff, indent_level):

@ -55,7 +55,7 @@ class Connection(Jail):
jail_uuid = self.get_jail_uuid()
kwargs[Jail.modified_jailname_key] = 'ioc-{}'.format(jail_uuid)
kwargs[Jail.modified_jailname_key] = 'ioc-{0}'.format(jail_uuid)
display.vvv(u"Jail {iocjail} has been translated to {rawjail}".format(
iocjail=self.ioc_jail, rawjail=kwargs[Jail.modified_jailname_key]),
@ -74,6 +74,6 @@ class Connection(Jail):
p.wait()
if p.returncode != 0:
raise AnsibleError(u"iocage returned an error: {}".format(stdout))
raise AnsibleError(u"iocage returned an error: {0}".format(stdout))
return stdout.strip('\n')

@ -75,7 +75,7 @@ class LookupModule(LookupBase):
setattr(self, arg, parsed)
except ValueError:
raise AnsibleError(
"can't parse arg {}={} as string".format(arg, arg_raw)
"can't parse arg {0}={1} as string".format(arg, arg_raw)
)
if args:
raise AnsibleError(

@ -72,7 +72,7 @@ class Hiera(object):
pargs.extend(hiera_key)
rc, output, err = run_cmd("{} -c {} {}".format(
rc, output, err = run_cmd("{0} -c {1} {2}".format(
ANSIBLE_HIERA_BIN, ANSIBLE_HIERA_CFG, hiera_key[0]))
return output.strip()

@ -121,7 +121,7 @@ class LookupModule(LookupBase):
return sort_parameter
if not isinstance(sort_parameter, list):
raise AnsibleError(u"Error. Sort parameters must be a list, not [ {} ]".format(sort_parameter))
raise AnsibleError(u"Error. Sort parameters must be a list, not [ {0} ]".format(sort_parameter))
for item in sort_parameter:
self._convert_sort_string_to_constant(item)
@ -160,7 +160,7 @@ class LookupModule(LookupBase):
return (result - datetime.datetime(1970, 1, 1)). total_seconds()
else:
# failsafe
return u"{}".format(result)
return u"{0}".format(result)
def run(self, terms, variables, **kwargs):

@ -154,14 +154,14 @@ class LookupModule(LookupBase):
if self.paramvals['length'].isdigit():
self.paramvals['length'] = int(self.paramvals['length'])
else:
raise AnsibleError("{} is not a correct value for length".format(self.paramvals['length']))
raise AnsibleError("{0} is not a correct value for length".format(self.paramvals['length']))
# Set PASSWORD_STORE_DIR if directory is set
if self.paramvals['directory']:
if os.path.isdir(self.paramvals['directory']):
os.environ['PASSWORD_STORE_DIR'] = self.paramvals['directory']
else:
raise AnsibleError('Passwordstore directory \'{}\' does not exist'.format(self.paramvals['directory']))
raise AnsibleError('Passwordstore directory \'{0}\' does not exist'.format(self.paramvals['directory']))
def check_pass(self):
try:
@ -180,7 +180,7 @@ class LookupModule(LookupBase):
# if pass returns 1 and return string contains 'is not in the password store.'
# We need to determine if this is valid or Error.
if not self.paramvals['create']:
raise AnsibleError('passname: {} not found, use create=True'.format(self.passname))
raise AnsibleError('passname: {0} not found, use create=True'.format(self.passname))
else:
return False
else:
@ -199,7 +199,7 @@ class LookupModule(LookupBase):
newpass = self.get_newpass()
datetime = time.strftime("%d/%m/%Y %H:%M:%S")
msg = newpass + '\n' + '\n'.join(self.passoutput[1:])
msg += "\nlookup_pass: old password was {} (Updated on {})\n".format(self.password, datetime)
msg += "\nlookup_pass: old password was {0} (Updated on {1})\n".format(self.password, datetime)
try:
check_output2(['pass', 'insert', '-f', '-m', self.passname], input=msg)
except (subprocess.CalledProcessError) as e:
@ -211,7 +211,7 @@ class LookupModule(LookupBase):
# use pwgen to generate the password and insert values with pass -m
newpass = self.get_newpass()
datetime = time.strftime("%d/%m/%Y %H:%M:%S")
msg = newpass + '\n' + "lookup_pass: First generated by ansible on {}\n".format(datetime)
msg = newpass + '\n' + "lookup_pass: First generated by ansible on {0}\n".format(datetime)
try:
check_output2(['pass', 'insert', '-f', '-m', self.passname], input=msg)
except (subprocess.CalledProcessError) as e:

@ -1,15 +1,6 @@
contrib/inventory/proxmox.py ansible-format-automatic-specification
contrib/inventory/stacki.py ansible-format-automatic-specification
contrib/vault/vault-keyring.py ansible-format-automatic-specification
examples/scripts/uptime.py ansible-format-automatic-specification
hacking/cherrypick.py ansible-format-automatic-specification
hacking/metadata-tool.py ansible-format-automatic-specification
lib/ansible/cli/adhoc.py syntax-error 3.7
lib/ansible/module_utils/dimensiondata.py ansible-format-automatic-specification
lib/ansible/module_utils/network/aci/aci.py ansible-format-automatic-specification
lib/ansible/module_utils/network/iosxr/iosxr.py ansible-format-automatic-specification
lib/ansible/module_utils/ovirt.py ansible-format-automatic-specification
lib/ansible/module_utils/univention_umc.py ansible-format-automatic-specification
lib/ansible/modules/cloud/amazon/aws_api_gateway.py ansible-format-automatic-specification
lib/ansible/modules/cloud/amazon/aws_kms.py ansible-format-automatic-specification
lib/ansible/modules/cloud/amazon/ec2_eip.py ansible-format-automatic-specification
@ -111,17 +102,8 @@ lib/ansible/modules/storage/infinidat/infini_vol.py ansible-format-automatic-spe
lib/ansible/modules/storage/purestorage/purefa_host.py ansible-format-automatic-specification
lib/ansible/modules/storage/purestorage/purefa_pg.py ansible-format-automatic-specification
lib/ansible/modules/system/firewalld.py ansible-format-automatic-specification
lib/ansible/plugins/callback/context_demo.py ansible-format-automatic-specification
lib/ansible/plugins/callback/hipchat.py ansible-format-automatic-specification
lib/ansible/plugins/callback/logentries.py ansible-format-automatic-specification
lib/ansible/plugins/callback/selective.py ansible-format-automatic-specification
lib/ansible/plugins/cliconf/junos.py ansible-no-format-on-bytestring 3
lib/ansible/plugins/cliconf/nxos.py ansible-format-automatic-specification
lib/ansible/plugins/connection/iocage.py ansible-format-automatic-specification
lib/ansible/plugins/lookup/chef_databag.py ansible-format-automatic-specification
lib/ansible/plugins/lookup/hiera.py ansible-format-automatic-specification
lib/ansible/plugins/lookup/mongodb.py ansible-format-automatic-specification
lib/ansible/plugins/lookup/passwordstore.py ansible-format-automatic-specification
test/runner/importer.py missing-docstring 3.7
test/runner/injector/importer.py missing-docstring 3.7
test/runner/injector/injector.py missing-docstring 3.7
@ -167,4 +149,3 @@ test/runner/shippable.py missing-docstring 3.7
test/runner/test.py missing-docstring 3.7
test/runner/units/test_diff.py missing-docstring 3.7
test/units/modules/network/nuage/test_nuage_vspk.py syntax-error 3.7
test/units/modules/remote_management/oneview/hpe_test_utils.py ansible-format-automatic-specification

@ -50,7 +50,7 @@ class OneViewBaseTest(object):
EXAMPLES = yaml.load(testing_module.EXAMPLES, yaml.SafeLoader)
except yaml.scanner.ScannerError:
message = "Something went wrong while parsing yaml from {}.EXAMPLES".format(self.testing_class.__module__)
message = "Something went wrong while parsing yaml from {0}.EXAMPLES".format(self.testing_class.__module__)
raise Exception(message)
return testing_module
@ -152,7 +152,7 @@ class OneViewBaseTestCase(object):
self.EXAMPLES = yaml.load(self.testing_module.EXAMPLES, yaml.SafeLoader)
except yaml.scanner.ScannerError:
message = "Something went wrong while parsing yaml from {}.EXAMPLES".format(self.testing_class.__module__)
message = "Something went wrong while parsing yaml from {0}.EXAMPLES".format(self.testing_class.__module__)
raise Exception(message)

Loading…
Cancel
Save