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

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
This commit is contained in:
Toshio Kuratomi 2018-12-19 20:45:47 -08:00
parent 7e92ff823e
commit ed8e60d804
9 changed files with 126 additions and 101 deletions

View file

@ -247,7 +247,8 @@ class CLI(with_metaclass(ABCMeta, object)):
return vault_secrets return vault_secrets
def ask_passwords(self): @staticmethod
def ask_passwords():
''' prompt for connection and become passwords if needed ''' ''' prompt for connection and become passwords if needed '''
op = context.CLIARGS op = context.CLIARGS
@ -347,7 +348,7 @@ class CLI(with_metaclass(ABCMeta, object)):
An implementation will look something like this:: An implementation will look something like this::
def init_parser(self): 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) ansible.arguments.optparse_helpers.add_runas_options(self.parser)
self.parser.add_option('--my-option', dest='my_option', action='store') 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], 'minor': ansible_versions[1],
'revision': ansible_versions[2]} 'revision': ansible_versions[2]}
def pager(self, text): @staticmethod
def pager(text):
''' find reasonable way to display text ''' ''' find reasonable way to display text '''
# this is a much simpler form of what is in pydoc.py # this is a much simpler form of what is in pydoc.py
if not sys.stdout.isatty(): if not sys.stdout.isatty():
@ -458,12 +460,12 @@ class CLI(with_metaclass(ABCMeta, object)):
if sys.platform == 'win32': if sys.platform == 'win32':
display.display(text, screen_only=True) display.display(text, screen_only=True)
else: else:
self.pager_pipe(text, os.environ['PAGER']) CLI.pager_pipe(text, os.environ['PAGER'])
else: else:
p = subprocess.Popen('less --version', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) p = subprocess.Popen('less --version', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.communicate() p.communicate()
if p.returncode == 0: if p.returncode == 0:
self.pager_pipe(text, 'less') CLI.pager_pipe(text, 'less')
else: else:
display.display(text, screen_only=True) display.display(text, screen_only=True)

View file

@ -1,5 +1,5 @@
# Copyright: (c) 2012, Michael DeHaan <michael.dehaan@gmail.com> # Copyright: (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
# Copyright: (c) 2018, Toshio Kuratomi <tkuratomi@ansible.com> # Copyright: (c) 2018, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # 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) from __future__ import (absolute_import, division, print_function)

View file

@ -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) # 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) 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] <search term>") self.parser.set_usage("usage: %prog update [options] [-c ansible.cfg] <search term>")
def post_process_args(self, options, args): 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 display.verbosity = options.verbosity
return options, args return options, args

View file

@ -71,6 +71,8 @@ class DocCLI(CLI):
choices=C.DOCUMENTABLE_PLUGINS) choices=C.DOCUMENTABLE_PLUGINS)
def post_process_args(self, options, args): 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: 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.") 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) loader.add_directory(path)
# save only top level paths for errors # 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 loader._paths = None # reset so we can use subdirs below
# list plugins names and filepath for type # list plugins names and filepath for type
if context.CLIARGS['list_files']: if context.CLIARGS['list_files']:
paths = loader._get_paths() paths = loader._get_paths()
for path in 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) list_text = self.get_plugin_list_filenames(loader)
self.pager(list_text) DocCLI.pager(list_text)
return 0 return 0
# list plugins for type # list plugins for type
if context.CLIARGS['list_dir']: if context.CLIARGS['list_dir']:
paths = loader._get_paths() paths = loader._get_paths()
for path in 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 return 0
# dump plugin desc/metadata as JSON # dump plugin desc/metadata as JSON
if context.CLIARGS['json_dump']: if context.CLIARGS['json_dump']:
plugin_data = {} 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: 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: if plugin_info is not None:
plugin_data[plugin_name] = plugin_info 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 return 0
@ -143,26 +145,28 @@ class DocCLI(CLI):
# process command line list # process command line list
text = '' text = ''
for plugin in context.CLIARGS['args']: 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: if textret:
text += textret text += textret
if text: if text:
self.pager(text) DocCLI.pager(text)
return 0 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) loader = getattr(plugin_loader, '%s_loader' % plugin_type)
plugin_list = set() plugin_list = set()
paths = loader._get_paths() paths = loader._get_paths()
for path in 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) plugin_list.update(plugins_to_add)
return sorted(set(plugin_list)) 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 # 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) loader = getattr(plugin_loader, '%s_loader' % plugin_type)
filename = loader.find_plugin(plugin_name, mod_type='.py', ignore_deprecated=True, check_aliases=True) filename = loader.find_plugin(plugin_name, mod_type='.py', ignore_deprecated=True, check_aliases=True)
@ -188,12 +192,13 @@ class DocCLI(CLI):
return dict( return dict(
name=plugin_name, 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"), description=doc.get('short_description', "UNKNOWN"),
version_added=doc.get('version_added', "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('/'): if not basedir.endswith('/'):
basedir += '/' basedir += '/'
rel_path = filepath.replace(basedir, '') rel_path = filepath.replace(basedir, '')
@ -205,7 +210,8 @@ class DocCLI(CLI):
return clean_ns 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 = '' text = ''
try: try:
@ -248,9 +254,9 @@ class DocCLI(CLI):
doc['docuri'] = doc[plugin_type].replace('_', '-') doc['docuri'] = doc[plugin_type].replace('_', '-')
if context.CLIARGS['show_snippet'] and plugin_type == 'module': if context.CLIARGS['show_snippet'] and plugin_type == 'module':
text += self.get_snippet_text(doc) text += DocCLI.get_snippet_text(doc)
else: else:
text += self.get_man_text(doc) text += DocCLI.get_man_text(doc)
return text return text
else: else:
@ -266,7 +272,8 @@ class DocCLI(CLI):
raise AnsibleError( raise AnsibleError(
"%s %s missing documentation (or could not parse documentation): %s\n" % (plugin_type, plugin, to_native(e))) "%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) display.vvvv("Searching %s for plugins" % path)
@ -340,7 +347,7 @@ class DocCLI(CLI):
continue continue
desc = 'UNDOCUMENTED' desc = 'UNDOCUMENTED'
else: 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: if len(desc) > linelimit:
desc = desc[:linelimit] + '...' desc = desc[:linelimit] + '...'
@ -394,10 +401,11 @@ class DocCLI(CLI):
ret.append(i) ret.append(i)
return os.pathsep.join(ret) return os.pathsep.join(ret)
def get_snippet_text(self, doc): @staticmethod
def get_snippet_text(doc):
text = [] text = []
desc = CLI.tty_ify(doc['short_description']) desc = DocCLI.tty_ify(doc['short_description'])
text.append("- name: %s" % (desc)) text.append("- name: %s" % (desc))
text.append(" %s:" % (doc['module'])) text.append(" %s:" % (doc['module']))
pad = 31 pad = 31
@ -407,9 +415,9 @@ class DocCLI(CLI):
for o in sorted(doc['options'].keys()): for o in sorted(doc['options'].keys()):
opt = doc['options'][o] opt = doc['options'][o]
if isinstance(opt['description'], string_types): if isinstance(opt['description'], string_types):
desc = CLI.tty_ify(opt['description']) desc = DocCLI.tty_ify(opt['description'])
else: else:
desc = CLI.tty_ify(" ".join(opt['description'])) desc = DocCLI.tty_ify(" ".join(opt['description']))
required = opt.get('required', False) required = opt.get('required', False)
if not isinstance(required, bool): if not isinstance(required, bool):
@ -422,10 +430,14 @@ class DocCLI(CLI):
return "\n".join(text) return "\n".join(text)
def _dump_yaml(self, struct, indent): @staticmethod
return CLI.tty_ify('\n'.join([indent + line for line in yaml.dump(struct, default_flow_style=False, Dumper=AnsibleDumper).split('\n')])) 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): for o in sorted(fields):
opt = fields[o] opt = fields[o]
@ -442,9 +454,9 @@ class DocCLI(CLI):
if isinstance(opt['description'], list): if isinstance(opt['description'], list):
for entry in opt['description']: 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: 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'] del opt['description']
aliases = '' aliases = ''
@ -461,37 +473,41 @@ class DocCLI(CLI):
if 'default' in opt or not required: if 'default' in opt or not required:
default = "[Default: %s" % str(opt.pop('default', '(null)')) + "]" 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: if 'options' in opt:
text.append("%soptions:\n" % opt_indent) 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: if 'spec' in opt:
text.append("%sspec:\n" % opt_indent) 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 = {} conf = {}
for config in ('env', 'ini', 'yaml', 'vars', 'keywords'): for config in ('env', 'ini', 'yaml', 'vars', 'keywords'):
if config in opt and opt[config]: if config in opt and opt[config]:
conf[config] = opt.pop(config) conf[config] = opt.pop(config)
for ignore in self.IGNORE: for ignore in DocCLI.IGNORE:
for item in conf[config]: for item in conf[config]:
if ignore in item: if ignore in item:
del item[ignore] del item[ignore]
if conf: 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): for k in sorted(opt):
if k.startswith('_'): if k.startswith('_'):
continue continue
if isinstance(opt[k], string_types): 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]): 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: else:
text.append(self._dump_yaml({k: opt[k]}, opt_indent)) text.append(DocCLI._dump_yaml({k: opt[k]}, opt_indent))
text.append('') text.append('')
@staticmethod @staticmethod
@ -519,9 +535,10 @@ class DocCLI(CLI):
text.append("\t%s: %s" % (k.capitalize(), doc['metadata'][k])) text.append("\t%s: %s" % (k.capitalize(), doc['metadata'][k]))
return text 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 = " " opt_indent = " "
text = [] text = []
pad = display.columns * 0.20 pad = display.columns * 0.20
@ -534,7 +551,8 @@ class DocCLI(CLI):
else: else:
desc = doc.pop('description') 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: if 'deprecated' in doc and doc['deprecated'] is not None and len(doc['deprecated']) > 0:
text.append("DEPRECATED: \n") text.append("DEPRECATED: \n")
@ -547,7 +565,7 @@ class DocCLI(CLI):
text.append("\n") text.append("\n")
try: try:
support_block = self.get_support_block(doc) support_block = DocCLI.get_support_block(doc)
if support_block: if support_block:
text.extend(support_block) text.extend(support_block)
except Exception: except Exception:
@ -558,13 +576,14 @@ class DocCLI(CLI):
if 'options' in doc and doc['options']: if 'options' in doc and doc['options']:
text.append("OPTIONS (= is mandatory):\n") 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('') text.append('')
if 'notes' in doc and doc['notes'] and len(doc['notes']) > 0: if 'notes' in doc and doc['notes'] and len(doc['notes']) > 0:
text.append("NOTES:") text.append("NOTES:")
for note in doc['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('')
text.append('') text.append('')
del doc['notes'] del doc['notes']
@ -573,32 +592,32 @@ class DocCLI(CLI):
text.append("SEE ALSO:") text.append("SEE ALSO:")
for item in doc['seealso']: for item in doc['seealso']:
if 'module' in item and 'description' in item: 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)) 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)) 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)) limit - 6, initial_indent=opt_indent + ' ', subsequent_indent=opt_indent))
elif 'module' in item: 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)) 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 + ' ')) 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)) limit - 6, initial_indent=opt_indent + ' ', subsequent_indent=opt_indent))
elif 'name' in item and 'link' in item and 'description' in item: 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)) 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 + ' ')) 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 + ' ')) limit - 6, initial_indent=opt_indent + ' ', subsequent_indent=opt_indent + ' '))
elif 'ref' in item and 'description' in item: 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)) 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 + ' ')) 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 + ' ')) limit - 6, initial_indent=opt_indent + ' ', subsequent_indent=opt_indent + ' '))
text.append('') text.append('')
@ -607,18 +626,18 @@ class DocCLI(CLI):
if 'requirements' in doc and doc['requirements'] is not None and len(doc['requirements']) > 0: if 'requirements' in doc and doc['requirements'] is not None and len(doc['requirements']) > 0:
req = ", ".join(doc.pop('requirements')) 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 # Generic handler
for k in sorted(doc): for k in sorted(doc):
if k in self.IGNORE or not doc[k]: if k in DocCLI.IGNORE or not doc[k]:
continue continue
if isinstance(doc[k], string_types): 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)): elif isinstance(doc[k], (list, tuple)):
text.append('%s: %s' % (k.upper(), ', '.join(doc[k]))) text.append('%s: %s' % (k.upper(), ', '.join(doc[k])))
else: 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] del doc[k]
text.append('') text.append('')
@ -641,7 +660,7 @@ class DocCLI(CLI):
text.append('') text.append('')
try: try:
metadata_block = self.get_metadata_block(doc) metadata_block = DocCLI.get_metadata_block(doc)
if metadata_block: if metadata_block:
text.extend(metadata_block) text.extend(metadata_block)
text.append('') text.append('')

View file

@ -145,7 +145,8 @@ class GalaxyCLI(CLI):
self.api = GalaxyAPI(self.galaxy) self.api = GalaxyAPI(self.galaxy)
self.execute() self.execute()
def exit_without_ignore(self, rc=1): @staticmethod
def exit_without_ignore(rc=1):
""" """
Exits with the specified return code unless the Exits with the specified return code unless the
option --ignore-errors was specified option --ignore-errors was specified
@ -153,20 +154,21 @@ class GalaxyCLI(CLI):
if not context.CLIARGS['ignore_errors']: if not context.CLIARGS['ignore_errors']:
raise AnsibleError('- you can use --ignore-errors to skip failed roles and finish processing the list.') 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 = [u"", u"Role: %s" % to_text(role_info['name'])]
text.append(u"\tdescription: %s" % role_info.get('description', '')) text.append(u"\tdescription: %s" % role_info.get('description', ''))
for k in sorted(role_info.keys()): for k in sorted(role_info.keys()):
if k in self.SKIP_INFO_KEYS: if k in GalaxyCLI.SKIP_INFO_KEYS:
continue continue
if isinstance(role_info[k], dict): if isinstance(role_info[k], dict):
text.append(u"\t%s:" % (k)) text.append(u"\t%s:" % (k))
for key in sorted(role_info[k].keys()): for key in sorted(role_info[k].keys()):
if key in self.SKIP_INFO_KEYS: if key in GalaxyCLI.SKIP_INFO_KEYS:
continue continue
text.append(u"\t\t%s: %s" % (key, role_info[k][key])) text.append(u"\t\t%s: %s" % (key, role_info[k][key]))
else: else:

View file

@ -53,10 +53,7 @@ class InventoryCLI(CLI):
self.loader = None self.loader = None
self.inventory = None self.inventory = None
self._new_api = True
def init_parser(self): def init_parser(self):
super(InventoryCLI, self).init_parser( super(InventoryCLI, self).init_parser(
usage='usage: %prog [options] [host|group]', usage='usage: %prog [options] [host|group]',
epilog='Show Ansible inventory information, by default it uses the inventory script JSON format') 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/") # 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): def post_process_args(self, options, args):
options, args = super(InventoryCLI, self).post_process_args(options, args)
display.verbosity = options.verbosity display.verbosity = options.verbosity
self.validate_conflicts(options, vault_opts=True) self.validate_conflicts(options, vault_opts=True)
@ -152,7 +151,8 @@ class InventoryCLI(CLI):
exit(1) exit(1)
def dump(self, stuff): @staticmethod
def dump(stuff):
if context.CLIARGS['yaml']: if context.CLIARGS['yaml']:
import yaml import yaml
@ -223,41 +223,39 @@ class InventoryCLI(CLI):
for inventory_dir in self.inventory._sources: for inventory_dir in self.inventory._sources:
hostvars = combine_vars(hostvars, self.get_plugin_vars(inventory_dir, host)) hostvars = combine_vars(hostvars, self.get_plugin_vars(inventory_dir, host))
else: else:
if self._new_api: hostvars = self.vm.get_vars(host=host, include_hostvars=False)
hostvars = self.vm.get_vars(host=host, include_hostvars=False)
else:
hostvars = self.vm.get_vars(self.loader, host=host, include_hostvars=False)
return hostvars return hostvars
def _get_group(self, gname): def _get_group(self, gname):
if self._new_api: group = self.inventory.groups.get(gname)
group = self.inventory.groups.get(gname)
else:
group = self.inventory.get_group(gname)
return group return group
def _remove_internal(self, dump): @staticmethod
def _remove_internal(dump):
for internal in INTERNAL_VARS: for internal in INTERNAL_VARS:
if internal in dump: if internal in dump:
del dump[internal] del dump[internal]
def _remove_empty(self, dump): @staticmethod
def _remove_empty(dump):
# remove empty keys # remove empty keys
for x in ('hosts', 'vars', 'children'): for x in ('hosts', 'vars', 'children'):
if x in dump and not dump[x]: if x in dump and not dump[x]:
del dump[x] del dump[x]
def _show_vars(self, dump, depth): @staticmethod
def _show_vars(dump, depth):
result = [] result = []
self._remove_internal(dump) InventoryCLI._remove_internal(dump)
if context.CLIARGS['show_vars']: if context.CLIARGS['show_vars']:
for (name, val) in sorted(dump.items()): 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 return result
def _graph_name(self, name, depth=0): @staticmethod
def _graph_name(name, depth=0):
if depth: if depth:
name = " |" * (depth) + "--%s" % name name = " |" * (depth) + "--%s" % name
return name return name

View file

@ -179,7 +179,8 @@ class PlaybookCLI(CLI):
else: else:
return results return results
def _flush_cache(self, inventory, variable_manager): @staticmethod
def _flush_cache(inventory, variable_manager):
for host in inventory.list_hosts(): for host in inventory.list_hosts():
hostname = host.get_name() hostname = host.get_name()
variable_manager.clear_facts(hostname) variable_manager.clear_facts(hostname)

View file

@ -54,8 +54,8 @@ class PullCLI(CLI):
SKIP_INVENTORY_DEFAULTS = True SKIP_INVENTORY_DEFAULTS = True
def _get_inv_cli(self): @staticmethod
def _get_inv_cli():
inv_opts = '' inv_opts = ''
if context.CLIARGS.get('inventory', False): if context.CLIARGS.get('inventory', False):
for inv in context.CLIARGS['inventory']: for inv in context.CLIARGS['inventory']:
@ -296,35 +296,37 @@ class PullCLI(CLI):
return rc return rc
def try_playbook(self, path): @staticmethod
def try_playbook(path):
if not os.path.exists(path): if not os.path.exists(path):
return 1 return 1
if not os.access(path, os.R_OK): if not os.access(path, os.R_OK):
return 2 return 2
return 0 return 0
def select_playbook(self, path): @staticmethod
def select_playbook(path):
playbook = None playbook = None
if context.CLIARGS['args'] and context.CLIARGS['args'][0] is not None: if context.CLIARGS['args'] and context.CLIARGS['args'][0] is not None:
playbook = os.path.join(path, context.CLIARGS['args'][0]) playbook = os.path.join(path, context.CLIARGS['args'][0])
rc = self.try_playbook(playbook) rc = PullCLI.try_playbook(playbook)
if rc != 0: if rc != 0:
display.warning("%s: %s" % (playbook, self.PLAYBOOK_ERRORS[rc])) display.warning("%s: %s" % (playbook, PullCLI.PLAYBOOK_ERRORS[rc]))
return None return None
return playbook return playbook
else: else:
fqdn = socket.getfqdn() fqdn = socket.getfqdn()
hostpb = os.path.join(path, fqdn + '.yml') hostpb = os.path.join(path, fqdn + '.yml')
shorthostpb = os.path.join(path, fqdn.split('.')[0] + '.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 = [] errors = []
for pb in [hostpb, shorthostpb, localpb]: for pb in [hostpb, shorthostpb, localpb]:
rc = self.try_playbook(pb) rc = PullCLI.try_playbook(pb)
if rc == 0: if rc == 0:
playbook = pb playbook = pb
break break
else: else:
errors.append("%s: %s" % (pb, self.PLAYBOOK_ERRORS[rc])) errors.append("%s: %s" % (pb, PullCLI.PLAYBOOK_ERRORS[rc]))
if playbook is None: if playbook is None:
display.warning("\n".join(errors)) display.warning("\n".join(errors))
return playbook return playbook

View file

@ -258,7 +258,8 @@ class VaultCLI(CLI):
if sys.stdout.isatty(): if sys.stdout.isatty():
display.display("Encryption successful", stderr=True) 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 indent = indent or 10
block_format_var_name = "" block_format_var_name = ""