1
0
Fork 0
mirror of https://github.com/ansible-collections/community.general.git synced 2024-09-14 20:13:21 +02:00

Python 2.6 str.format() compatibility fixes.

This commit is contained in:
Matt Clay 2018-01-10 12:03:25 -08:00
parent 95ff8f1a90
commit 797664d9cb
20 changed files with 43 additions and 62 deletions

View file

@ -97,7 +97,7 @@ class ProxmoxAPI(object):
raise Exception('Missing mandatory parameter --password (or PROXMOX_PASSWORD).') raise Exception('Missing mandatory parameter --password (or PROXMOX_PASSWORD).')
def auth(self): 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({ request_params = urlencode({
'username': self.options.username, 'username': self.options.username,
@ -112,9 +112,9 @@ class ProxmoxAPI(object):
} }
def get(self, url, data=None): 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) request = open_url(request_path, data=data, headers=headers)
response = json.load(request) response = json.load(request)
@ -124,10 +124,10 @@ class ProxmoxAPI(object):
return ProxmoxNodeList(self.get('api2/json/nodes')) return ProxmoxNodeList(self.get('api2/json/nodes'))
def vms_by_type(self, node, type): 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): 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): def node_qemu(self, node):
return self.vms_by_type(node, 'qemu') return self.vms_by_type(node, 'qemu')
@ -145,7 +145,7 @@ class ProxmoxAPI(object):
return ProxmoxPoolList(self.get('api2/json/pools')) return ProxmoxPoolList(self.get('api2/json/pools'))
def pool(self, poolid): 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): def main_list(options):

View file

@ -173,7 +173,7 @@ def main():
config = yaml.safe_load(stream) config = yaml.safe_load(stream)
break break
if not config: 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) sys.exit(1)
client, auth_creds = stack_auth(config['stacki']['auth']) client, auth_creds = stack_auth(config['stacki']['auth'])
header = stack_build_header(auth_creds) header = stack_build_header(auth_creds)

View file

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

View file

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

View file

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

View file

@ -113,11 +113,11 @@ def insert_metadata(module_data, new_metadata, insertion_line, targets=('ANSIBLE
pretty_metadata = pformat(new_metadata, width=1).split('\n') pretty_metadata = pformat(new_metadata, width=1).split('\n')
new_lines = [] 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: if len(pretty_metadata) > 1:
for line in 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') old_lines = module_data.split('\n')
lines = old_lines[:insertion_line] + new_lines + old_lines[insertion_line:] 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 raise
# Probably non-python modules. These should all have python # Probably non-python modules. These should all have python
# documentation files where we can place the data # 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: if current_metadata is None:
# No current metadata so we can just add it # 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 # These aren't new-style modules
return 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',)) 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): for module_name, new_metadata in parse_assigned_metadata(csv_file):
filename = module_loader.find_plugin(module_name, mod_type='.py') filename = module_loader.find_plugin(module_name, mod_type='.py')
if filename is None: 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 continue
try: try:

View file

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

View file

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

View file

@ -105,7 +105,7 @@ def uldap():
def construct(): def construct():
try: try:
secret_file = open('/etc/ldap.secret', 'r') 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 except IOError: # pragma: no cover
secret_file = open('/etc/machine.secret', 'r') secret_file = open('/etc/machine.secret', 'r')
bind_dn = config_registry()["ldap/hostdn"] bind_dn = config_registry()["ldap/hostdn"]

View file

@ -36,7 +36,7 @@ class CallbackModule(CallbackBase):
self.play = None self.play = None
def v2_on_any(self, *args, **kwargs): 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 ") self._display.display(" --- ARGS ")
for i, a in enumerate(args): for i, a in enumerate(args):

View file

@ -141,7 +141,7 @@ class CallbackModule(CallbackBase):
response = open_url(url, data=data, headers=headers, method='POST') response = open_url(url, data=data, headers=headers, method='POST')
return response.read() return response.read()
except Exception as ex: 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): def send_msg_v1(self, msg, msg_format='text', color='yellow', notify=False):
"""Method for sending a message to HipChat""" """Method for sending a message to HipChat"""
@ -159,7 +159,7 @@ class CallbackModule(CallbackBase):
response = open_url(url, data=urlencode(params)) response = open_url(url, data=urlencode(params))
return response.read() return response.read()
except Exception as ex: 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): def v2_playbook_on_play_start(self, play):
"""Display Playbook and play start messages""" """Display Playbook and play start messages"""

View file

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

View file

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

View file

@ -55,7 +55,7 @@ class Connection(Jail):
jail_uuid = self.get_jail_uuid() 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( display.vvv(u"Jail {iocjail} has been translated to {rawjail}".format(
iocjail=self.ioc_jail, rawjail=kwargs[Jail.modified_jailname_key]), iocjail=self.ioc_jail, rawjail=kwargs[Jail.modified_jailname_key]),
@ -74,6 +74,6 @@ class Connection(Jail):
p.wait() p.wait()
if p.returncode != 0: 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') return stdout.strip('\n')

View file

@ -75,7 +75,7 @@ class LookupModule(LookupBase):
setattr(self, arg, parsed) setattr(self, arg, parsed)
except ValueError: except ValueError:
raise AnsibleError( 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: if args:
raise AnsibleError( raise AnsibleError(

View file

@ -72,7 +72,7 @@ class Hiera(object):
pargs.extend(hiera_key) 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])) ANSIBLE_HIERA_BIN, ANSIBLE_HIERA_CFG, hiera_key[0]))
return output.strip() return output.strip()

View file

@ -121,7 +121,7 @@ class LookupModule(LookupBase):
return sort_parameter return sort_parameter
if not isinstance(sort_parameter, list): 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: for item in sort_parameter:
self._convert_sort_string_to_constant(item) self._convert_sort_string_to_constant(item)
@ -160,7 +160,7 @@ class LookupModule(LookupBase):
return (result - datetime.datetime(1970, 1, 1)). total_seconds() return (result - datetime.datetime(1970, 1, 1)). total_seconds()
else: else:
# failsafe # failsafe
return u"{}".format(result) return u"{0}".format(result)
def run(self, terms, variables, **kwargs): def run(self, terms, variables, **kwargs):

View file

@ -154,14 +154,14 @@ class LookupModule(LookupBase):
if self.paramvals['length'].isdigit(): if self.paramvals['length'].isdigit():
self.paramvals['length'] = int(self.paramvals['length']) self.paramvals['length'] = int(self.paramvals['length'])
else: 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 # Set PASSWORD_STORE_DIR if directory is set
if self.paramvals['directory']: if self.paramvals['directory']:
if os.path.isdir(self.paramvals['directory']): if os.path.isdir(self.paramvals['directory']):
os.environ['PASSWORD_STORE_DIR'] = self.paramvals['directory'] os.environ['PASSWORD_STORE_DIR'] = self.paramvals['directory']
else: 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): def check_pass(self):
try: try:
@ -180,7 +180,7 @@ class LookupModule(LookupBase):
# if pass returns 1 and return string contains 'is not in the password store.' # if pass returns 1 and return string contains 'is not in the password store.'
# We need to determine if this is valid or Error. # We need to determine if this is valid or Error.
if not self.paramvals['create']: 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: else:
return False return False
else: else:
@ -199,7 +199,7 @@ class LookupModule(LookupBase):
newpass = self.get_newpass() newpass = self.get_newpass()
datetime = time.strftime("%d/%m/%Y %H:%M:%S") datetime = time.strftime("%d/%m/%Y %H:%M:%S")
msg = newpass + '\n' + '\n'.join(self.passoutput[1:]) 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: try:
check_output2(['pass', 'insert', '-f', '-m', self.passname], input=msg) check_output2(['pass', 'insert', '-f', '-m', self.passname], input=msg)
except (subprocess.CalledProcessError) as e: except (subprocess.CalledProcessError) as e:
@ -211,7 +211,7 @@ class LookupModule(LookupBase):
# use pwgen to generate the password and insert values with pass -m # use pwgen to generate the password and insert values with pass -m
newpass = self.get_newpass() newpass = self.get_newpass()
datetime = time.strftime("%d/%m/%Y %H:%M:%S") 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: try:
check_output2(['pass', 'insert', '-f', '-m', self.passname], input=msg) check_output2(['pass', 'insert', '-f', '-m', self.passname], input=msg)
except (subprocess.CalledProcessError) as e: except (subprocess.CalledProcessError) as e:

View file

@ -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/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/aci/aci.py ansible-format-automatic-specification
lib/ansible/module_utils/network/iosxr/iosxr.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_api_gateway.py ansible-format-automatic-specification
lib/ansible/modules/cloud/amazon/aws_kms.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 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_host.py ansible-format-automatic-specification
lib/ansible/modules/storage/purestorage/purefa_pg.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/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/junos.py ansible-no-format-on-bytestring 3
lib/ansible/plugins/cliconf/nxos.py ansible-format-automatic-specification 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/importer.py missing-docstring 3.7
test/runner/injector/importer.py missing-docstring 3.7 test/runner/injector/importer.py missing-docstring 3.7
test/runner/injector/injector.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/test.py missing-docstring 3.7
test/runner/units/test_diff.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/network/nuage/test_nuage_vspk.py syntax-error 3.7
test/units/modules/remote_management/oneview/hpe_test_utils.py ansible-format-automatic-specification

View file

@ -50,7 +50,7 @@ class OneViewBaseTest(object):
EXAMPLES = yaml.load(testing_module.EXAMPLES, yaml.SafeLoader) EXAMPLES = yaml.load(testing_module.EXAMPLES, yaml.SafeLoader)
except yaml.scanner.ScannerError: 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) raise Exception(message)
return testing_module return testing_module
@ -152,7 +152,7 @@ class OneViewBaseTestCase(object):
self.EXAMPLES = yaml.load(self.testing_module.EXAMPLES, yaml.SafeLoader) self.EXAMPLES = yaml.load(self.testing_module.EXAMPLES, yaml.SafeLoader)
except yaml.scanner.ScannerError: 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) raise Exception(message)