2008-08-08 16:46:23 -05:00
|
|
|
# Authors:
|
|
|
|
# Jason Gerard DeRose <jderose@redhat.com>
|
|
|
|
#
|
|
|
|
# Copyright (C) 2008 Red Hat
|
|
|
|
# see file 'COPYING' for use and warranty information
|
|
|
|
#
|
2010-12-09 06:59:11 -06:00
|
|
|
# This program is free software; you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License as published by
|
|
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
2008-08-08 16:46:23 -05:00
|
|
|
#
|
|
|
|
# This program is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU General Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU General Public License
|
2010-12-09 06:59:11 -06:00
|
|
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
2008-08-08 16:46:23 -05:00
|
|
|
|
|
|
|
"""
|
2008-09-23 19:01:29 -05:00
|
|
|
Functionality for Command Line Interface.
|
2008-08-08 16:46:23 -05:00
|
|
|
"""
|
2015-08-12 06:44:11 -05:00
|
|
|
from __future__ import print_function
|
2008-08-08 16:46:23 -05:00
|
|
|
|
2018-07-11 09:59:21 -05:00
|
|
|
import atexit
|
2018-09-27 00:47:07 -05:00
|
|
|
import builtins
|
2016-05-12 06:41:09 -05:00
|
|
|
import importlib
|
2017-05-24 08:42:23 -05:00
|
|
|
import logging
|
2008-11-12 01:46:04 -06:00
|
|
|
import textwrap
|
2008-08-11 21:03:47 -05:00
|
|
|
import sys
|
2008-11-18 12:30:16 -06:00
|
|
|
import getpass
|
2008-08-26 19:25:33 -05:00
|
|
|
import code
|
2016-11-23 03:04:43 -06:00
|
|
|
import optparse # pylint: disable=deprecated-module
|
2018-07-11 09:59:21 -05:00
|
|
|
import os
|
|
|
|
import pprint
|
2008-12-16 20:00:39 -06:00
|
|
|
import fcntl
|
|
|
|
import termios
|
|
|
|
import struct
|
2010-02-01 12:59:29 -06:00
|
|
|
import base64
|
2014-05-15 08:42:48 -05:00
|
|
|
import traceback
|
2018-07-11 09:59:21 -05:00
|
|
|
try:
|
|
|
|
import readline
|
|
|
|
import rlcompleter
|
|
|
|
except ImportError:
|
|
|
|
readline = rlcompleter = None
|
|
|
|
|
2015-08-10 11:29:33 -05:00
|
|
|
|
|
|
|
import six
|
2015-08-11 10:07:11 -05:00
|
|
|
from six.moves import input
|
2015-08-10 11:29:33 -05:00
|
|
|
|
2017-10-30 10:09:14 -05:00
|
|
|
from ipalib.util import (
|
2018-12-05 07:54:29 -06:00
|
|
|
check_client_configuration, get_pager, get_terminal_height, open_in_pager
|
2017-10-30 10:09:14 -05:00
|
|
|
)
|
|
|
|
|
2015-09-11 06:43:28 -05:00
|
|
|
if six.PY3:
|
|
|
|
unicode = str
|
|
|
|
|
2016-01-05 01:49:04 -06:00
|
|
|
if six.PY2:
|
2016-11-23 03:04:43 -06:00
|
|
|
reload(sys) # pylint: disable=reload-builtin, undefined-variable
|
|
|
|
sys.setdefaultencoding('utf-8') # pylint: disable=no-member
|
2008-10-17 15:55:03 -05:00
|
|
|
|
2015-07-31 03:15:01 -05:00
|
|
|
from ipalib import frontend
|
|
|
|
from ipalib import backend
|
|
|
|
from ipalib import plugable
|
|
|
|
from ipalib.errors import (PublicError, CommandError, HelpError, InternalError,
|
|
|
|
NoSuchNamespaceError, ValidationError, NotFound,
|
|
|
|
NotConfiguredError, PromptFailed)
|
|
|
|
from ipalib.constants import CLI_TAB, LDAP_GENERALIZED_TIME_FORMAT
|
2018-04-27 05:29:17 -05:00
|
|
|
from ipalib.parameters import File, BinaryFile, Str, Enum, Any, Flag
|
2015-07-31 03:15:01 -05:00
|
|
|
from ipalib.text import _
|
2015-12-16 09:06:03 -06:00
|
|
|
from ipalib import api # pylint: disable=unused-import
|
2014-03-27 09:04:58 -05:00
|
|
|
from ipapython.dnsutil import DNSName
|
2017-08-04 16:25:12 -05:00
|
|
|
from ipapython.admintool import ScriptError
|
2008-09-10 18:33:36 -05:00
|
|
|
|
2014-01-09 04:14:56 -06:00
|
|
|
import datetime
|
|
|
|
|
2017-05-24 08:42:23 -05:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2008-09-10 18:33:36 -05:00
|
|
|
|
2008-08-08 16:46:23 -05:00
|
|
|
def to_cli(name):
|
|
|
|
"""
|
|
|
|
Takes a Python identifier and transforms it into form suitable for the
|
|
|
|
Command Line Interface.
|
|
|
|
"""
|
|
|
|
assert isinstance(name, str)
|
|
|
|
return name.replace('_', '-')
|
|
|
|
|
|
|
|
|
|
|
|
def from_cli(cli_name):
|
|
|
|
"""
|
|
|
|
Takes a string from the Command Line Interface and transforms it into a
|
|
|
|
Python identifier.
|
|
|
|
"""
|
2008-08-13 20:09:11 -05:00
|
|
|
return str(cli_name).replace('-', '_')
|
2008-08-11 14:35:57 -05:00
|
|
|
|
|
|
|
|
2008-11-12 01:46:04 -06:00
|
|
|
class textui(backend.Backend):
|
2008-09-24 00:03:10 -05:00
|
|
|
"""
|
2008-11-12 01:46:04 -06:00
|
|
|
Backend plugin to nicely format output to stdout.
|
2008-09-24 00:03:10 -05:00
|
|
|
"""
|
|
|
|
|
2008-11-12 01:46:04 -06:00
|
|
|
def get_tty_width(self):
|
|
|
|
"""
|
|
|
|
Return the width (in characters) of output tty.
|
|
|
|
|
|
|
|
If stdout is not a tty, this method will return ``None``.
|
|
|
|
"""
|
2008-12-16 20:00:39 -06:00
|
|
|
# /usr/include/asm/termios.h says that struct winsize has four
|
|
|
|
# unsigned shorts, hence the HHHH
|
2008-11-12 01:46:04 -06:00
|
|
|
if sys.stdout.isatty():
|
2008-12-16 20:00:39 -06:00
|
|
|
try:
|
|
|
|
winsize = fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ,
|
|
|
|
struct.pack('HHHH', 0, 0, 0, 0))
|
|
|
|
return struct.unpack('HHHH', winsize)[1]
|
|
|
|
except IOError:
|
2017-12-15 10:00:04 -06:00
|
|
|
pass
|
|
|
|
return None
|
2008-11-12 01:46:04 -06:00
|
|
|
|
|
|
|
def max_col_width(self, rows, col=None):
|
|
|
|
"""
|
|
|
|
Return the max width (in characters) of a specified column.
|
|
|
|
|
|
|
|
For example:
|
|
|
|
|
2015-07-10 04:56:02 -05:00
|
|
|
>>> ui = textui(api)
|
2008-11-12 01:46:04 -06:00
|
|
|
>>> rows = [
|
|
|
|
... ('a', 'package'),
|
|
|
|
... ('an', 'egg'),
|
|
|
|
... ]
|
|
|
|
>>> ui.max_col_width(rows, col=0) # len('an')
|
|
|
|
2
|
|
|
|
>>> ui.max_col_width(rows, col=1) # len('package')
|
|
|
|
7
|
|
|
|
>>> ui.max_col_width(['a', 'cherry', 'py']) # len('cherry')
|
|
|
|
6
|
|
|
|
"""
|
|
|
|
if type(rows) not in (list, tuple):
|
|
|
|
raise TypeError(
|
|
|
|
'rows: need %r or %r; got %r' % (list, tuple, rows)
|
|
|
|
)
|
|
|
|
if len(rows) == 0:
|
|
|
|
return 0
|
|
|
|
if col is None:
|
|
|
|
return max(len(row) for row in rows)
|
|
|
|
return max(len(row[col]) for row in rows)
|
|
|
|
|
2008-11-19 04:31:29 -06:00
|
|
|
def __get_encoding(self, stream):
|
|
|
|
assert stream in (sys.stdin, sys.stdout)
|
2012-03-13 06:10:52 -05:00
|
|
|
if getattr(stream, 'encoding', None) is None:
|
2008-11-19 04:31:29 -06:00
|
|
|
return 'UTF-8'
|
|
|
|
return stream.encoding
|
|
|
|
|
2016-01-26 09:49:23 -06:00
|
|
|
if six.PY2:
|
|
|
|
def decode(self, value):
|
|
|
|
"""
|
|
|
|
Decode text from stdin.
|
|
|
|
"""
|
|
|
|
if type(value) is bytes:
|
|
|
|
encoding = self.__get_encoding(sys.stdin)
|
|
|
|
return value.decode(encoding)
|
|
|
|
elif type(value) in (list, tuple):
|
|
|
|
return tuple(self.decode(v) for v in value)
|
|
|
|
return value
|
|
|
|
|
|
|
|
def encode(self, unicode_text):
|
|
|
|
"""
|
|
|
|
Encode text for output to stdout.
|
|
|
|
"""
|
|
|
|
assert type(unicode_text) is unicode
|
|
|
|
encoding = self.__get_encoding(sys.stdout)
|
|
|
|
return unicode_text.encode(encoding)
|
|
|
|
else:
|
|
|
|
def decode(self, value):
|
|
|
|
return value
|
|
|
|
|
|
|
|
def encode(self, value):
|
|
|
|
return value
|
2008-11-19 04:31:29 -06:00
|
|
|
|
2008-11-14 14:33:42 -06:00
|
|
|
def choose_number(self, n, singular, plural=None):
|
|
|
|
if n == 1 or plural is None:
|
|
|
|
return singular % n
|
|
|
|
return plural % n
|
2008-11-12 01:46:04 -06:00
|
|
|
|
2010-02-01 12:59:29 -06:00
|
|
|
def encode_binary(self, value):
|
|
|
|
"""
|
|
|
|
Convert a binary value to base64. We know a value is binary
|
2016-05-05 09:49:24 -05:00
|
|
|
if it is a python bytes type, otherwise it is a plain string.
|
|
|
|
This function also converts datetime and DNSName values to string.
|
2010-02-01 12:59:29 -06:00
|
|
|
"""
|
2015-09-11 07:02:13 -05:00
|
|
|
if type(value) is bytes:
|
2016-05-05 09:49:24 -05:00
|
|
|
return base64.b64encode(value).decode('ascii')
|
2014-01-09 04:14:56 -06:00
|
|
|
elif type(value) is datetime.datetime:
|
|
|
|
return value.strftime(LDAP_GENERALIZED_TIME_FORMAT)
|
2014-03-27 09:04:58 -05:00
|
|
|
elif isinstance(value, DNSName):
|
|
|
|
return unicode(value)
|
2010-02-01 12:59:29 -06:00
|
|
|
else:
|
|
|
|
return value
|
|
|
|
|
2008-11-14 14:33:42 -06:00
|
|
|
def print_plain(self, string):
|
|
|
|
"""
|
|
|
|
Print exactly like ``print`` statement would.
|
2008-11-12 01:46:04 -06:00
|
|
|
"""
|
2015-08-12 06:44:11 -05:00
|
|
|
print(unicode(string))
|
2008-09-24 00:03:10 -05:00
|
|
|
|
2008-11-12 01:46:04 -06:00
|
|
|
def print_line(self, text, width=None):
|
|
|
|
"""
|
|
|
|
Force printing on a single line, using ellipsis if needed.
|
|
|
|
|
|
|
|
For example:
|
|
|
|
|
2015-07-10 04:56:02 -05:00
|
|
|
>>> ui = textui(api)
|
2008-11-12 01:46:04 -06:00
|
|
|
>>> ui.print_line('This line can fit!', width=18)
|
|
|
|
This line can fit!
|
|
|
|
>>> ui.print_line('This line wont quite fit!', width=18)
|
|
|
|
This line wont ...
|
|
|
|
|
|
|
|
The above example aside, you normally should not specify the
|
|
|
|
``width``. When you don't, it is automatically determined by calling
|
|
|
|
`textui.get_tty_width()`.
|
|
|
|
"""
|
|
|
|
if width is None:
|
|
|
|
width = self.get_tty_width()
|
|
|
|
if width is not None and width < len(text):
|
|
|
|
text = text[:width - 3] + '...'
|
2015-08-12 06:44:11 -05:00
|
|
|
print(unicode(text))
|
2008-11-12 01:46:04 -06:00
|
|
|
|
2008-11-14 14:33:42 -06:00
|
|
|
def print_paragraph(self, text, width=None):
|
|
|
|
"""
|
|
|
|
Print a paragraph, automatically word-wrapping to tty width.
|
|
|
|
|
|
|
|
For example:
|
|
|
|
|
|
|
|
>>> text = '''
|
|
|
|
... Python is a dynamic object-oriented programming language that can
|
|
|
|
... be used for many kinds of software development.
|
|
|
|
... '''
|
2015-07-10 04:56:02 -05:00
|
|
|
>>> ui = textui(api)
|
2008-11-14 14:33:42 -06:00
|
|
|
>>> ui.print_paragraph(text, width=45)
|
|
|
|
Python is a dynamic object-oriented
|
|
|
|
programming language that can be used for
|
|
|
|
many kinds of software development.
|
|
|
|
|
|
|
|
The above example aside, you normally should not specify the
|
|
|
|
``width``. When you don't, it is automatically determined by calling
|
|
|
|
`textui.get_tty_width()`.
|
|
|
|
|
|
|
|
The word-wrapping is done using the Python ``textwrap`` module. See:
|
|
|
|
|
|
|
|
http://docs.python.org/library/textwrap.html
|
|
|
|
"""
|
|
|
|
if width is None:
|
|
|
|
width = self.get_tty_width()
|
|
|
|
for line in textwrap.wrap(text.strip(), width):
|
2015-08-12 06:44:11 -05:00
|
|
|
print(line)
|
2008-11-14 14:33:42 -06:00
|
|
|
|
2008-11-12 01:46:04 -06:00
|
|
|
def print_indented(self, text, indent=1):
|
|
|
|
"""
|
|
|
|
Print at specified indentation level.
|
|
|
|
|
|
|
|
For example:
|
|
|
|
|
2015-07-10 04:56:02 -05:00
|
|
|
>>> ui = textui(api)
|
2008-11-12 01:46:04 -06:00
|
|
|
>>> ui.print_indented('One indentation level.')
|
|
|
|
One indentation level.
|
|
|
|
>>> ui.print_indented('Two indentation levels.', indent=2)
|
|
|
|
Two indentation levels.
|
|
|
|
>>> ui.print_indented('No indentation.', indent=0)
|
|
|
|
No indentation.
|
|
|
|
"""
|
2015-08-12 06:44:11 -05:00
|
|
|
print((CLI_TAB * indent + text))
|
2008-11-12 01:46:04 -06:00
|
|
|
|
|
|
|
def print_keyval(self, rows, indent=1):
|
|
|
|
"""
|
|
|
|
Print (key = value) pairs, one pair per line.
|
|
|
|
|
|
|
|
For example:
|
|
|
|
|
|
|
|
>>> items = [
|
|
|
|
... ('in_server', True),
|
2010-02-12 15:34:21 -06:00
|
|
|
... ('mode', u'production'),
|
2008-11-12 01:46:04 -06:00
|
|
|
... ]
|
2015-07-10 04:56:02 -05:00
|
|
|
>>> ui = textui(api)
|
2008-11-12 01:46:04 -06:00
|
|
|
>>> ui.print_keyval(items)
|
|
|
|
in_server = True
|
2010-02-12 15:34:21 -06:00
|
|
|
mode = u'production'
|
2008-11-12 01:46:04 -06:00
|
|
|
>>> ui.print_keyval(items, indent=0)
|
|
|
|
in_server = True
|
2010-02-12 15:34:21 -06:00
|
|
|
mode = u'production'
|
2008-11-12 01:46:04 -06:00
|
|
|
|
|
|
|
Also see `textui.print_indented`.
|
|
|
|
"""
|
2008-11-14 23:03:31 -06:00
|
|
|
for (key, value) in rows:
|
2010-02-01 12:59:29 -06:00
|
|
|
self.print_indented('%s = %r' % (key, self.encode_binary(value)), indent)
|
2008-11-12 01:46:04 -06:00
|
|
|
|
2010-02-17 08:46:43 -06:00
|
|
|
def print_attribute(self, attr, value, format='%s: %s', indent=1, one_value_per_line=True):
|
2009-04-21 08:20:32 -05:00
|
|
|
"""
|
|
|
|
Print an ldap attribute.
|
|
|
|
|
|
|
|
For example:
|
|
|
|
|
|
|
|
>>> attr = 'dn'
|
2015-07-10 04:56:02 -05:00
|
|
|
>>> ui = textui(api)
|
2009-04-21 08:20:32 -05:00
|
|
|
>>> ui.print_attribute(attr, u'dc=example,dc=com')
|
|
|
|
dn: dc=example,dc=com
|
|
|
|
>>> attr = 'objectClass'
|
2009-08-27 08:55:19 -05:00
|
|
|
>>> ui.print_attribute(attr, [u'top', u'someClass'], one_value_per_line=False)
|
2009-08-04 01:21:26 -05:00
|
|
|
objectClass: top, someClass
|
2009-08-27 08:55:19 -05:00
|
|
|
>>> ui.print_attribute(attr, [u'top', u'someClass'])
|
|
|
|
objectClass: top
|
|
|
|
objectClass: someClass
|
2009-04-21 08:20:32 -05:00
|
|
|
"""
|
2018-09-26 05:24:33 -05:00
|
|
|
assert isinstance(attr, str)
|
2009-04-21 08:20:32 -05:00
|
|
|
if not isinstance(value, (list, tuple)):
|
2009-07-31 10:59:28 -05:00
|
|
|
# single-value attribute
|
2010-02-17 08:46:43 -06:00
|
|
|
self.print_indented(format % (attr, self.encode_binary(value)), indent)
|
2009-07-31 10:59:28 -05:00
|
|
|
else:
|
|
|
|
# multi-value attribute
|
2009-08-25 07:05:40 -05:00
|
|
|
if one_value_per_line:
|
|
|
|
for v in value:
|
2010-02-17 08:46:43 -06:00
|
|
|
self.print_indented(format % (attr, self.encode_binary(v)), indent)
|
2009-08-25 07:05:40 -05:00
|
|
|
else:
|
2015-08-12 05:25:30 -05:00
|
|
|
value = [self.encode_binary(v) for v in value]
|
2010-10-27 11:07:53 -05:00
|
|
|
if len(value) > 0 and type(value[0]) in (list, tuple):
|
|
|
|
# This is where we print failed add/remove members
|
|
|
|
for l in value:
|
|
|
|
text = ': '.join(l)
|
|
|
|
self.print_indented(format % (attr, self.encode_binary(text)), indent)
|
|
|
|
return
|
|
|
|
else:
|
|
|
|
if len(value) > 0:
|
2013-11-26 16:31:05 -06:00
|
|
|
text = ', '.join(str(v) for v in value)
|
2010-10-27 11:07:53 -05:00
|
|
|
else:
|
|
|
|
return
|
2009-08-25 07:05:40 -05:00
|
|
|
line_len = self.get_tty_width()
|
2009-10-22 09:47:22 -05:00
|
|
|
if line_len and text:
|
2009-08-25 07:05:40 -05:00
|
|
|
s_indent = '%s%s' % (
|
|
|
|
CLI_TAB * indent, ' ' * (len(attr) + 2)
|
|
|
|
)
|
|
|
|
line_len -= len(s_indent)
|
|
|
|
text = textwrap.wrap(
|
|
|
|
text, line_len, break_long_words=False
|
|
|
|
)
|
2011-01-21 08:30:23 -06:00
|
|
|
if len(text) == 0:
|
|
|
|
text = [u'']
|
2009-08-25 07:05:40 -05:00
|
|
|
else:
|
2016-06-01 08:26:43 -05:00
|
|
|
s_indent = u''
|
2009-08-25 07:05:40 -05:00
|
|
|
text = [text]
|
2010-02-17 08:46:43 -06:00
|
|
|
self.print_indented(format % (attr, text[0]), indent)
|
2009-08-25 07:05:40 -05:00
|
|
|
for line in text[1:]:
|
|
|
|
self.print_plain('%s%s' % (s_indent, line))
|
|
|
|
|
2010-01-12 09:33:16 -06:00
|
|
|
def print_entry1(self, entry, indent=1, attr_map={}, attr_order=['dn'],
|
2009-08-25 07:05:40 -05:00
|
|
|
one_value_per_line=True):
|
2008-11-17 16:27:08 -06:00
|
|
|
"""
|
|
|
|
Print an ldap entry dict.
|
|
|
|
"""
|
2009-07-31 10:59:28 -05:00
|
|
|
assert isinstance(entry, dict)
|
|
|
|
assert isinstance(attr_map, dict)
|
|
|
|
assert isinstance(attr_order, (list, tuple))
|
|
|
|
|
|
|
|
def print_attr(a):
|
|
|
|
if attr in attr_map:
|
2009-08-25 07:05:40 -05:00
|
|
|
self.print_attribute(
|
2010-02-17 10:53:33 -06:00
|
|
|
attr_map[attr], entry[attr], indent=indent, one_value_per_line=one_value_per_line
|
2009-08-25 07:05:40 -05:00
|
|
|
)
|
2009-07-31 10:59:28 -05:00
|
|
|
else:
|
2009-08-25 07:05:40 -05:00
|
|
|
self.print_attribute(
|
2010-02-17 10:53:33 -06:00
|
|
|
attr, entry[attr], indent=indent, one_value_per_line=one_value_per_line
|
2009-08-25 07:05:40 -05:00
|
|
|
)
|
2009-07-31 10:59:28 -05:00
|
|
|
|
|
|
|
for attr in attr_order:
|
|
|
|
if attr in entry:
|
|
|
|
print_attr(attr)
|
|
|
|
del entry[attr]
|
|
|
|
for attr in sorted(entry):
|
|
|
|
print_attr(attr)
|
2008-11-17 16:27:08 -06:00
|
|
|
|
2011-01-07 10:17:55 -06:00
|
|
|
def print_entries(self, entries, order=None, labels=None, flags=None, print_all=True, format='%s: %s', indent=1):
|
2009-12-09 10:09:53 -06:00
|
|
|
assert isinstance(entries, (list, tuple))
|
|
|
|
first = True
|
|
|
|
for entry in entries:
|
|
|
|
if not first:
|
2015-08-12 06:44:11 -05:00
|
|
|
print('')
|
2009-12-09 10:09:53 -06:00
|
|
|
first = False
|
2011-01-07 10:17:55 -06:00
|
|
|
self.print_entry(entry, order, labels, flags, print_all, format, indent)
|
2009-12-09 10:09:53 -06:00
|
|
|
|
2011-01-07 10:17:55 -06:00
|
|
|
def print_entry(self, entry, order=None, labels=None, flags=None, print_all=True, format='%s: %s', indent=1):
|
2009-12-09 10:09:53 -06:00
|
|
|
if isinstance(entry, (list, tuple)):
|
|
|
|
entry = dict(entry)
|
|
|
|
assert isinstance(entry, dict)
|
2010-02-17 08:46:43 -06:00
|
|
|
if labels is None:
|
|
|
|
labels = dict()
|
|
|
|
one_value_per_line = True
|
2009-12-09 10:09:53 -06:00
|
|
|
else:
|
2010-02-17 08:46:43 -06:00
|
|
|
one_value_per_line = False
|
|
|
|
if order is not None:
|
|
|
|
for key in order:
|
|
|
|
if key not in entry:
|
|
|
|
continue
|
|
|
|
label = labels.get(key, key)
|
2011-01-07 10:17:55 -06:00
|
|
|
flag = flags.get(key, [])
|
2010-02-17 08:46:43 -06:00
|
|
|
value = entry[key]
|
2014-03-27 08:04:00 -05:00
|
|
|
if ('suppress_empty' in flag and
|
|
|
|
value in [u'', '', (), [], None]):
|
2011-01-07 10:17:55 -06:00
|
|
|
continue
|
2010-02-17 08:46:43 -06:00
|
|
|
if isinstance(value, dict):
|
2010-10-27 11:07:53 -05:00
|
|
|
if frontend.entry_count(value) == 0:
|
|
|
|
continue
|
2010-02-17 08:46:43 -06:00
|
|
|
self.print_indented(format % (label, ''), indent)
|
|
|
|
self.print_entry(
|
2011-01-10 13:21:45 -06:00
|
|
|
value, order, labels, flags, print_all, format,
|
2010-02-17 08:46:43 -06:00
|
|
|
indent=indent+1
|
|
|
|
)
|
|
|
|
else:
|
2011-12-21 07:44:58 -06:00
|
|
|
if isinstance(value, (list, tuple)) and \
|
|
|
|
all(isinstance(val, dict) for val in value):
|
|
|
|
# this is a list of entries (dicts), not values
|
|
|
|
self.print_attribute(label, u'', format, indent)
|
|
|
|
self.print_entries(value, order, labels, flags, print_all,
|
|
|
|
format, indent+1)
|
|
|
|
else:
|
|
|
|
self.print_attribute(
|
|
|
|
label, value, format, indent, one_value_per_line
|
|
|
|
)
|
2010-02-17 08:46:43 -06:00
|
|
|
del entry[key]
|
|
|
|
if print_all:
|
|
|
|
for key in sorted(entry):
|
|
|
|
label = labels.get(key, key)
|
|
|
|
self.print_attribute(
|
|
|
|
key, entry[key], format, indent, one_value_per_line
|
|
|
|
)
|
2009-12-09 10:09:53 -06:00
|
|
|
|
2008-11-17 21:41:01 -06:00
|
|
|
def print_dashed(self, string, above=True, below=True, indent=0, dash='-'):
|
2008-11-14 14:33:42 -06:00
|
|
|
"""
|
|
|
|
Print a string with a dashed line above and/or below.
|
|
|
|
|
|
|
|
For example:
|
|
|
|
|
2015-07-10 04:56:02 -05:00
|
|
|
>>> ui = textui(api)
|
2008-11-14 14:33:42 -06:00
|
|
|
>>> ui.print_dashed('Dashed above and below.')
|
|
|
|
-----------------------
|
|
|
|
Dashed above and below.
|
|
|
|
-----------------------
|
|
|
|
>>> ui.print_dashed('Only dashed below.', above=False)
|
|
|
|
Only dashed below.
|
|
|
|
------------------
|
|
|
|
>>> ui.print_dashed('Only dashed above.', below=False)
|
|
|
|
------------------
|
|
|
|
Only dashed above.
|
|
|
|
"""
|
2018-09-26 05:24:33 -05:00
|
|
|
assert isinstance(dash, str)
|
2008-11-17 21:41:01 -06:00
|
|
|
assert len(dash) == 1
|
|
|
|
dashes = dash * len(string)
|
2008-11-14 14:33:42 -06:00
|
|
|
if above:
|
2008-11-17 21:41:01 -06:00
|
|
|
self.print_indented(dashes, indent)
|
|
|
|
self.print_indented(string, indent)
|
2008-11-14 14:33:42 -06:00
|
|
|
if below:
|
2008-11-17 21:41:01 -06:00
|
|
|
self.print_indented(dashes, indent)
|
|
|
|
|
|
|
|
def print_h1(self, text):
|
|
|
|
"""
|
|
|
|
Print a primary header at indentation level 0.
|
|
|
|
|
|
|
|
For example:
|
|
|
|
|
2015-07-10 04:56:02 -05:00
|
|
|
>>> ui = textui(api)
|
2008-11-17 21:41:01 -06:00
|
|
|
>>> ui.print_h1('A primary header')
|
|
|
|
================
|
|
|
|
A primary header
|
|
|
|
================
|
|
|
|
"""
|
|
|
|
self.print_dashed(text, indent=0, dash='=')
|
|
|
|
|
|
|
|
def print_h2(self, text):
|
|
|
|
"""
|
|
|
|
Print a secondary header at indentation level 1.
|
|
|
|
|
|
|
|
For example:
|
|
|
|
|
2015-07-10 04:56:02 -05:00
|
|
|
>>> ui = textui(api)
|
2008-11-17 21:41:01 -06:00
|
|
|
>>> ui.print_h2('A secondary header')
|
|
|
|
------------------
|
|
|
|
A secondary header
|
|
|
|
------------------
|
|
|
|
"""
|
|
|
|
self.print_dashed(text, indent=1, dash='-')
|
2008-11-14 14:33:42 -06:00
|
|
|
|
|
|
|
def print_name(self, name):
|
|
|
|
"""
|
|
|
|
Print a command name.
|
|
|
|
|
|
|
|
The typical use for this is to mark the start of output from a
|
|
|
|
command. For example, a hypothetical ``show_status`` command would
|
|
|
|
output something like this:
|
|
|
|
|
2015-07-10 04:56:02 -05:00
|
|
|
>>> ui = textui(api)
|
2008-11-14 14:33:42 -06:00
|
|
|
>>> ui.print_name('show_status')
|
|
|
|
------------
|
|
|
|
show-status:
|
|
|
|
------------
|
|
|
|
"""
|
|
|
|
self.print_dashed('%s:' % to_cli(name))
|
|
|
|
|
2009-12-09 10:09:53 -06:00
|
|
|
def print_header(self, msg, output):
|
|
|
|
self.print_dashed(msg % output)
|
|
|
|
|
|
|
|
def print_summary(self, msg):
|
|
|
|
"""
|
|
|
|
Print a summary at the end of a comand's output.
|
|
|
|
|
|
|
|
For example:
|
|
|
|
|
2015-07-10 04:56:02 -05:00
|
|
|
>>> ui = textui(api)
|
2009-12-09 10:09:53 -06:00
|
|
|
>>> ui.print_summary('Added user "jdoe"')
|
|
|
|
-----------------
|
|
|
|
Added user "jdoe"
|
|
|
|
-----------------
|
|
|
|
"""
|
|
|
|
self.print_dashed(msg)
|
|
|
|
|
2008-11-12 01:46:04 -06:00
|
|
|
def print_count(self, count, singular, plural=None):
|
|
|
|
"""
|
|
|
|
Print a summary count.
|
|
|
|
|
|
|
|
The typical use for this is to print the number of items returned
|
|
|
|
by a command, especially when this return count can vary. This
|
|
|
|
preferably should be used as a summary and should be the final text
|
|
|
|
a command outputs.
|
|
|
|
|
|
|
|
For example:
|
|
|
|
|
2015-07-10 04:56:02 -05:00
|
|
|
>>> ui = textui(api)
|
2008-11-12 01:46:04 -06:00
|
|
|
>>> ui.print_count(1, '%d goose', '%d geese')
|
|
|
|
-------
|
|
|
|
1 goose
|
|
|
|
-------
|
|
|
|
>>> ui.print_count(['Don', 'Sue'], 'Found %d user', 'Found %d users')
|
|
|
|
-------------
|
|
|
|
Found 2 users
|
|
|
|
-------------
|
|
|
|
|
|
|
|
If ``count`` is not an integer, it must be a list or tuple, and then
|
|
|
|
``len(count)`` is used as the count.
|
|
|
|
"""
|
|
|
|
if type(count) is not int:
|
2009-12-09 10:09:53 -06:00
|
|
|
assert type(count) in (list, tuple, dict)
|
2008-11-12 01:46:04 -06:00
|
|
|
count = len(count)
|
|
|
|
self.print_dashed(
|
|
|
|
self.choose_number(count, singular, plural)
|
|
|
|
)
|
|
|
|
|
2009-01-23 11:33:54 -06:00
|
|
|
def print_error(self, text):
|
2015-08-12 06:44:11 -05:00
|
|
|
print(' ** %s **' % unicode(text))
|
2009-01-23 11:33:54 -06:00
|
|
|
|
2015-08-11 10:07:11 -05:00
|
|
|
def prompt_helper(self, prompt, label, prompt_func=input):
|
2012-02-09 08:09:03 -06:00
|
|
|
"""Prompt user for input
|
|
|
|
|
|
|
|
Handles encoding the prompt and decoding the input.
|
|
|
|
On end of stream or ctrl+c, raise PromptFailed.
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
return self.decode(prompt_func(self.encode(prompt)))
|
|
|
|
except (KeyboardInterrupt, EOFError):
|
2015-08-12 06:44:11 -05:00
|
|
|
print()
|
2012-02-09 08:09:03 -06:00
|
|
|
raise PromptFailed(name=label)
|
|
|
|
|
2012-02-28 08:04:05 -06:00
|
|
|
def print_prompt_attribute_error(self, attribute, error):
|
|
|
|
self.print_plain('>>> %s: %s' % (attribute, error))
|
|
|
|
|
2011-01-24 15:59:52 -06:00
|
|
|
def prompt(self, label, default=None, get_values=None, optional=False):
|
2008-11-14 00:54:34 -06:00
|
|
|
"""
|
|
|
|
Prompt user for input.
|
|
|
|
"""
|
2008-11-19 04:31:29 -06:00
|
|
|
# TODO: Add tab completion using readline
|
2011-01-24 15:59:52 -06:00
|
|
|
if optional:
|
|
|
|
prompt = u'[%s]' % label
|
|
|
|
else:
|
|
|
|
prompt = u'%s' % label
|
2008-11-14 00:54:34 -06:00
|
|
|
if default is None:
|
2011-01-24 15:59:52 -06:00
|
|
|
prompt = u'%s: ' % prompt
|
2008-11-14 00:54:34 -06:00
|
|
|
else:
|
2011-01-24 15:59:52 -06:00
|
|
|
prompt = u'%s [%s]: ' % (prompt, default)
|
2012-02-09 08:09:03 -06:00
|
|
|
return self.prompt_helper(prompt, label)
|
2008-11-14 00:54:34 -06:00
|
|
|
|
2011-05-26 02:55:53 -05:00
|
|
|
def prompt_yesno(self, label, default=None):
|
|
|
|
"""
|
|
|
|
Prompt user for yes/no input. This method returns True/False according
|
|
|
|
to user response.
|
|
|
|
|
|
|
|
Parameter "default" should be True, False or None
|
|
|
|
|
|
|
|
If Default parameter is not None, user can enter an empty input instead
|
|
|
|
of Yes/No answer. Value passed to Default is returned in that case.
|
2011-08-24 17:10:22 -05:00
|
|
|
|
2011-05-26 02:55:53 -05:00
|
|
|
If Default parameter is None, user is asked for Yes/No answer until
|
|
|
|
a correct answer is provided. Answer is then returned.
|
|
|
|
"""
|
|
|
|
|
|
|
|
default_prompt = None
|
|
|
|
if default is not None:
|
|
|
|
if default:
|
|
|
|
default_prompt = "Yes"
|
|
|
|
else:
|
|
|
|
default_prompt = "No"
|
|
|
|
|
|
|
|
if default_prompt:
|
|
|
|
prompt = u'%s Yes/No (default %s): ' % (label, default_prompt)
|
|
|
|
else:
|
|
|
|
prompt = u'%s Yes/No: ' % label
|
|
|
|
|
|
|
|
while True:
|
2012-03-07 11:51:04 -06:00
|
|
|
data = self.prompt_helper(prompt, label).lower() #pylint: disable=E1103
|
2011-05-26 02:55:53 -05:00
|
|
|
|
|
|
|
if data in (u'yes', u'y'):
|
|
|
|
return True
|
|
|
|
elif data in ( u'n', u'no'):
|
|
|
|
return False
|
|
|
|
elif default is not None and data == u'':
|
|
|
|
return default
|
|
|
|
|
2017-12-15 10:00:04 -06:00
|
|
|
return default # pylint consinstent return statements
|
|
|
|
|
2011-08-24 17:10:22 -05:00
|
|
|
def prompt_password(self, label, confirm=True):
|
2008-11-18 12:30:16 -06:00
|
|
|
"""
|
2009-05-26 15:49:13 -05:00
|
|
|
Prompt user for a password or read it in via stdin depending
|
|
|
|
on whether there is a tty or not.
|
2008-11-18 12:30:16 -06:00
|
|
|
"""
|
2012-02-09 08:09:03 -06:00
|
|
|
if sys.stdin.isatty():
|
|
|
|
prompt = u'%s: ' % unicode(label)
|
|
|
|
repeat_prompt = unicode(_('Enter %(label)s again to verify: ') % dict(label=label))
|
|
|
|
while True:
|
|
|
|
pw1 = self.prompt_helper(prompt, label, prompt_func=getpass.getpass)
|
|
|
|
if not confirm:
|
|
|
|
return pw1
|
|
|
|
pw2 = self.prompt_helper(repeat_prompt, label, prompt_func=getpass.getpass)
|
|
|
|
if pw1 == pw2:
|
|
|
|
return pw1
|
2017-12-15 10:00:04 -06:00
|
|
|
else:
|
|
|
|
self.print_error(_('Passwords do not match!'))
|
2012-02-09 08:09:03 -06:00
|
|
|
else:
|
|
|
|
return self.decode(sys.stdin.readline().strip())
|
2008-11-18 12:30:16 -06:00
|
|
|
|
2009-07-10 15:43:47 -05:00
|
|
|
def select_entry(self, entries, format, attrs, display_count=True):
|
|
|
|
"""
|
|
|
|
Display a list of lines in with formatting defined in ``format``.
|
|
|
|
``attrs`` is a list of attributes in the format.
|
|
|
|
|
|
|
|
Prompt user for a selection and return the value (index of
|
|
|
|
``entries`` -1).
|
|
|
|
|
|
|
|
If only one entry is provided then always return 0.
|
|
|
|
|
|
|
|
Return: 0..n for the index of the selected entry
|
|
|
|
-1 if all entries should be displayed
|
|
|
|
-2 to quit, no entries to be displayed
|
|
|
|
"""
|
|
|
|
if not self.env.interactive or not sys.stdout.isatty():
|
|
|
|
return -1
|
|
|
|
|
|
|
|
counter = len(entries)
|
2009-06-09 14:24:23 -05:00
|
|
|
if counter == 0:
|
2012-07-04 07:52:47 -05:00
|
|
|
raise NotFound(reason=_("No matching entries found"))
|
2009-06-09 14:24:23 -05:00
|
|
|
|
2009-07-10 15:43:47 -05:00
|
|
|
i = 1
|
|
|
|
for e in entries:
|
|
|
|
# There is no guarantee that all attrs are in any given
|
|
|
|
# entry
|
|
|
|
d = {}
|
|
|
|
for a in attrs:
|
|
|
|
d[a] = e.get(a, '')
|
|
|
|
self.print_line("%d: %s" % (i, format % d))
|
|
|
|
i = i + 1
|
|
|
|
|
|
|
|
if display_count:
|
|
|
|
self.print_count(entries, 'Found %d match', 'Found %d matches')
|
|
|
|
|
|
|
|
while True:
|
|
|
|
try:
|
|
|
|
resp = self.prompt("Choose one: (1 - %s), a for all, q to quit" % counter)
|
|
|
|
except EOFError:
|
|
|
|
return -2
|
|
|
|
|
2011-04-07 09:53:52 -05:00
|
|
|
if resp.lower() == "q": #pylint: disable=E1103
|
2009-07-10 15:43:47 -05:00
|
|
|
return -2
|
2011-04-07 09:53:52 -05:00
|
|
|
if resp.lower() == "a": #pylint: disable=E1103
|
2009-07-10 15:43:47 -05:00
|
|
|
return -1
|
|
|
|
try:
|
|
|
|
selection = int(resp) - 1
|
2018-07-11 15:30:12 -05:00
|
|
|
if (counter > selection >= 0):
|
2009-07-10 15:43:47 -05:00
|
|
|
break
|
2016-03-11 12:51:07 -06:00
|
|
|
except Exception:
|
2009-07-10 15:43:47 -05:00
|
|
|
# fall through to the error msg
|
|
|
|
pass
|
|
|
|
|
|
|
|
self.print_line("Please enter a number between 1 and %s" % counter)
|
|
|
|
|
|
|
|
self.print_line('')
|
|
|
|
return selection
|
2008-11-12 01:46:04 -06:00
|
|
|
|
2017-10-30 10:09:14 -05:00
|
|
|
|
2010-07-26 16:54:38 -05:00
|
|
|
class help(frontend.Local):
|
2009-01-27 17:28:50 -06:00
|
|
|
"""
|
|
|
|
Display help for a command or topic.
|
|
|
|
"""
|
2018-09-26 04:59:50 -05:00
|
|
|
class Writer:
|
2017-10-30 10:09:14 -05:00
|
|
|
"""
|
|
|
|
Writer abstraction
|
|
|
|
"""
|
|
|
|
def __init__(self, outfile):
|
|
|
|
self.outfile = outfile
|
|
|
|
self.buffer = []
|
|
|
|
|
|
|
|
@property
|
|
|
|
def buffer_length(self):
|
|
|
|
length = 0
|
|
|
|
for line in self.buffer:
|
|
|
|
length += len(line.split("\n"))
|
|
|
|
return length
|
|
|
|
|
|
|
|
def append(self, string=u""):
|
|
|
|
self.buffer.append(unicode(string))
|
|
|
|
|
|
|
|
def write(self):
|
2018-12-05 07:54:29 -06:00
|
|
|
pager = get_pager()
|
|
|
|
|
|
|
|
if pager and self.buffer_length > get_terminal_height():
|
2017-10-30 10:09:14 -05:00
|
|
|
data = "\n".join(self.buffer).encode("utf-8")
|
2018-12-05 07:54:29 -06:00
|
|
|
open_in_pager(data, pager)
|
2017-10-30 10:09:14 -05:00
|
|
|
else:
|
|
|
|
try:
|
|
|
|
for line in self.buffer:
|
|
|
|
print(line, file=self.outfile)
|
|
|
|
except IOError:
|
|
|
|
pass
|
2008-09-08 20:41:15 -05:00
|
|
|
|
2012-11-08 07:57:39 -06:00
|
|
|
takes_args = (
|
|
|
|
Str('command?', cli_name='topic', label=_('Topic or Command'),
|
|
|
|
doc=_('The topic or command name.')),
|
|
|
|
)
|
2012-11-06 10:45:50 -06:00
|
|
|
takes_options = (
|
|
|
|
Any('outfile?', flags=['no_option']),
|
|
|
|
)
|
2008-09-08 20:41:15 -05:00
|
|
|
|
2009-12-09 10:09:53 -06:00
|
|
|
has_output = tuple()
|
|
|
|
|
2016-05-12 06:41:09 -05:00
|
|
|
topic = None
|
2009-08-04 03:41:11 -05:00
|
|
|
|
2016-05-12 06:41:09 -05:00
|
|
|
def _get_topic(self, topic):
|
2016-05-16 07:15:19 -05:00
|
|
|
doc = u''
|
|
|
|
parent_topic = None
|
2010-12-20 08:42:04 -06:00
|
|
|
|
2016-05-16 07:15:19 -05:00
|
|
|
for package in self.api.packages:
|
2017-10-30 10:09:14 -05:00
|
|
|
module_name = '{0}.{1}'.format(package.__name__, topic)
|
2016-05-16 07:15:19 -05:00
|
|
|
try:
|
|
|
|
module = sys.modules[module_name]
|
|
|
|
except KeyError:
|
|
|
|
try:
|
|
|
|
module = importlib.import_module(module_name)
|
|
|
|
except ImportError:
|
|
|
|
continue
|
|
|
|
|
|
|
|
if module.__doc__ is not None:
|
|
|
|
doc = unicode(module.__doc__ or '').strip()
|
|
|
|
try:
|
|
|
|
parent_topic = module.topic
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
2010-12-20 08:42:04 -06:00
|
|
|
|
2016-05-12 06:41:09 -05:00
|
|
|
return doc, parent_topic
|
2010-12-20 08:42:04 -06:00
|
|
|
|
|
|
|
def _count_topic_mcl(self, topic_name, mod_name):
|
|
|
|
mcl = max((self._topics[topic_name][1], len(mod_name)))
|
|
|
|
self._topics[topic_name][1] = mcl
|
|
|
|
|
2011-11-03 05:42:17 -05:00
|
|
|
def _on_finalize(self):
|
2017-10-30 10:09:14 -05:00
|
|
|
# {topic: ["description", mcl, {
|
|
|
|
# "subtopic": ["description", mcl, [commands]]}]}
|
2010-12-20 08:42:04 -06:00
|
|
|
# {topic: ["description", mcl, [commands]]}
|
2009-04-27 09:41:49 -05:00
|
|
|
self._topics = {}
|
|
|
|
# [builtin_commands]
|
|
|
|
self._builtins = []
|
|
|
|
|
|
|
|
# build help topics
|
2016-07-20 06:24:03 -05:00
|
|
|
for c in self.api.Command:
|
|
|
|
if c is not self.api.Command.get_plugin(c.name):
|
2016-06-21 05:07:21 -05:00
|
|
|
continue
|
2011-01-20 14:07:43 -06:00
|
|
|
if c.NO_CLI:
|
2010-03-16 09:06:07 -05:00
|
|
|
continue
|
2010-12-20 08:42:04 -06:00
|
|
|
|
2016-05-12 06:41:09 -05:00
|
|
|
if c.topic is not None:
|
|
|
|
doc, topic_name = self._get_topic(c.topic)
|
|
|
|
doc = doc.split('\n', 1)[0]
|
|
|
|
if topic_name is None: # a module without grouping
|
|
|
|
topic_name = c.topic
|
2010-12-20 08:42:04 -06:00
|
|
|
if topic_name in self._topics:
|
|
|
|
self._topics[topic_name][2].append(c)
|
|
|
|
else:
|
|
|
|
self._topics[topic_name] = [doc, 0, [c]]
|
|
|
|
mcl = max((self._topics[topic_name][1], len(c.name)))
|
|
|
|
self._topics[topic_name][1] = mcl
|
2017-10-30 10:09:14 -05:00
|
|
|
else: # a module grouped in a topic
|
2016-05-30 23:36:55 -05:00
|
|
|
topic = self._get_topic(topic_name)
|
2016-05-12 06:41:09 -05:00
|
|
|
mod_name = c.topic
|
2010-12-20 08:42:04 -06:00
|
|
|
if topic_name in self._topics:
|
|
|
|
if mod_name in self._topics[topic_name][2]:
|
|
|
|
self._topics[topic_name][2][mod_name][2].append(c)
|
|
|
|
else:
|
2017-10-30 10:09:14 -05:00
|
|
|
self._topics[topic_name][2][mod_name] = [
|
|
|
|
doc, 0, [c]]
|
2010-12-20 08:42:04 -06:00
|
|
|
self._count_topic_mcl(topic_name, mod_name)
|
|
|
|
# count mcl for for the subtopic
|
2017-10-30 10:09:14 -05:00
|
|
|
mcl = max((
|
|
|
|
self._topics[topic_name][2][mod_name][1],
|
|
|
|
len(c.name)))
|
2010-12-20 08:42:04 -06:00
|
|
|
self._topics[topic_name][2][mod_name][1] = mcl
|
|
|
|
else:
|
2017-10-30 10:09:14 -05:00
|
|
|
self._topics[topic_name] = [
|
|
|
|
topic[0].split('\n', 1)[0],
|
|
|
|
0,
|
|
|
|
{mod_name: [doc, 0, [c]]}]
|
2010-12-20 08:42:04 -06:00
|
|
|
self._count_topic_mcl(topic_name, mod_name)
|
2009-04-27 09:41:49 -05:00
|
|
|
else:
|
|
|
|
self._builtins.append(c)
|
|
|
|
|
|
|
|
# compute maximum topic length
|
Use Python3-compatible dict method names
Python 2 has keys()/values()/items(), which return lists,
iterkeys()/itervalues()/iteritems(), which return iterators,
and viewkeys()/viewvalues()/viewitems() which return views.
Python 3 has only keys()/values()/items(), which return views.
To get iterators, one can use iter() or a for loop/comprehension;
for lists there's the list() constructor.
When iterating through the entire dict, without modifying the dict,
the difference between Python 2's items() and iteritems() is
negligible, especially on small dicts (the main overhead is
extra memory, not CPU time). In the interest of simpler code,
this patch changes many instances of iteritems() to items(),
iterkeys() to keys() etc.
In other cases, helpers like six.itervalues are used.
Reviewed-By: Christian Heimes <cheimes@redhat.com>
Reviewed-By: Jan Cholasta <jcholast@redhat.com>
2015-08-11 06:51:14 -05:00
|
|
|
topics = list(self._topics) + [c.name for c in self._builtins]
|
|
|
|
self._mtl = max(len(s) for s in topics)
|
2009-04-27 09:41:49 -05:00
|
|
|
|
2011-11-03 05:42:17 -05:00
|
|
|
super(help, self)._on_finalize()
|
2009-01-27 17:28:50 -06:00
|
|
|
|
2016-05-30 01:12:32 -05:00
|
|
|
def run(self, key=None, outfile=None, **options):
|
2012-11-06 10:45:50 -06:00
|
|
|
if outfile is None:
|
|
|
|
outfile = sys.stdout
|
2017-10-30 10:09:14 -05:00
|
|
|
|
|
|
|
writer = self.Writer(outfile)
|
2009-06-12 12:26:15 -05:00
|
|
|
name = from_cli(key)
|
2017-10-30 10:09:14 -05:00
|
|
|
|
2012-11-06 10:45:50 -06:00
|
|
|
if key is None:
|
2012-11-08 07:00:51 -06:00
|
|
|
self.api.parser.print_help(outfile)
|
2012-11-06 10:45:50 -06:00
|
|
|
return
|
|
|
|
if name == "topics":
|
|
|
|
self.print_topics(outfile)
|
2008-11-12 11:15:24 -06:00
|
|
|
return
|
2009-04-27 09:41:49 -05:00
|
|
|
if name in self._topics:
|
2012-11-06 10:45:50 -06:00
|
|
|
self.print_commands(name, outfile)
|
2009-04-27 09:41:49 -05:00
|
|
|
elif name in self.Command:
|
|
|
|
cmd = self.Command[name]
|
2011-10-18 12:32:36 -05:00
|
|
|
if cmd.NO_CLI:
|
|
|
|
raise HelpError(topic=name)
|
2012-11-08 07:00:51 -06:00
|
|
|
self.Backend.cli.build_parser(cmd).print_help(outfile)
|
2016-05-16 07:15:19 -05:00
|
|
|
elif any(name in t[2] for t in self._topics.values()
|
|
|
|
if type(t[2]) is dict):
|
2012-11-06 10:45:50 -06:00
|
|
|
self.print_commands(name, outfile)
|
2009-06-12 12:26:15 -05:00
|
|
|
elif name == "commands":
|
2016-06-20 00:41:08 -05:00
|
|
|
mcl = 0
|
2016-07-20 06:24:03 -05:00
|
|
|
for cmd_plugin in self.Command:
|
|
|
|
if cmd_plugin is not self.Command.get_plugin(cmd_plugin.name):
|
2016-06-21 05:07:21 -05:00
|
|
|
continue
|
2016-07-20 06:24:03 -05:00
|
|
|
if cmd_plugin.NO_CLI:
|
2010-11-10 15:51:00 -06:00
|
|
|
continue
|
2016-07-20 06:24:03 -05:00
|
|
|
mcl = max(mcl, len(cmd_plugin.name))
|
2017-10-30 10:09:14 -05:00
|
|
|
writer.append('{0} {1}'.format(
|
|
|
|
to_cli(cmd_plugin.name).ljust(mcl), cmd_plugin.summary))
|
2009-04-27 09:41:49 -05:00
|
|
|
else:
|
|
|
|
raise HelpError(topic=name)
|
2017-10-30 10:09:14 -05:00
|
|
|
writer.write()
|
2012-11-06 10:45:50 -06:00
|
|
|
|
|
|
|
def print_topics(self, outfile):
|
2017-10-30 10:09:14 -05:00
|
|
|
writer = self.Writer(outfile)
|
2012-11-08 07:10:54 -06:00
|
|
|
|
|
|
|
for t, topic in sorted(self._topics.items()):
|
2017-10-30 10:09:14 -05:00
|
|
|
writer.append('{0} {1}'.format(
|
|
|
|
to_cli(t).ljust(self._mtl), topic[0]))
|
|
|
|
writer.write()
|
2008-11-12 11:15:24 -06:00
|
|
|
|
2012-11-06 10:45:50 -06:00
|
|
|
def print_commands(self, topic, outfile):
|
2017-10-30 10:09:14 -05:00
|
|
|
writer = self.Writer(outfile)
|
|
|
|
|
2010-12-20 08:42:04 -06:00
|
|
|
if topic in self._topics and type(self._topics[topic][2]) is dict:
|
|
|
|
# we want to display topic which has subtopics
|
|
|
|
for subtopic in self._topics[topic][2]:
|
|
|
|
doc = self._topics[topic][2][subtopic][0]
|
|
|
|
mcl = self._topics[topic][1]
|
2017-10-30 10:09:14 -05:00
|
|
|
writer.append(' {0} {1}'.format(
|
|
|
|
to_cli(subtopic).ljust(mcl), doc))
|
2010-12-20 08:42:04 -06:00
|
|
|
else:
|
|
|
|
# we want to display subtopic or a topic which has no subtopics
|
|
|
|
if topic in self._topics:
|
|
|
|
mcl = self._topics[topic][1]
|
|
|
|
commands = self._topics[topic][2]
|
|
|
|
else:
|
2011-02-02 11:47:34 -06:00
|
|
|
commands = []
|
2010-12-20 08:42:04 -06:00
|
|
|
for t in self._topics:
|
|
|
|
if type(self._topics[t][2]) is not dict:
|
|
|
|
continue
|
|
|
|
if topic not in self._topics[t][2]:
|
|
|
|
continue
|
|
|
|
mcl = self._topics[t][2][topic][1]
|
|
|
|
commands = self._topics[t][2][topic][2]
|
|
|
|
break
|
2011-01-10 13:21:45 -06:00
|
|
|
|
2016-05-16 07:15:19 -05:00
|
|
|
doc, _topic = self._get_topic(topic)
|
2009-04-27 09:41:49 -05:00
|
|
|
|
2011-10-18 12:32:36 -05:00
|
|
|
if topic not in self.Command and len(commands) == 0:
|
|
|
|
raise HelpError(topic=topic)
|
|
|
|
|
2017-10-30 10:09:14 -05:00
|
|
|
writer.append(doc)
|
2012-02-03 02:38:16 -06:00
|
|
|
if commands:
|
2017-10-30 10:09:14 -05:00
|
|
|
writer.append()
|
|
|
|
writer.append(_('Topic commands:'))
|
2010-12-20 08:42:04 -06:00
|
|
|
for c in commands:
|
2017-10-30 10:09:14 -05:00
|
|
|
writer.append(
|
|
|
|
' {0} {1}'.format(
|
|
|
|
to_cli(c.name).ljust(mcl), c.summary))
|
|
|
|
writer.append()
|
|
|
|
writer.append(_('To get command help, use:'))
|
|
|
|
writer.append(_(' ipa <command> --help'))
|
|
|
|
writer.append()
|
|
|
|
writer.write()
|
|
|
|
|
2008-11-12 11:15:24 -06:00
|
|
|
|
2011-01-26 06:09:26 -06:00
|
|
|
class show_mappings(frontend.Command):
|
2011-10-18 12:32:36 -05:00
|
|
|
"""
|
|
|
|
Show mapping of LDAP attributes to command-line option.
|
|
|
|
"""
|
2011-01-26 06:09:26 -06:00
|
|
|
takes_args = (
|
|
|
|
Str('command_name',
|
|
|
|
label=_('Command name'),
|
|
|
|
),
|
|
|
|
)
|
|
|
|
has_output = tuple()
|
|
|
|
|
2016-05-12 06:41:09 -05:00
|
|
|
topic = None
|
|
|
|
|
2013-03-18 06:57:00 -05:00
|
|
|
def run(self, command_name, **options):
|
2011-01-26 06:09:26 -06:00
|
|
|
command_name = from_cli(command_name)
|
|
|
|
if command_name not in self.Command:
|
|
|
|
raise CommandError(name=command_name)
|
|
|
|
params = self.Command[command_name].options
|
|
|
|
out = [('Parameter','LDAP attribute'),
|
|
|
|
('=========','==============')]
|
|
|
|
mcl = len(out[0][0])
|
|
|
|
for param in params():
|
|
|
|
if param.exclude and 'webui' in param.exclude:
|
|
|
|
continue
|
|
|
|
out.append((param.cli_name, param.param_spec))
|
|
|
|
mcl = max(mcl,len(param.cli_name))
|
|
|
|
for item in out:
|
2015-08-12 06:44:11 -05:00
|
|
|
print(to_cli(item[0]).ljust(mcl)+' : '+item[1])
|
2011-01-26 06:09:26 -06:00
|
|
|
|
2008-10-27 15:48:02 -05:00
|
|
|
|
2020-06-30 02:58:33 -05:00
|
|
|
class IPACompleter(rlcompleter.Completer):
|
|
|
|
def _callable_postfix(self, val, word):
|
|
|
|
# Don't add '(' postfix for callable API objects
|
|
|
|
if isinstance(val, (plugable.APINameSpace, plugable.API)):
|
|
|
|
return word
|
|
|
|
return super()._callable_postfix(val, word)
|
|
|
|
|
|
|
|
|
2009-10-13 23:23:19 -05:00
|
|
|
class console(frontend.Command):
|
2014-05-15 08:42:48 -05:00
|
|
|
"""Start the IPA interactive Python console, or run a script.
|
2008-08-26 19:25:33 -05:00
|
|
|
|
2014-05-15 08:42:48 -05:00
|
|
|
An IPA API object is initialized and made available
|
|
|
|
in the `api` global variable.
|
|
|
|
"""
|
|
|
|
|
|
|
|
takes_args = ('filename?',)
|
2009-12-09 10:09:53 -06:00
|
|
|
has_output = tuple()
|
|
|
|
|
2016-05-12 06:41:09 -05:00
|
|
|
topic = None
|
|
|
|
|
2018-07-11 09:59:21 -05:00
|
|
|
def _setup_tab_completion(self, local):
|
|
|
|
readline.parse_and_bind("tab: complete")
|
|
|
|
# completer with custom locals
|
2020-06-30 02:58:33 -05:00
|
|
|
readline.set_completer(IPACompleter(local).complete)
|
2018-07-11 09:59:21 -05:00
|
|
|
# load history
|
|
|
|
history = os.path.join(api.env.dot_ipa, "console.history")
|
|
|
|
try:
|
|
|
|
readline.read_history_file(history)
|
|
|
|
except OSError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
def save_history():
|
|
|
|
directory = os.path.dirname(history)
|
|
|
|
if not os.path.isdir(directory):
|
|
|
|
os.makedirs(directory)
|
|
|
|
readline.set_history_length(50)
|
|
|
|
try:
|
|
|
|
readline.write_history_file(history)
|
|
|
|
except OSError:
|
|
|
|
logger.exception("Unable to store history %s", history)
|
|
|
|
|
|
|
|
atexit.register(save_history)
|
|
|
|
|
2014-05-15 08:42:48 -05:00
|
|
|
def run(self, filename=None, **options):
|
2018-07-11 09:59:21 -05:00
|
|
|
local = dict(
|
|
|
|
api=self.api,
|
|
|
|
pp=pprint.pprint, # just too convenient
|
|
|
|
__builtins__=builtins,
|
|
|
|
)
|
2014-05-15 08:42:48 -05:00
|
|
|
if filename:
|
|
|
|
try:
|
2018-07-12 07:50:40 -05:00
|
|
|
with open(filename) as f:
|
|
|
|
source = f.read()
|
2014-05-15 08:42:48 -05:00
|
|
|
except IOError as e:
|
2018-01-03 03:08:50 -06:00
|
|
|
sys.exit("%s: %s" % (e.filename, e.strerror))
|
2014-05-15 08:42:48 -05:00
|
|
|
try:
|
2018-07-12 07:50:40 -05:00
|
|
|
compiled = compile(
|
|
|
|
source,
|
|
|
|
filename,
|
|
|
|
'exec',
|
|
|
|
flags=print_function.compiler_flag
|
|
|
|
)
|
|
|
|
exec(compiled, globals(), local)
|
2016-03-11 12:51:07 -06:00
|
|
|
except Exception:
|
2014-05-15 08:42:48 -05:00
|
|
|
traceback.print_exc()
|
2018-01-03 03:08:50 -06:00
|
|
|
sys.exit(1)
|
2014-05-15 08:42:48 -05:00
|
|
|
else:
|
2018-07-11 09:59:21 -05:00
|
|
|
if readline is not None:
|
|
|
|
self._setup_tab_completion(local)
|
2014-05-15 08:42:48 -05:00
|
|
|
code.interact(
|
2018-07-11 09:59:21 -05:00
|
|
|
"\n".join((
|
|
|
|
"(Custom IPA interactive Python console)",
|
|
|
|
" api: IPA API object",
|
|
|
|
" pp: pretty printer",
|
|
|
|
)),
|
2014-05-15 08:42:48 -05:00
|
|
|
local=local
|
|
|
|
)
|
2008-08-26 19:25:33 -05:00
|
|
|
|
2008-09-23 22:10:35 -05:00
|
|
|
|
2009-10-13 23:23:19 -05:00
|
|
|
class show_api(frontend.Command):
|
2008-09-24 00:35:40 -05:00
|
|
|
'Show attributes on dynamic API object'
|
|
|
|
|
|
|
|
takes_args = ('namespaces*',)
|
|
|
|
|
2016-05-12 06:41:09 -05:00
|
|
|
topic = None
|
|
|
|
|
2016-05-30 01:12:32 -05:00
|
|
|
def run(self, namespaces=None):
|
2008-09-24 00:35:40 -05:00
|
|
|
if namespaces is None:
|
|
|
|
names = tuple(self.api)
|
|
|
|
else:
|
|
|
|
for name in namespaces:
|
|
|
|
if name not in self.api:
|
2009-04-20 12:58:26 -05:00
|
|
|
raise NoSuchNamespaceError(name=name)
|
2008-09-24 00:35:40 -05:00
|
|
|
names = namespaces
|
|
|
|
lines = self.__traverse(names)
|
2008-09-08 16:37:02 -05:00
|
|
|
ml = max(len(l[1]) for l in lines)
|
2008-12-17 18:21:25 -06:00
|
|
|
self.Backend.textui.print_name('run')
|
2008-09-24 00:35:40 -05:00
|
|
|
first = True
|
2008-09-08 16:37:02 -05:00
|
|
|
for line in lines:
|
2008-09-24 00:35:40 -05:00
|
|
|
if line[0] == 0 and not first:
|
2015-08-12 06:44:11 -05:00
|
|
|
print('')
|
2008-09-24 00:35:40 -05:00
|
|
|
if first:
|
|
|
|
first = False
|
2015-08-12 06:44:11 -05:00
|
|
|
print('%s%s %r' % (
|
2008-09-08 16:37:02 -05:00
|
|
|
' ' * line[0],
|
|
|
|
line[1].ljust(ml),
|
|
|
|
line[2],
|
2015-08-12 06:44:11 -05:00
|
|
|
))
|
2008-09-24 00:35:40 -05:00
|
|
|
if len(lines) == 1:
|
|
|
|
s = '1 attribute shown.'
|
|
|
|
else:
|
|
|
|
s = '%d attributes show.' % len(lines)
|
2008-12-17 18:21:25 -06:00
|
|
|
self.Backend.textui.print_dashed(s)
|
2008-09-24 00:35:40 -05:00
|
|
|
|
|
|
|
def __traverse(self, names):
|
2008-09-08 16:37:02 -05:00
|
|
|
lines = []
|
2008-09-24 00:35:40 -05:00
|
|
|
for name in names:
|
2008-09-08 16:37:02 -05:00
|
|
|
namespace = self.api[name]
|
2008-09-24 00:35:40 -05:00
|
|
|
self.__traverse_namespace('%s' % name, namespace, lines)
|
2008-09-08 16:37:02 -05:00
|
|
|
return lines
|
|
|
|
|
|
|
|
def __traverse_namespace(self, name, namespace, lines, tab=0):
|
|
|
|
lines.append((tab, name, namespace))
|
|
|
|
for member_name in namespace:
|
|
|
|
member = namespace[member_name]
|
|
|
|
lines.append((tab + 1, member_name, member))
|
|
|
|
if not hasattr(member, '__iter__'):
|
|
|
|
continue
|
|
|
|
for n in member:
|
|
|
|
attr = member[n]
|
2016-06-08 07:38:23 -05:00
|
|
|
if isinstance(attr, plugable.APINameSpace) and len(attr) > 0:
|
2008-09-08 16:37:02 -05:00
|
|
|
self.__traverse_namespace(n, attr, lines, tab + 2)
|
|
|
|
|
2008-08-26 19:25:33 -05:00
|
|
|
|
2008-09-23 23:44:52 -05:00
|
|
|
cli_application_commands = (
|
|
|
|
help,
|
|
|
|
console,
|
2008-09-24 00:35:40 -05:00
|
|
|
show_api,
|
2008-09-23 23:44:52 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
|
2018-09-26 04:59:50 -05:00
|
|
|
class Collector:
|
2009-01-28 14:05:26 -06:00
|
|
|
def __init__(self):
|
2009-01-27 17:28:50 -06:00
|
|
|
object.__setattr__(self, '_Collector__options', {})
|
2008-09-04 01:33:57 -05:00
|
|
|
|
|
|
|
def __setattr__(self, name, value):
|
2009-01-28 14:05:26 -06:00
|
|
|
if name in self.__options:
|
|
|
|
v = self.__options[name]
|
|
|
|
if type(v) is tuple:
|
|
|
|
value = v + (value,)
|
|
|
|
else:
|
|
|
|
value = (v, value)
|
2017-08-22 07:06:22 -05:00
|
|
|
# pylint: disable=unsupported-assignment-operation
|
2009-01-28 14:05:26 -06:00
|
|
|
self.__options[name] = value
|
2017-08-22 07:06:22 -05:00
|
|
|
# pylint: enable=unsupported-assignment-operation
|
2008-09-04 01:33:57 -05:00
|
|
|
object.__setattr__(self, name, value)
|
|
|
|
|
|
|
|
def __todict__(self):
|
2009-01-27 17:28:50 -06:00
|
|
|
return dict(self.__options)
|
2008-09-04 01:33:57 -05:00
|
|
|
|
2012-01-27 09:51:37 -06:00
|
|
|
class CLIOptionParserFormatter(optparse.IndentedHelpFormatter):
|
|
|
|
def format_argument(self, name, help_string):
|
|
|
|
result = []
|
|
|
|
opt_width = self.help_position - self.current_indent - 2
|
|
|
|
if len(name) > opt_width:
|
|
|
|
name = "%*s%s\n" % (self.current_indent, "", name)
|
|
|
|
indent_first = self.help_position
|
|
|
|
else: # start help on same line as name
|
|
|
|
name = "%*s%-*s " % (self.current_indent, "", opt_width, name)
|
|
|
|
indent_first = 0
|
|
|
|
result.append(name)
|
|
|
|
if help_string:
|
|
|
|
help_lines = textwrap.wrap(help_string, self.help_width)
|
|
|
|
result.append("%*s%s\n" % (indent_first, "", help_lines[0]))
|
|
|
|
result.extend(["%*s%s\n" % (self.help_position, "", line)
|
|
|
|
for line in help_lines[1:]])
|
|
|
|
elif name[-1] != "\n":
|
|
|
|
result.append("\n")
|
|
|
|
return "".join(result)
|
|
|
|
|
|
|
|
class CLIOptionParser(optparse.OptionParser):
|
|
|
|
"""
|
|
|
|
This OptionParser subclass adds an ability to print positional
|
|
|
|
arguments in CLI help. Custom formatter is used to format the argument
|
|
|
|
list in the same way as OptionParser formats options.
|
|
|
|
"""
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
self._arguments = []
|
|
|
|
if 'formatter' not in kwargs:
|
|
|
|
kwargs['formatter'] = CLIOptionParserFormatter()
|
|
|
|
optparse.OptionParser.__init__(self, *args, **kwargs)
|
|
|
|
|
|
|
|
def format_option_help(self, formatter=None):
|
|
|
|
"""
|
|
|
|
Prepend argument help to standard OptionParser's option help
|
|
|
|
"""
|
|
|
|
option_help = optparse.OptionParser.format_option_help(self, formatter)
|
|
|
|
|
|
|
|
if isinstance(formatter, CLIOptionParserFormatter):
|
|
|
|
heading = unicode(_("Positional arguments"))
|
|
|
|
arguments = [formatter.format_heading(heading)]
|
|
|
|
formatter.indent()
|
|
|
|
for (name, help_string) in self._arguments:
|
|
|
|
arguments.append(formatter.format_argument(name, help_string))
|
|
|
|
formatter.dedent()
|
|
|
|
if len(arguments) > 1:
|
|
|
|
# there is more than just the heading
|
|
|
|
arguments.append(u"\n")
|
|
|
|
else:
|
|
|
|
arguments = []
|
|
|
|
option_help = "".join(arguments) + option_help
|
|
|
|
return option_help
|
|
|
|
|
|
|
|
def add_argument(self, name, help_string):
|
|
|
|
self._arguments.append((name, help_string))
|
2008-09-04 01:33:57 -05:00
|
|
|
|
2009-01-28 14:05:26 -06:00
|
|
|
class cli(backend.Executioner):
|
2008-10-27 20:21:49 -05:00
|
|
|
"""
|
2009-01-28 14:05:26 -06:00
|
|
|
Backend plugin for executing from command line interface.
|
2008-10-27 20:21:49 -05:00
|
|
|
"""
|
|
|
|
|
2012-03-13 06:10:52 -05:00
|
|
|
def get_command(self, argv):
|
|
|
|
"""Given CLI arguments, return the Command to use
|
|
|
|
|
|
|
|
On incorrect invocation, prints out a help message and returns None
|
|
|
|
"""
|
2009-01-28 14:05:26 -06:00
|
|
|
if len(argv) == 0:
|
2012-11-08 07:00:51 -06:00
|
|
|
self.Command.help(outfile=sys.stderr)
|
2015-08-12 06:44:11 -05:00
|
|
|
print(file=sys.stderr)
|
|
|
|
print('Error: Command not specified', file=sys.stderr)
|
2018-01-03 03:08:50 -06:00
|
|
|
sys.exit(2)
|
2009-01-28 14:05:26 -06:00
|
|
|
(key, argv) = (argv[0], argv[1:])
|
2009-01-28 17:12:49 -06:00
|
|
|
name = from_cli(key)
|
2011-05-13 07:36:19 -05:00
|
|
|
if name not in self.Command and len(argv) == 0:
|
|
|
|
try:
|
2012-11-06 10:45:50 -06:00
|
|
|
self.Command.help(unicode(key), outfile=sys.stderr)
|
2011-05-13 07:36:19 -05:00
|
|
|
except HelpError:
|
|
|
|
pass
|
2011-01-20 14:07:43 -06:00
|
|
|
if name not in self.Command or self.Command[name].NO_CLI:
|
2009-01-28 17:12:49 -06:00
|
|
|
raise CommandError(name=key)
|
|
|
|
cmd = self.Command[name]
|
2012-03-13 06:10:52 -05:00
|
|
|
return cmd
|
|
|
|
|
2013-02-22 06:25:03 -06:00
|
|
|
def process_keyword_arguments(self, cmd, kw):
|
2012-03-13 06:10:52 -05:00
|
|
|
"""Get the keyword arguments for a Command"""
|
2009-01-28 14:05:26 -06:00
|
|
|
if self.env.interactive:
|
2008-11-18 14:43:43 -06:00
|
|
|
self.prompt_interactively(cmd, kw)
|
2013-01-09 11:09:10 -06:00
|
|
|
try:
|
|
|
|
callbacks = cmd.get_callbacks('interactive_prompt')
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
for callback in callbacks:
|
|
|
|
callback(cmd, kw)
|
2009-11-05 09:15:47 -06:00
|
|
|
self.load_files(cmd, kw)
|
2012-03-13 06:10:52 -05:00
|
|
|
return kw
|
|
|
|
|
|
|
|
def run(self, argv):
|
|
|
|
cmd = self.get_command(argv)
|
|
|
|
if cmd is None:
|
2017-12-15 10:00:04 -06:00
|
|
|
return None
|
2016-09-05 03:18:13 -05:00
|
|
|
name = cmd.full_name
|
2013-02-22 06:25:03 -06:00
|
|
|
kw = self.parse(cmd, argv[1:])
|
2012-03-13 06:10:52 -05:00
|
|
|
if not isinstance(cmd, frontend.Local):
|
|
|
|
self.create_context()
|
2009-07-10 15:43:47 -05:00
|
|
|
try:
|
2013-02-22 06:25:03 -06:00
|
|
|
kw = self.process_keyword_arguments(cmd, kw)
|
2009-07-10 15:43:47 -05:00
|
|
|
result = self.execute(name, **kw)
|
|
|
|
if callable(cmd.output_for_cli):
|
|
|
|
for param in cmd.params():
|
|
|
|
if param.password and param.name in kw:
|
|
|
|
del kw[param.name]
|
|
|
|
(args, options) = cmd.params_2_args_options(**kw)
|
2009-06-09 14:24:23 -05:00
|
|
|
rv = cmd.output_for_cli(self.api.Backend.textui, result, *args, **options)
|
|
|
|
if rv:
|
|
|
|
return rv
|
|
|
|
else:
|
|
|
|
return 0
|
2009-07-10 15:43:47 -05:00
|
|
|
finally:
|
|
|
|
self.destroy_context()
|
2017-12-15 10:00:04 -06:00
|
|
|
return None
|
2008-09-04 02:18:26 -05:00
|
|
|
|
2009-01-28 14:05:26 -06:00
|
|
|
def parse(self, cmd, argv):
|
2008-09-04 01:33:57 -05:00
|
|
|
parser = self.build_parser(cmd)
|
2009-01-28 14:05:26 -06:00
|
|
|
(collector, args) = parser.parse_args(argv, Collector())
|
|
|
|
options = collector.__todict__()
|
2009-01-22 18:03:48 -06:00
|
|
|
kw = cmd.args_options_2_params(*args, **options)
|
2009-01-23 11:33:54 -06:00
|
|
|
return dict(self.parse_iter(cmd, kw))
|
2009-01-22 18:03:48 -06:00
|
|
|
|
2009-01-28 14:05:26 -06:00
|
|
|
# FIXME: Probably move decoding to Command, use same method regardless of
|
|
|
|
# request source:
|
2009-01-23 11:33:54 -06:00
|
|
|
def parse_iter(self, cmd, kw):
|
|
|
|
"""
|
|
|
|
Decode param values if appropriate.
|
|
|
|
"""
|
Use Python3-compatible dict method names
Python 2 has keys()/values()/items(), which return lists,
iterkeys()/itervalues()/iteritems(), which return iterators,
and viewkeys()/viewvalues()/viewitems() which return views.
Python 3 has only keys()/values()/items(), which return views.
To get iterators, one can use iter() or a for loop/comprehension;
for lists there's the list() constructor.
When iterating through the entire dict, without modifying the dict,
the difference between Python 2's items() and iteritems() is
negligible, especially on small dicts (the main overhead is
extra memory, not CPU time). In the interest of simpler code,
this patch changes many instances of iteritems() to items(),
iterkeys() to keys() etc.
In other cases, helpers like six.itervalues are used.
Reviewed-By: Christian Heimes <cheimes@redhat.com>
Reviewed-By: Jan Cholasta <jcholast@redhat.com>
2015-08-11 06:51:14 -05:00
|
|
|
for (key, value) in kw.items():
|
2012-01-23 08:50:41 -06:00
|
|
|
yield (key, self.Backend.textui.decode(value))
|
2008-09-04 01:33:57 -05:00
|
|
|
|
|
|
|
def build_parser(self, cmd):
|
2012-01-27 09:51:37 -06:00
|
|
|
parser = CLIOptionParser(
|
2012-11-08 07:56:52 -06:00
|
|
|
usage=' '.join(self.usage_iter(cmd)),
|
2013-04-03 03:40:30 -05:00
|
|
|
description=unicode(cmd.doc),
|
|
|
|
formatter=IPAHelpFormatter(),
|
2008-09-04 01:33:57 -05:00
|
|
|
)
|
2014-03-18 04:11:19 -05:00
|
|
|
|
2011-12-21 07:44:58 -06:00
|
|
|
option_groups = {}
|
2014-03-18 04:11:19 -05:00
|
|
|
|
|
|
|
def _get_option_group(group_name):
|
|
|
|
"""Get or create an option group for the given name"""
|
|
|
|
option_group = option_groups.get(group_name)
|
|
|
|
if option_group is None:
|
|
|
|
option_group = optparse.OptionGroup(parser, group_name)
|
|
|
|
parser.add_option_group(option_group)
|
|
|
|
option_groups[group_name] = option_group
|
|
|
|
return option_group
|
|
|
|
|
2008-09-10 10:31:34 -05:00
|
|
|
for option in cmd.options():
|
2008-11-18 12:30:16 -06:00
|
|
|
kw = dict(
|
2008-10-13 21:31:10 -05:00
|
|
|
dest=option.name,
|
2010-03-04 17:41:51 -06:00
|
|
|
help=unicode(option.doc),
|
2008-09-04 01:33:57 -05:00
|
|
|
)
|
2011-01-13 13:29:16 -06:00
|
|
|
if 'no_option' in option.flags:
|
|
|
|
continue
|
2009-01-28 14:05:26 -06:00
|
|
|
if option.password and self.env.interactive:
|
2008-11-18 12:30:16 -06:00
|
|
|
kw['action'] = 'store_true'
|
2015-05-07 05:41:12 -05:00
|
|
|
elif isinstance(option, Flag):
|
2008-11-17 19:50:30 -06:00
|
|
|
if option.default is True:
|
2008-11-18 12:30:16 -06:00
|
|
|
kw['action'] = 'store_false'
|
2008-11-17 19:50:30 -06:00
|
|
|
else:
|
2008-11-18 12:30:16 -06:00
|
|
|
kw['action'] = 'store_true'
|
|
|
|
else:
|
2016-05-30 03:36:48 -05:00
|
|
|
kw['metavar'] = option.cli_metavar
|
2011-10-04 07:17:58 -05:00
|
|
|
|
2014-03-18 04:11:19 -05:00
|
|
|
cli_name = to_cli(option.cli_name)
|
|
|
|
option_names = ['--%s' % cli_name]
|
2009-06-10 14:07:24 -05:00
|
|
|
if option.cli_short_name:
|
2014-03-18 04:11:19 -05:00
|
|
|
option_names.append('-%s' % option.cli_short_name)
|
|
|
|
opt = optparse.make_option(*option_names, **kw)
|
|
|
|
if option.option_group is None:
|
|
|
|
parser.add_option(opt)
|
2011-12-21 07:44:58 -06:00
|
|
|
else:
|
2014-03-18 04:11:19 -05:00
|
|
|
_get_option_group(option.option_group).add_option(opt)
|
|
|
|
|
|
|
|
if option.deprecated_cli_aliases:
|
|
|
|
new_kw = dict(kw)
|
|
|
|
new_kw['help'] = _('Same as --%s') % cli_name
|
|
|
|
if isinstance(option, Enum):
|
|
|
|
new_kw['metavar'] = 'VAL'
|
|
|
|
group = _get_option_group(unicode(_('Deprecated options')))
|
|
|
|
for alias in option.deprecated_cli_aliases:
|
|
|
|
name = '--%s' % alias
|
|
|
|
group.add_option(optparse.make_option(name, **new_kw))
|
2012-01-27 09:51:37 -06:00
|
|
|
|
|
|
|
for arg in cmd.args():
|
|
|
|
name = self.__get_arg_name(arg, format_name=False)
|
2012-11-06 10:45:50 -06:00
|
|
|
if 'no_option' in arg.flags or name is None:
|
2012-01-27 09:51:37 -06:00
|
|
|
continue
|
|
|
|
doc = unicode(arg.doc)
|
|
|
|
parser.add_argument(name, doc)
|
|
|
|
|
2008-09-04 01:33:57 -05:00
|
|
|
return parser
|
|
|
|
|
2012-01-27 09:51:37 -06:00
|
|
|
def __get_arg_name(self, arg, format_name=True):
|
|
|
|
if arg.password:
|
2017-12-15 10:00:04 -06:00
|
|
|
return None
|
2012-01-27 09:51:37 -06:00
|
|
|
|
|
|
|
name = to_cli(arg.cli_name).upper()
|
|
|
|
if not format_name:
|
|
|
|
return name
|
|
|
|
if arg.multivalue:
|
|
|
|
name = '%s...' % name
|
|
|
|
if arg.required:
|
|
|
|
return name
|
|
|
|
else:
|
|
|
|
return '[%s]' % name
|
|
|
|
|
2009-01-28 14:05:26 -06:00
|
|
|
def usage_iter(self, cmd):
|
2008-10-03 15:13:50 -05:00
|
|
|
yield 'Usage: %%prog [global-options] %s' % to_cli(cmd.name)
|
2008-09-09 21:02:26 -05:00
|
|
|
for arg in cmd.args():
|
2012-01-27 09:51:37 -06:00
|
|
|
name = self.__get_arg_name(arg)
|
|
|
|
if name is None:
|
2008-11-18 14:43:43 -06:00
|
|
|
continue
|
2012-01-27 09:51:37 -06:00
|
|
|
yield name
|
2011-01-21 09:26:37 -06:00
|
|
|
yield '[options]'
|
2008-09-08 20:41:15 -05:00
|
|
|
|
2009-01-28 14:05:26 -06:00
|
|
|
def prompt_interactively(self, cmd, kw):
|
2009-01-27 17:28:50 -06:00
|
|
|
"""
|
|
|
|
Interactively prompt for missing or invalid values.
|
|
|
|
|
|
|
|
By default this method will only prompt for *required* Param that
|
|
|
|
have a missing or invalid value. However, if
|
2009-01-28 14:05:26 -06:00
|
|
|
``self.env.prompt_all`` is ``True``, this method will prompt for any
|
|
|
|
params that have a missing values, even if the param is optional.
|
2009-01-27 17:28:50 -06:00
|
|
|
"""
|
2013-05-09 08:36:41 -05:00
|
|
|
|
2010-12-08 16:24:26 -06:00
|
|
|
honor_alwaysask = True
|
|
|
|
for param in cmd.params():
|
|
|
|
if param.alwaysask and param.name in kw:
|
|
|
|
honor_alwaysask = False
|
|
|
|
break
|
2013-05-09 08:36:41 -05:00
|
|
|
|
2010-12-02 15:19:00 -06:00
|
|
|
for param in cmd.params():
|
|
|
|
if (param.required and param.name not in kw) or \
|
2010-12-08 16:24:26 -06:00
|
|
|
(param.alwaysask and honor_alwaysask) or self.env.prompt_all:
|
2011-09-16 14:08:17 -05:00
|
|
|
if param.autofill:
|
2012-01-16 08:21:50 -06:00
|
|
|
kw[param.name] = cmd.get_default_of(param.name, **kw)
|
2011-09-16 14:08:17 -05:00
|
|
|
if param.name in kw and kw[param.name] is not None:
|
2016-04-06 08:26:48 -05:00
|
|
|
if param.autofill:
|
|
|
|
del kw[param.name]
|
2011-09-16 14:08:17 -05:00
|
|
|
continue
|
2010-11-24 07:01:31 -06:00
|
|
|
if param.password:
|
|
|
|
kw[param.name] = self.Backend.textui.prompt_password(
|
2011-08-24 17:10:22 -05:00
|
|
|
param.label, param.confirm
|
2010-11-24 07:01:31 -06:00
|
|
|
)
|
|
|
|
else:
|
2012-01-16 08:21:50 -06:00
|
|
|
default = cmd.get_default_of(param.name, **kw)
|
2013-05-09 08:36:41 -05:00
|
|
|
optional = param.alwaysask or not param.required
|
|
|
|
|
|
|
|
value = cmd.prompt_param(param,
|
|
|
|
default=default,
|
|
|
|
optional=optional,
|
|
|
|
kw=kw)
|
|
|
|
|
|
|
|
if value is not None:
|
|
|
|
kw[param.name] = value
|
|
|
|
|
2010-11-24 07:01:31 -06:00
|
|
|
elif param.password and kw.get(param.name, False) is True:
|
|
|
|
kw[param.name] = self.Backend.textui.prompt_password(
|
2011-08-24 17:10:22 -05:00
|
|
|
param.label, param.confirm
|
2010-11-24 07:01:31 -06:00
|
|
|
)
|
2009-01-27 17:28:50 -06:00
|
|
|
|
2009-11-05 09:15:47 -06:00
|
|
|
def load_files(self, cmd, kw):
|
|
|
|
"""
|
|
|
|
Load files from File parameters.
|
|
|
|
|
|
|
|
This has to be done after all required parameters have been read
|
|
|
|
(i.e. after prompt_interactively has or would have been called)
|
|
|
|
AND before they are passed to the command. This is because:
|
|
|
|
1) we need to be sure no more files are going to be added
|
|
|
|
2) we load files from the machine where the command was executed
|
|
|
|
3) the webUI will use a different way of loading files
|
|
|
|
"""
|
|
|
|
for p in cmd.params():
|
2018-04-27 05:29:17 -05:00
|
|
|
if isinstance(p, (File, BinaryFile)):
|
2011-02-01 13:24:46 -06:00
|
|
|
# FIXME: this only reads the first file
|
|
|
|
raw = None
|
2009-11-05 09:15:47 -06:00
|
|
|
if p.name in kw:
|
2011-02-01 13:24:46 -06:00
|
|
|
if type(kw[p.name]) in (tuple, list):
|
|
|
|
fname = kw[p.name][0]
|
|
|
|
else:
|
|
|
|
fname = kw[p.name]
|
2009-11-05 09:15:47 -06:00
|
|
|
try:
|
2018-04-27 05:29:17 -05:00
|
|
|
with open(fname, p.open_mode) as f:
|
|
|
|
raw = f.read()
|
2015-07-30 09:49:29 -05:00
|
|
|
except IOError as e:
|
2009-11-05 09:15:47 -06:00
|
|
|
raise ValidationError(
|
|
|
|
name=to_cli(p.cli_name),
|
2016-01-05 06:36:15 -06:00
|
|
|
error='%s: %s:' % (fname, e.args[1])
|
2009-11-05 09:15:47 -06:00
|
|
|
)
|
|
|
|
elif p.stdin_if_missing:
|
|
|
|
try:
|
2018-04-27 05:29:17 -05:00
|
|
|
if six.PY3 and p.type is bytes:
|
|
|
|
# pylint: disable=no-member
|
|
|
|
raw = sys.stdin.buffer.read()
|
|
|
|
# pylint: enable=no-member
|
|
|
|
else:
|
|
|
|
raw = sys.stdin.read()
|
2015-07-30 09:49:29 -05:00
|
|
|
except IOError as e:
|
2009-11-12 16:34:19 -06:00
|
|
|
raise ValidationError(
|
2016-01-05 06:36:15 -06:00
|
|
|
name=to_cli(p.cli_name), error=e.args[1]
|
2009-11-05 09:15:47 -06:00
|
|
|
)
|
2013-10-21 02:45:21 -05:00
|
|
|
|
|
|
|
if raw:
|
2018-04-27 05:29:17 -05:00
|
|
|
if p.type is bytes:
|
|
|
|
kw[p.name] = raw
|
|
|
|
else:
|
|
|
|
kw[p.name] = self.Backend.textui.decode(raw)
|
2013-10-21 02:45:21 -05:00
|
|
|
elif p.required:
|
|
|
|
raise ValidationError(
|
|
|
|
name=to_cli(p.cli_name), error=_('No file to read')
|
|
|
|
)
|
2009-11-05 09:15:47 -06:00
|
|
|
|
2009-01-27 17:28:50 -06:00
|
|
|
|
2013-04-03 03:40:30 -05:00
|
|
|
class IPAHelpFormatter(optparse.IndentedHelpFormatter):
|
|
|
|
"""Formatter suitable for printing IPA command help
|
|
|
|
|
|
|
|
The default help formatter reflows text to fit the terminal, but it
|
|
|
|
ignores line/paragraph breaks.
|
|
|
|
IPA's descriptions already have correct line breaks. This formatter
|
|
|
|
doesn't touch them (save for removing initial/trailing whitespace).
|
|
|
|
"""
|
|
|
|
def format_description(self, description):
|
|
|
|
if description:
|
|
|
|
return description.strip()
|
|
|
|
else:
|
|
|
|
return ""
|
|
|
|
|
|
|
|
|
2009-01-27 17:28:50 -06:00
|
|
|
cli_plugins = (
|
|
|
|
cli,
|
|
|
|
textui,
|
2009-01-28 14:05:26 -06:00
|
|
|
console,
|
2009-01-27 17:28:50 -06:00
|
|
|
help,
|
2011-01-26 06:09:26 -06:00
|
|
|
show_mappings,
|
2009-01-27 17:28:50 -06:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
def run(api):
|
2009-01-28 14:05:26 -06:00
|
|
|
error = None
|
2009-01-27 17:28:50 -06:00
|
|
|
try:
|
2016-09-26 07:08:17 -05:00
|
|
|
(_options, argv) = api.bootstrap_with_global_options(context='cli')
|
2017-08-04 16:25:12 -05:00
|
|
|
|
|
|
|
try:
|
2019-01-08 01:54:07 -06:00
|
|
|
check_client_configuration(env=api.env)
|
2017-08-04 16:25:12 -05:00
|
|
|
except ScriptError as e:
|
|
|
|
sys.exit(e)
|
|
|
|
|
2009-01-27 17:28:50 -06:00
|
|
|
for klass in cli_plugins:
|
2015-06-22 05:16:34 -05:00
|
|
|
api.add_plugin(klass)
|
2009-01-27 17:28:50 -06:00
|
|
|
api.finalize()
|
2020-04-30 08:12:34 -05:00
|
|
|
if 'config_loaded' not in api.env and 'help' not in argv:
|
2010-10-15 14:03:51 -05:00
|
|
|
raise NotConfiguredError()
|
2009-06-09 14:24:23 -05:00
|
|
|
sys.exit(api.Backend.cli.run(argv))
|
2009-01-27 17:28:50 -06:00
|
|
|
except KeyboardInterrupt:
|
2015-08-12 06:44:11 -05:00
|
|
|
print('')
|
2017-05-24 08:42:23 -05:00
|
|
|
logger.info('operation aborted')
|
2015-07-30 09:49:29 -05:00
|
|
|
except PublicError as e:
|
2009-01-27 17:28:50 -06:00
|
|
|
error = e
|
2015-08-24 05:40:33 -05:00
|
|
|
except Exception as e:
|
2017-05-24 08:42:23 -05:00
|
|
|
logger.exception('%s: %s', e.__class__.__name__, str(e))
|
2009-01-27 17:28:50 -06:00
|
|
|
error = InternalError()
|
2009-01-28 14:05:26 -06:00
|
|
|
if error is not None:
|
|
|
|
assert isinstance(error, PublicError)
|
2017-05-24 08:42:23 -05:00
|
|
|
logger.error(error.strerror)
|
2009-06-09 14:24:23 -05:00
|
|
|
sys.exit(error.rval)
|