From ed8e60d804973bdb6703daa24255bb8fc24d2988 Mon Sep 17 00:00:00 2001 From: Toshio Kuratomi Date: Wed, 19 Dec 2018 20:45:47 -0800 Subject: [PATCH] Cleanups and fixes to cli * Mark methods which are really functions as staticmethod * Fix calls to other staticmethods to use the subclass rather than the base class so that any inheritance overriding will be honored. * Remove unnecessary logic and dead code * Fix a typo in a docstring of how to implement subclass init_parser() methods * Call superclass's post_process_args in ansible-doc * Fix copyright comment according to suggested practice --- lib/ansible/cli/__init__.py | 12 +-- lib/ansible/cli/adhoc.py | 2 +- lib/ansible/cli/config.py | 4 +- lib/ansible/cli/doc.py | 139 ++++++++++++++++++++--------------- lib/ansible/cli/galaxy.py | 10 ++- lib/ansible/cli/inventory.py | 34 ++++----- lib/ansible/cli/playbook.py | 3 +- lib/ansible/cli/pull.py | 20 ++--- lib/ansible/cli/vault.py | 3 +- 9 files changed, 126 insertions(+), 101 deletions(-) diff --git a/lib/ansible/cli/__init__.py b/lib/ansible/cli/__init__.py index b707ac1587..4b2a2da1b9 100644 --- a/lib/ansible/cli/__init__.py +++ b/lib/ansible/cli/__init__.py @@ -247,7 +247,8 @@ class CLI(with_metaclass(ABCMeta, object)): return vault_secrets - def ask_passwords(self): + @staticmethod + def ask_passwords(): ''' prompt for connection and become passwords if needed ''' op = context.CLIARGS @@ -347,7 +348,7 @@ class CLI(with_metaclass(ABCMeta, object)): An implementation will look something like this:: def init_parser(self): - super(MyCLI, self).init__parser(usage="My Ansible CLI", inventory_opts=True) + super(MyCLI, self).init_parser(usage="My Ansible CLI", inventory_opts=True) ansible.arguments.optparse_helpers.add_runas_options(self.parser) self.parser.add_option('--my-option', dest='my_option', action='store') """ @@ -449,7 +450,8 @@ class CLI(with_metaclass(ABCMeta, object)): 'minor': ansible_versions[1], 'revision': ansible_versions[2]} - def pager(self, text): + @staticmethod + def pager(text): ''' find reasonable way to display text ''' # this is a much simpler form of what is in pydoc.py if not sys.stdout.isatty(): @@ -458,12 +460,12 @@ class CLI(with_metaclass(ABCMeta, object)): if sys.platform == 'win32': display.display(text, screen_only=True) else: - self.pager_pipe(text, os.environ['PAGER']) + CLI.pager_pipe(text, os.environ['PAGER']) else: p = subprocess.Popen('less --version', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.communicate() if p.returncode == 0: - self.pager_pipe(text, 'less') + CLI.pager_pipe(text, 'less') else: display.display(text, screen_only=True) diff --git a/lib/ansible/cli/adhoc.py b/lib/ansible/cli/adhoc.py index cfd6c76477..be9341b0d3 100644 --- a/lib/ansible/cli/adhoc.py +++ b/lib/ansible/cli/adhoc.py @@ -1,5 +1,5 @@ # Copyright: (c) 2012, Michael DeHaan -# Copyright: (c) 2018, Toshio Kuratomi +# Copyright: (c) 2018, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) diff --git a/lib/ansible/cli/config.py b/lib/ansible/cli/config.py index 7b9fee201d..63416e0cdd 100644 --- a/lib/ansible/cli/config.py +++ b/lib/ansible/cli/config.py @@ -1,4 +1,4 @@ -# Copyright: (c) 2017-2018, Ansible Project +# Copyright: (c) 2017, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) @@ -62,7 +62,7 @@ class ConfigCLI(CLI): self.parser.set_usage("usage: %prog update [options] [-c ansible.cfg] ") def post_process_args(self, options, args): - super(ConfigCLI, self).post_process_args(options, args) + options, args = super(ConfigCLI, self).post_process_args(options, args) display.verbosity = options.verbosity return options, args diff --git a/lib/ansible/cli/doc.py b/lib/ansible/cli/doc.py index 2299751390..4eb14b1a29 100644 --- a/lib/ansible/cli/doc.py +++ b/lib/ansible/cli/doc.py @@ -71,6 +71,8 @@ class DocCLI(CLI): choices=C.DOCUMENTABLE_PLUGINS) def post_process_args(self, options, args): + options, args = super(DocCLI, self).post_process_args(options, args) + if [options.all_plugins, options.json_dump, options.list_dir, options.list_files, options.show_snippet].count(True) > 1: raise AnsibleOptionsError("Only one of -l, -F, -s, -j or -a can be used at the same time.") @@ -102,38 +104,38 @@ class DocCLI(CLI): loader.add_directory(path) # save only top level paths for errors - search_paths = self.print_paths(loader) + search_paths = DocCLI.print_paths(loader) loader._paths = None # reset so we can use subdirs below # list plugins names and filepath for type if context.CLIARGS['list_files']: paths = loader._get_paths() for path in paths: - self.plugin_list.update(self.find_plugins(path, plugin_type)) + self.plugin_list.update(DocCLI.find_plugins(path, plugin_type)) list_text = self.get_plugin_list_filenames(loader) - self.pager(list_text) + DocCLI.pager(list_text) return 0 # list plugins for type if context.CLIARGS['list_dir']: paths = loader._get_paths() for path in paths: - self.plugin_list.update(self.find_plugins(path, plugin_type)) + self.plugin_list.update(DocCLI.find_plugins(path, plugin_type)) - self.pager(self.get_plugin_list_text(loader)) + DocCLI.pager(self.get_plugin_list_text(loader)) return 0 # dump plugin desc/metadata as JSON if context.CLIARGS['json_dump']: plugin_data = {} - plugin_names = self.get_all_plugins_of_type(plugin_type) + plugin_names = DocCLI.get_all_plugins_of_type(plugin_type) for plugin_name in plugin_names: - plugin_info = self.get_plugin_metadata(plugin_type, plugin_name) + plugin_info = DocCLI.get_plugin_metadata(plugin_type, plugin_name) if plugin_info is not None: plugin_data[plugin_name] = plugin_info - self.pager(json.dumps(plugin_data, sort_keys=True, indent=4)) + DocCLI.pager(json.dumps(plugin_data, sort_keys=True, indent=4)) return 0 @@ -143,26 +145,28 @@ class DocCLI(CLI): # process command line list text = '' for plugin in context.CLIARGS['args']: - textret = self.format_plugin_doc(plugin, loader, plugin_type, search_paths) + textret = DocCLI.format_plugin_doc(plugin, loader, plugin_type, search_paths) if textret: text += textret if text: - self.pager(text) + DocCLI.pager(text) return 0 - def get_all_plugins_of_type(self, plugin_type): + @staticmethod + def get_all_plugins_of_type(plugin_type): loader = getattr(plugin_loader, '%s_loader' % plugin_type) plugin_list = set() paths = loader._get_paths() for path in paths: - plugins_to_add = self.find_plugins(path, plugin_type) + plugins_to_add = DocCLI.find_plugins(path, plugin_type) plugin_list.update(plugins_to_add) return sorted(set(plugin_list)) - def get_plugin_metadata(self, plugin_type, plugin_name): + @staticmethod + def get_plugin_metadata(plugin_type, plugin_name): # if the plugin lives in a non-python file (eg, win_X.ps1), require the corresponding python file for docs loader = getattr(plugin_loader, '%s_loader' % plugin_type) filename = loader.find_plugin(plugin_name, mod_type='.py', ignore_deprecated=True, check_aliases=True) @@ -188,12 +192,13 @@ class DocCLI(CLI): return dict( name=plugin_name, - namespace=self.namespace_from_plugin_filepath(filename, plugin_name, loader.package_path), + namespace=DocCLI.namespace_from_plugin_filepath(filename, plugin_name, loader.package_path), description=doc.get('short_description', "UNKNOWN"), version_added=doc.get('version_added', "UNKNOWN") ) - def namespace_from_plugin_filepath(self, filepath, plugin_name, basedir): + @staticmethod + def namespace_from_plugin_filepath(filepath, plugin_name, basedir): if not basedir.endswith('/'): basedir += '/' rel_path = filepath.replace(basedir, '') @@ -205,7 +210,8 @@ class DocCLI(CLI): return clean_ns - def format_plugin_doc(self, plugin, loader, plugin_type, search_paths): + @staticmethod + def format_plugin_doc(plugin, loader, plugin_type, search_paths): text = '' try: @@ -248,9 +254,9 @@ class DocCLI(CLI): doc['docuri'] = doc[plugin_type].replace('_', '-') if context.CLIARGS['show_snippet'] and plugin_type == 'module': - text += self.get_snippet_text(doc) + text += DocCLI.get_snippet_text(doc) else: - text += self.get_man_text(doc) + text += DocCLI.get_man_text(doc) return text else: @@ -266,7 +272,8 @@ class DocCLI(CLI): raise AnsibleError( "%s %s missing documentation (or could not parse documentation): %s\n" % (plugin_type, plugin, to_native(e))) - def find_plugins(self, path, ptype): + @staticmethod + def find_plugins(path, ptype): display.vvvv("Searching %s for plugins" % path) @@ -340,7 +347,7 @@ class DocCLI(CLI): continue desc = 'UNDOCUMENTED' else: - desc = self.tty_ify(doc.get('short_description', 'INVALID SHORT DESCRIPTION').strip()) + desc = DocCLI.tty_ify(doc.get('short_description', 'INVALID SHORT DESCRIPTION').strip()) if len(desc) > linelimit: desc = desc[:linelimit] + '...' @@ -394,10 +401,11 @@ class DocCLI(CLI): ret.append(i) return os.pathsep.join(ret) - def get_snippet_text(self, doc): + @staticmethod + def get_snippet_text(doc): text = [] - desc = CLI.tty_ify(doc['short_description']) + desc = DocCLI.tty_ify(doc['short_description']) text.append("- name: %s" % (desc)) text.append(" %s:" % (doc['module'])) pad = 31 @@ -407,9 +415,9 @@ class DocCLI(CLI): for o in sorted(doc['options'].keys()): opt = doc['options'][o] if isinstance(opt['description'], string_types): - desc = CLI.tty_ify(opt['description']) + desc = DocCLI.tty_ify(opt['description']) else: - desc = CLI.tty_ify(" ".join(opt['description'])) + desc = DocCLI.tty_ify(" ".join(opt['description'])) required = opt.get('required', False) if not isinstance(required, bool): @@ -422,10 +430,14 @@ class DocCLI(CLI): return "\n".join(text) - def _dump_yaml(self, struct, indent): - return CLI.tty_ify('\n'.join([indent + line for line in yaml.dump(struct, default_flow_style=False, Dumper=AnsibleDumper).split('\n')])) + @staticmethod + def _dump_yaml(struct, indent): + return DocCLI.tty_ify('\n'.join([indent + line for line in + yaml.dump(struct, default_flow_style=False, + Dumper=AnsibleDumper).split('\n')])) - def add_fields(self, text, fields, limit, opt_indent): + @staticmethod + def add_fields(text, fields, limit, opt_indent): for o in sorted(fields): opt = fields[o] @@ -442,9 +454,9 @@ class DocCLI(CLI): if isinstance(opt['description'], list): for entry in opt['description']: - text.append(textwrap.fill(CLI.tty_ify(entry), limit, initial_indent=opt_indent, subsequent_indent=opt_indent)) + text.append(textwrap.fill(DocCLI.tty_ify(entry), limit, initial_indent=opt_indent, subsequent_indent=opt_indent)) else: - text.append(textwrap.fill(CLI.tty_ify(opt['description']), limit, initial_indent=opt_indent, subsequent_indent=opt_indent)) + text.append(textwrap.fill(DocCLI.tty_ify(opt['description']), limit, initial_indent=opt_indent, subsequent_indent=opt_indent)) del opt['description'] aliases = '' @@ -461,37 +473,41 @@ class DocCLI(CLI): if 'default' in opt or not required: default = "[Default: %s" % str(opt.pop('default', '(null)')) + "]" - text.append(textwrap.fill(CLI.tty_ify(aliases + choices + default), limit, initial_indent=opt_indent, subsequent_indent=opt_indent)) + text.append(textwrap.fill(DocCLI.tty_ify(aliases + choices + default), limit, + initial_indent=opt_indent, subsequent_indent=opt_indent)) if 'options' in opt: text.append("%soptions:\n" % opt_indent) - self.add_fields(text, opt.pop('options'), limit, opt_indent + opt_indent) + DocCLI.add_fields(text, opt.pop('options'), limit, opt_indent + opt_indent) if 'spec' in opt: text.append("%sspec:\n" % opt_indent) - self.add_fields(text, opt.pop('spec'), limit, opt_indent + opt_indent) + DocCLI.add_fields(text, opt.pop('spec'), limit, opt_indent + opt_indent) conf = {} for config in ('env', 'ini', 'yaml', 'vars', 'keywords'): if config in opt and opt[config]: conf[config] = opt.pop(config) - for ignore in self.IGNORE: + for ignore in DocCLI.IGNORE: for item in conf[config]: if ignore in item: del item[ignore] if conf: - text.append(self._dump_yaml({'set_via': conf}, opt_indent)) + text.append(DocCLI._dump_yaml({'set_via': conf}, opt_indent)) for k in sorted(opt): if k.startswith('_'): continue if isinstance(opt[k], string_types): - text.append('%s%s: %s' % (opt_indent, k, textwrap.fill(CLI.tty_ify(opt[k]), limit - (len(k) + 2), subsequent_indent=opt_indent))) + text.append('%s%s: %s' % (opt_indent, k, + textwrap.fill(DocCLI.tty_ify(opt[k]), + limit - (len(k) + 2), + subsequent_indent=opt_indent))) elif isinstance(opt[k], (Sequence)) and all(isinstance(x, string_types) for x in opt[k]): - text.append(CLI.tty_ify('%s%s: %s' % (opt_indent, k, ', '.join(opt[k])))) + text.append(DocCLI.tty_ify('%s%s: %s' % (opt_indent, k, ', '.join(opt[k])))) else: - text.append(self._dump_yaml({k: opt[k]}, opt_indent)) + text.append(DocCLI._dump_yaml({k: opt[k]}, opt_indent)) text.append('') @staticmethod @@ -519,9 +535,10 @@ class DocCLI(CLI): text.append("\t%s: %s" % (k.capitalize(), doc['metadata'][k])) return text - def get_man_text(self, doc): + @staticmethod + def get_man_text(doc): - self.IGNORE = self.IGNORE + (context.CLIARGS['type'],) + DocCLI.IGNORE = DocCLI.IGNORE + (context.CLIARGS['type'],) opt_indent = " " text = [] pad = display.columns * 0.20 @@ -534,7 +551,8 @@ class DocCLI(CLI): else: desc = doc.pop('description') - text.append("%s\n" % textwrap.fill(CLI.tty_ify(desc), limit, initial_indent=opt_indent, subsequent_indent=opt_indent)) + text.append("%s\n" % textwrap.fill(DocCLI.tty_ify(desc), limit, initial_indent=opt_indent, + subsequent_indent=opt_indent)) if 'deprecated' in doc and doc['deprecated'] is not None and len(doc['deprecated']) > 0: text.append("DEPRECATED: \n") @@ -547,7 +565,7 @@ class DocCLI(CLI): text.append("\n") try: - support_block = self.get_support_block(doc) + support_block = DocCLI.get_support_block(doc) if support_block: text.extend(support_block) except Exception: @@ -558,13 +576,14 @@ class DocCLI(CLI): if 'options' in doc and doc['options']: text.append("OPTIONS (= is mandatory):\n") - self.add_fields(text, doc.pop('options'), limit, opt_indent) + DocCLI.add_fields(text, doc.pop('options'), limit, opt_indent) text.append('') if 'notes' in doc and doc['notes'] and len(doc['notes']) > 0: text.append("NOTES:") for note in doc['notes']: - text.append(textwrap.fill(CLI.tty_ify(note), limit - 6, initial_indent=opt_indent[:-2] + "* ", subsequent_indent=opt_indent)) + text.append(textwrap.fill(DocCLI.tty_ify(note), limit - 6, + initial_indent=opt_indent[:-2] + "* ", subsequent_indent=opt_indent)) text.append('') text.append('') del doc['notes'] @@ -573,32 +592,32 @@ class DocCLI(CLI): text.append("SEE ALSO:") for item in doc['seealso']: if 'module' in item and 'description' in item: - text.append(textwrap.fill(CLI.tty_ify('Module %s' % item['module']), + text.append(textwrap.fill(DocCLI.tty_ify('Module %s' % item['module']), limit - 6, initial_indent=opt_indent[:-2] + "* ", subsequent_indent=opt_indent)) - text.append(textwrap.fill(CLI.tty_ify(item['description']), + text.append(textwrap.fill(DocCLI.tty_ify(item['description']), limit - 6, initial_indent=opt_indent, subsequent_indent=opt_indent)) - text.append(textwrap.fill(CLI.tty_ify('https://docs.ansible.com/ansible/latest/modules/%s_module.html' % item['module']), + text.append(textwrap.fill(DocCLI.tty_ify('https://docs.ansible.com/ansible/latest/modules/%s_module.html' % item['module']), limit - 6, initial_indent=opt_indent + ' ', subsequent_indent=opt_indent)) elif 'module' in item: - text.append(textwrap.fill(CLI.tty_ify('Module %s' % item['module']), + text.append(textwrap.fill(DocCLI.tty_ify('Module %s' % item['module']), limit - 6, initial_indent=opt_indent[:-2] + "* ", subsequent_indent=opt_indent)) - text.append(textwrap.fill(CLI.tty_ify('The official documentation on the %s module.' % item['module']), + text.append(textwrap.fill(DocCLI.tty_ify('The official documentation on the %s module.' % item['module']), limit - 6, initial_indent=opt_indent + ' ', subsequent_indent=opt_indent + ' ')) - text.append(textwrap.fill(CLI.tty_ify('https://docs.ansible.com/ansible/latest/modules/%s_module.html' % item['module']), + text.append(textwrap.fill(DocCLI.tty_ify('https://docs.ansible.com/ansible/latest/modules/%s_module.html' % item['module']), limit - 6, initial_indent=opt_indent + ' ', subsequent_indent=opt_indent)) elif 'name' in item and 'link' in item and 'description' in item: - text.append(textwrap.fill(CLI.tty_ify(item['name']), + text.append(textwrap.fill(DocCLI.tty_ify(item['name']), limit - 6, initial_indent=opt_indent[:-2] + "* ", subsequent_indent=opt_indent)) - text.append(textwrap.fill(CLI.tty_ify(item['description']), + text.append(textwrap.fill(DocCLI.tty_ify(item['description']), limit - 6, initial_indent=opt_indent + ' ', subsequent_indent=opt_indent + ' ')) - text.append(textwrap.fill(CLI.tty_ify(item['link']), + text.append(textwrap.fill(DocCLI.tty_ify(item['link']), limit - 6, initial_indent=opt_indent + ' ', subsequent_indent=opt_indent + ' ')) elif 'ref' in item and 'description' in item: - text.append(textwrap.fill(CLI.tty_ify('Ansible documentation [%s]' % item['ref']), + text.append(textwrap.fill(DocCLI.tty_ify('Ansible documentation [%s]' % item['ref']), limit - 6, initial_indent=opt_indent[:-2] + "* ", subsequent_indent=opt_indent)) - text.append(textwrap.fill(CLI.tty_ify(item['description']), + text.append(textwrap.fill(DocCLI.tty_ify(item['description']), limit - 6, initial_indent=opt_indent + ' ', subsequent_indent=opt_indent + ' ')) - text.append(textwrap.fill(CLI.tty_ify('https://docs.ansible.com/ansible/latest/#stq=%s&stp=1' % item['ref']), + text.append(textwrap.fill(DocCLI.tty_ify('https://docs.ansible.com/ansible/latest/#stq=%s&stp=1' % item['ref']), limit - 6, initial_indent=opt_indent + ' ', subsequent_indent=opt_indent + ' ')) text.append('') @@ -607,18 +626,18 @@ class DocCLI(CLI): if 'requirements' in doc and doc['requirements'] is not None and len(doc['requirements']) > 0: req = ", ".join(doc.pop('requirements')) - text.append("REQUIREMENTS:%s\n" % textwrap.fill(CLI.tty_ify(req), limit - 16, initial_indent=" ", subsequent_indent=opt_indent)) + text.append("REQUIREMENTS:%s\n" % textwrap.fill(DocCLI.tty_ify(req), limit - 16, initial_indent=" ", subsequent_indent=opt_indent)) # Generic handler for k in sorted(doc): - if k in self.IGNORE or not doc[k]: + if k in DocCLI.IGNORE or not doc[k]: continue if isinstance(doc[k], string_types): - text.append('%s: %s' % (k.upper(), textwrap.fill(CLI.tty_ify(doc[k]), limit - (len(k) + 2), subsequent_indent=opt_indent))) + text.append('%s: %s' % (k.upper(), textwrap.fill(DocCLI.tty_ify(doc[k]), limit - (len(k) + 2), subsequent_indent=opt_indent))) elif isinstance(doc[k], (list, tuple)): text.append('%s: %s' % (k.upper(), ', '.join(doc[k]))) else: - text.append(self._dump_yaml({k.upper(): doc[k]}, opt_indent)) + text.append(DocCLI._dump_yaml({k.upper(): doc[k]}, opt_indent)) del doc[k] text.append('') @@ -641,7 +660,7 @@ class DocCLI(CLI): text.append('') try: - metadata_block = self.get_metadata_block(doc) + metadata_block = DocCLI.get_metadata_block(doc) if metadata_block: text.extend(metadata_block) text.append('') diff --git a/lib/ansible/cli/galaxy.py b/lib/ansible/cli/galaxy.py index c7edd05348..6ad128c6a7 100644 --- a/lib/ansible/cli/galaxy.py +++ b/lib/ansible/cli/galaxy.py @@ -145,7 +145,8 @@ class GalaxyCLI(CLI): self.api = GalaxyAPI(self.galaxy) self.execute() - def exit_without_ignore(self, rc=1): + @staticmethod + def exit_without_ignore(rc=1): """ Exits with the specified return code unless the option --ignore-errors was specified @@ -153,20 +154,21 @@ class GalaxyCLI(CLI): if not context.CLIARGS['ignore_errors']: raise AnsibleError('- you can use --ignore-errors to skip failed roles and finish processing the list.') - def _display_role_info(self, role_info): + @staticmethod + def _display_role_info(role_info): text = [u"", u"Role: %s" % to_text(role_info['name'])] text.append(u"\tdescription: %s" % role_info.get('description', '')) for k in sorted(role_info.keys()): - if k in self.SKIP_INFO_KEYS: + if k in GalaxyCLI.SKIP_INFO_KEYS: continue if isinstance(role_info[k], dict): text.append(u"\t%s:" % (k)) for key in sorted(role_info[k].keys()): - if key in self.SKIP_INFO_KEYS: + if key in GalaxyCLI.SKIP_INFO_KEYS: continue text.append(u"\t\t%s: %s" % (key, role_info[k][key])) else: diff --git a/lib/ansible/cli/inventory.py b/lib/ansible/cli/inventory.py index 2aff7ebeea..26b27f6699 100644 --- a/lib/ansible/cli/inventory.py +++ b/lib/ansible/cli/inventory.py @@ -53,10 +53,7 @@ class InventoryCLI(CLI): self.loader = None self.inventory = None - self._new_api = True - def init_parser(self): - super(InventoryCLI, self).init_parser( usage='usage: %prog [options] [host|group]', epilog='Show Ansible inventory information, by default it uses the inventory script JSON format') @@ -93,6 +90,8 @@ class InventoryCLI(CLI): # help="When doing an --list, skip vars data from vars plugins, by default, this would include group_vars/ and host_vars/") def post_process_args(self, options, args): + options, args = super(InventoryCLI, self).post_process_args(options, args) + display.verbosity = options.verbosity self.validate_conflicts(options, vault_opts=True) @@ -152,7 +151,8 @@ class InventoryCLI(CLI): exit(1) - def dump(self, stuff): + @staticmethod + def dump(stuff): if context.CLIARGS['yaml']: import yaml @@ -223,41 +223,39 @@ class InventoryCLI(CLI): for inventory_dir in self.inventory._sources: hostvars = combine_vars(hostvars, self.get_plugin_vars(inventory_dir, host)) else: - if self._new_api: - hostvars = self.vm.get_vars(host=host, include_hostvars=False) - else: - hostvars = self.vm.get_vars(self.loader, host=host, include_hostvars=False) + hostvars = self.vm.get_vars(host=host, include_hostvars=False) return hostvars def _get_group(self, gname): - if self._new_api: - group = self.inventory.groups.get(gname) - else: - group = self.inventory.get_group(gname) + group = self.inventory.groups.get(gname) return group - def _remove_internal(self, dump): + @staticmethod + def _remove_internal(dump): for internal in INTERNAL_VARS: if internal in dump: del dump[internal] - def _remove_empty(self, dump): + @staticmethod + def _remove_empty(dump): # remove empty keys for x in ('hosts', 'vars', 'children'): if x in dump and not dump[x]: del dump[x] - def _show_vars(self, dump, depth): + @staticmethod + def _show_vars(dump, depth): result = [] - self._remove_internal(dump) + InventoryCLI._remove_internal(dump) if context.CLIARGS['show_vars']: for (name, val) in sorted(dump.items()): - result.append(self._graph_name('{%s = %s}' % (name, val), depth)) + result.append(InventoryCLI._graph_name('{%s = %s}' % (name, val), depth)) return result - def _graph_name(self, name, depth=0): + @staticmethod + def _graph_name(name, depth=0): if depth: name = " |" * (depth) + "--%s" % name return name diff --git a/lib/ansible/cli/playbook.py b/lib/ansible/cli/playbook.py index c81688c23c..44dddb2ea7 100644 --- a/lib/ansible/cli/playbook.py +++ b/lib/ansible/cli/playbook.py @@ -179,7 +179,8 @@ class PlaybookCLI(CLI): else: return results - def _flush_cache(self, inventory, variable_manager): + @staticmethod + def _flush_cache(inventory, variable_manager): for host in inventory.list_hosts(): hostname = host.get_name() variable_manager.clear_facts(hostname) diff --git a/lib/ansible/cli/pull.py b/lib/ansible/cli/pull.py index 57d3c530c6..2d34c5bcdb 100644 --- a/lib/ansible/cli/pull.py +++ b/lib/ansible/cli/pull.py @@ -54,8 +54,8 @@ class PullCLI(CLI): SKIP_INVENTORY_DEFAULTS = True - def _get_inv_cli(self): - + @staticmethod + def _get_inv_cli(): inv_opts = '' if context.CLIARGS.get('inventory', False): for inv in context.CLIARGS['inventory']: @@ -296,35 +296,37 @@ class PullCLI(CLI): return rc - def try_playbook(self, path): + @staticmethod + def try_playbook(path): if not os.path.exists(path): return 1 if not os.access(path, os.R_OK): return 2 return 0 - def select_playbook(self, path): + @staticmethod + def select_playbook(path): playbook = None if context.CLIARGS['args'] and context.CLIARGS['args'][0] is not None: playbook = os.path.join(path, context.CLIARGS['args'][0]) - rc = self.try_playbook(playbook) + rc = PullCLI.try_playbook(playbook) if rc != 0: - display.warning("%s: %s" % (playbook, self.PLAYBOOK_ERRORS[rc])) + display.warning("%s: %s" % (playbook, PullCLI.PLAYBOOK_ERRORS[rc])) return None return playbook else: fqdn = socket.getfqdn() hostpb = os.path.join(path, fqdn + '.yml') shorthostpb = os.path.join(path, fqdn.split('.')[0] + '.yml') - localpb = os.path.join(path, self.DEFAULT_PLAYBOOK) + localpb = os.path.join(path, PullCLI.DEFAULT_PLAYBOOK) errors = [] for pb in [hostpb, shorthostpb, localpb]: - rc = self.try_playbook(pb) + rc = PullCLI.try_playbook(pb) if rc == 0: playbook = pb break else: - errors.append("%s: %s" % (pb, self.PLAYBOOK_ERRORS[rc])) + errors.append("%s: %s" % (pb, PullCLI.PLAYBOOK_ERRORS[rc])) if playbook is None: display.warning("\n".join(errors)) return playbook diff --git a/lib/ansible/cli/vault.py b/lib/ansible/cli/vault.py index 89044809df..9a941dcdd0 100644 --- a/lib/ansible/cli/vault.py +++ b/lib/ansible/cli/vault.py @@ -258,7 +258,8 @@ class VaultCLI(CLI): if sys.stdout.isatty(): display.display("Encryption successful", stderr=True) - def format_ciphertext_yaml(self, b_ciphertext, indent=None, name=None): + @staticmethod + def format_ciphertext_yaml(b_ciphertext, indent=None, name=None): indent = indent or 10 block_format_var_name = ""