From 797664d9cb681a66b3c2e17405d23b9c8723321c Mon Sep 17 00:00:00 2001 From: Matt Clay Date: Wed, 10 Jan 2018 12:03:25 -0800 Subject: [PATCH] Python 2.6 `str.format()` compatibility fixes. --- contrib/inventory/proxmox.py | 12 ++++++------ contrib/inventory/stacki.py | 2 +- contrib/vault/vault-keyring.py | 4 ++-- examples/scripts/uptime.py | 6 +++--- hacking/cherrypick.py | 2 +- hacking/metadata-tool.py | 10 +++++----- lib/ansible/module_utils/dimensiondata.py | 2 +- lib/ansible/module_utils/ovirt.py | 4 ++-- lib/ansible/module_utils/univention_umc.py | 2 +- lib/ansible/plugins/callback/context_demo.py | 2 +- lib/ansible/plugins/callback/hipchat.py | 4 ++-- lib/ansible/plugins/callback/logentries.py | 2 +- lib/ansible/plugins/callback/selective.py | 8 ++++---- lib/ansible/plugins/connection/iocage.py | 4 ++-- lib/ansible/plugins/lookup/chef_databag.py | 2 +- lib/ansible/plugins/lookup/hiera.py | 2 +- lib/ansible/plugins/lookup/mongodb.py | 4 ++-- lib/ansible/plugins/lookup/passwordstore.py | 10 +++++----- test/sanity/pylint/ignore.txt | 19 ------------------- .../oneview/hpe_test_utils.py | 4 ++-- 20 files changed, 43 insertions(+), 62 deletions(-) diff --git a/contrib/inventory/proxmox.py b/contrib/inventory/proxmox.py index fd675ef4aaa..afa7032ad20 100755 --- a/contrib/inventory/proxmox.py +++ b/contrib/inventory/proxmox.py @@ -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): diff --git a/contrib/inventory/stacki.py b/contrib/inventory/stacki.py index a61f6b8fee2..824ecaf5e7a 100755 --- a/contrib/inventory/stacki.py +++ b/contrib/inventory/stacki.py @@ -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) diff --git a/contrib/vault/vault-keyring.py b/contrib/vault/vault-keyring.py index 461f2137d54..69a1e902ecd 100755 --- a/contrib/vault/vault-keyring.py +++ b/contrib/vault/vault-keyring.py @@ -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) diff --git a/examples/scripts/uptime.py b/examples/scripts/uptime.py index e27c5e83b27..68bf375cdc6 100755 --- a/examples/scripts/uptime.py +++ b/examples/scripts/uptime.py @@ -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() diff --git a/hacking/cherrypick.py b/hacking/cherrypick.py index 0f1b4b8d2a8..d99f4055953 100755 --- a/hacking/cherrypick.py +++ b/hacking/cherrypick.py @@ -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) diff --git a/hacking/metadata-tool.py b/hacking/metadata-tool.py index ddd85493556..2da3a809dcf 100755 --- a/hacking/metadata-tool.py +++ b/hacking/metadata-tool.py @@ -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: diff --git a/lib/ansible/module_utils/dimensiondata.py b/lib/ansible/module_utils/dimensiondata.py index 694ecea946a..09dce3b6111 100644 --- a/lib/ansible/module_utils/dimensiondata.py +++ b/lib/ansible/module_utils/dimensiondata.py @@ -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'] diff --git a/lib/ansible/module_utils/ovirt.py b/lib/ansible/module_utils/ovirt.py index 314d29946fc..39806e8b6f4 100644 --- a/lib/ansible/module_utils/ovirt.py +++ b/lib/ansible/module_utils/ovirt.py @@ -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 ) ) diff --git a/lib/ansible/module_utils/univention_umc.py b/lib/ansible/module_utils/univention_umc.py index cbc9ea3fd98..9c84930cf55 100644 --- a/lib/ansible/module_utils/univention_umc.py +++ b/lib/ansible/module_utils/univention_umc.py @@ -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"] diff --git a/lib/ansible/plugins/callback/context_demo.py b/lib/ansible/plugins/callback/context_demo.py index 0229d4ea462..ec8fbb47df1 100644 --- a/lib/ansible/plugins/callback/context_demo.py +++ b/lib/ansible/plugins/callback/context_demo.py @@ -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): diff --git a/lib/ansible/plugins/callback/hipchat.py b/lib/ansible/plugins/callback/hipchat.py index f0cd1030849..c0aa12405a3 100644 --- a/lib/ansible/plugins/callback/hipchat.py +++ b/lib/ansible/plugins/callback/hipchat.py @@ -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""" diff --git a/lib/ansible/plugins/callback/logentries.py b/lib/ansible/plugins/callback/logentries.py index 53fa99a6f7a..f25925ce26d 100644 --- a/lib/ansible/plugins/callback/logentries.py +++ b/lib/ansible/plugins/callback/logentries.py @@ -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") diff --git a/lib/ansible/plugins/callback/selective.py b/lib/ansible/plugins/callback/selective.py index 372551c58b0..1c015fe5af4 100644 --- a/lib/ansible/plugins/callback/selective.py +++ b/lib/ansible/plugins/callback/selective.py @@ -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): diff --git a/lib/ansible/plugins/connection/iocage.py b/lib/ansible/plugins/connection/iocage.py index 6c0e7e050e6..b1f01c44359 100644 --- a/lib/ansible/plugins/connection/iocage.py +++ b/lib/ansible/plugins/connection/iocage.py @@ -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') diff --git a/lib/ansible/plugins/lookup/chef_databag.py b/lib/ansible/plugins/lookup/chef_databag.py index 9be0d37c6d9..2941926792b 100644 --- a/lib/ansible/plugins/lookup/chef_databag.py +++ b/lib/ansible/plugins/lookup/chef_databag.py @@ -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( diff --git a/lib/ansible/plugins/lookup/hiera.py b/lib/ansible/plugins/lookup/hiera.py index 8de81b68dac..5469c0cac9f 100644 --- a/lib/ansible/plugins/lookup/hiera.py +++ b/lib/ansible/plugins/lookup/hiera.py @@ -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() diff --git a/lib/ansible/plugins/lookup/mongodb.py b/lib/ansible/plugins/lookup/mongodb.py index 7a207e09f26..4fcabc6851b 100644 --- a/lib/ansible/plugins/lookup/mongodb.py +++ b/lib/ansible/plugins/lookup/mongodb.py @@ -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): diff --git a/lib/ansible/plugins/lookup/passwordstore.py b/lib/ansible/plugins/lookup/passwordstore.py index 3af01099523..be09f66d880 100644 --- a/lib/ansible/plugins/lookup/passwordstore.py +++ b/lib/ansible/plugins/lookup/passwordstore.py @@ -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: diff --git a/test/sanity/pylint/ignore.txt b/test/sanity/pylint/ignore.txt index ff6c2b63247..507d83110dd 100644 --- a/test/sanity/pylint/ignore.txt +++ b/test/sanity/pylint/ignore.txt @@ -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 diff --git a/test/units/modules/remote_management/oneview/hpe_test_utils.py b/test/units/modules/remote_management/oneview/hpe_test_utils.py index 42f2cdf89d7..d6660b6b137 100644 --- a/test/units/modules/remote_management/oneview/hpe_test_utils.py +++ b/test/units/modules/remote_management/oneview/hpe_test_utils.py @@ -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)