Greatly refactored help formatting by moving it from optparse to a higher level.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parent 5ffa7c8 · Browse files · 4 files·+256 added−313 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+256 added−313 removed
- other:+256 added−313 removed
Provenance
- Commit
981172f- Tree
6a7ae80- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
5ffa7c8
4 files changed+256 added−313 removed
modified:click/_optparse.py+7 added-263 removed
4 unmodified lines5 6 This module is largely a copy paste from the stdlib's optparse module7 with the features removed that we do not need from optparse because8 we implement them in click on a higher level (for instance type9- handling and some other things).9+ handling, help formatting and a lot more).10 11 The plan is to remove more and more from here over time.12 13 The reason this is a different module and not optparse from the stdlib1 unmodified line15 generated and optparse in the stdlib uses gettext for no good reason16 and might cause us issues.17 """18 import sys19-import textwrap19 21-from .helpers import get_terminal_size22-from .formatting import TextWrapper20 from .exceptions import UsageError21 22 26-class HelpFormatter(object):27-28- def __init__(self, indent_increment, max_help_position, width,29- short_first):30- self.parser = None31- self.indent_increment = indent_increment32- if width is None:33- width = min(get_terminal_size()[0], 80) - 234- self.width = width35- self.help_position = self.max_help_position = \36- min(max_help_position, max(width - 20, indent_increment * 2))37- self.current_indent = 038- self.level = 039- self.help_width = None40- self.short_first = short_first41- self.option_strings = {}42- self._short_opt_fmt = '%s %s'43- self._long_opt_fmt = '%s=%s'44-45- def set_parser(self, parser):46- self.parser = parser47-48- def indent(self):49- self.current_indent += self.indent_increment50- self.level += 151-52- def dedent(self):53- self.current_indent -= self.indent_increment54- assert self.current_indent >= 0, 'Indent decreased below 0.'55- self.level -= 156-57- def format_usage(self, usage):58- raise NotImplementedError('subclasses must implement')59-60- def format_heading(self, heading):61- raise NotImplementedError('subclasses must implement')62-63- def _format_text(self, text):64- """65- Format a paragraph of free-form text for inclusion in the66- help output at the current indentation level.67- """68- text_width = max(self.width - self.current_indent, 11)69- indent = ' ' * self.current_indent70- return textwrap.fill(text,71- text_width,72- initial_indent=indent,73- subsequent_indent=indent)74-75- def format_description(self, description):76- if description:77- return self._format_text(description) + '\n'78- else:79- return ''80-81- def format_epilog(self, epilog):82- if epilog:83- return '\n' + self._format_text(epilog) + '\n'84- else:85- return ''86-87- def format_option(self, option):88- result = []89- opts = self.option_strings[option]90- opt_width = self.help_position - self.current_indent - 291- if len(opts) > opt_width:92- opts = '%*s%s\n' % (self.current_indent, '', opts)93- indent_first = self.help_position94- else: # start help on same line as opts95- opts = '%*s%-*s ' % (self.current_indent, '', opt_width, opts)96- indent_first = 097- result.append(opts)98- if option.help:99- help_text = option.help100- help_lines = textwrap.wrap(help_text, self.help_width)101- result.append('%*s%s\n' % (indent_first, '', help_lines[0]))102- result.extend(['%*s%s\n' % (self.help_position, '', line)103- for line in help_lines[1:]])104- elif opts[-1] != '\n':105- result.append('\n')106- return ''.join(result)107-108- def store_option_strings(self, parser):109- self.indent()110- max_len = 0111- for opt in parser.option_list:112- strings = self.format_option_strings(opt)113- self.option_strings[opt] = strings114- max_len = max(max_len, len(strings) + self.current_indent)115- self.dedent()116- self.help_position = min(max_len + 2, self.max_help_position)117- self.help_width = max(self.width - self.help_position, 11)118-119- def format_option_strings(self, option):120- if option.takes_value:121- metavar = option.metavar or option.dest.upper()122- short_opts = [self._short_opt_fmt % (sopt, metavar)123- for sopt in option._short_opts]124- long_opts = [self._long_opt_fmt % (lopt, metavar)125- for lopt in option._long_opts]126- else:127- short_opts = option._short_opts128- long_opts = option._long_opts129-130- if self.short_first:131- opts = short_opts + long_opts132- else:133- opts = long_opts + short_opts134-135- return ', '.join(opts)136-137-138-class IndentedHelpFormatter(HelpFormatter):139- """Format help with indented section bodies.140- """141-142- def __init__(self, indent_increment=2, max_help_position=24,143- width=None, short_first=1):144- HelpFormatter.__init__(145- self, indent_increment, max_help_position, width, short_first)146-147- def format_usage(self, usage):148- return 'Usage: %s\n' % usage149-150- def format_heading(self, heading):151- return '%*s%s:\n' % (self.current_indent, '', heading)152-153-23 class Option(object):24 ATTRS = ['action', 'type', 'dest', 'nargs', 'const', 'help',25 'metavar']26 ACTIONS = ('store', 'store_const', 'append', 'append_const')62 unmodified lines89 else:90 raise ValueError('unknown action %r' % self.action)91 92 224-SUPPRESS_HELP = object()225-226-93 class OptionContainer(object):94 229- def __init__(self, option_class, description):95+ def __init__(self, option_class):96 # Initialize the option list and related data structures.97 # This method must be provided by subclasses, and it must98 # initialize at least the following instance attributes:99 # option_list, _short_opt, _long_opt.100 self._create_option_list()101 102 self.option_class = option_class237- self.description = description103 104 def _create_option_mappings(self):105 # For use by OptionParser constructor -- create the master106 # option mappings used by this OptionParser and all44 unmodified lines151 for opt in option._long_opts:152 del self._long_opt[opt]153 option.container.option_list.remove(option)154 290- def format_option_help(self, formatter):291- if not self.option_list:292- return ''293- result = []294- for option in self.option_list:295- if not option.help is SUPPRESS_HELP:296- result.append(formatter.format_option(option))297- return ''.join(result)155 299- def format_description(self, formatter):300- return formatter.format_description(self.description)301-302- def format_help(self, formatter):303- result = []304- if self.description:305- result.append(self.format_description(formatter))306- if self.option_list:307- result.append(self.format_option_help(formatter))308- return '\n'.join(result)309-310-156 class OptionParser(OptionContainer):312- standard_option_list = []157 314- def __init__(self,315- usage=None,316- option_list=None,317- option_class=Option,318- description=None,319- formatter=None,320- epilog=None):321- OptionContainer.__init__(322- self, option_class, description)323- self.usage = usage158+ def __init__(self, option_list=None, option_class=Option):159+ OptionContainer.__init__(self, option_class)160 self.allow_interspersed_args = True325- if formatter is None:326- formatter = IndentedHelpFormatter()327- self.formatter = formatter328- self.formatter.set_parser(self)329- self.epilog = epilog330-331- self._populate_option_list(option_list)332-161+ if option_list:162+ self.add_options(option_list)163 self._init_parsing_state()164 165 def _create_option_list(self):166 self.option_list = []167 self._create_option_mappings()168 339- def _populate_option_list(self, option_list):340- if self.standard_option_list:341- self.add_options(self.standard_option_list)342- if option_list:343- self.add_options(option_list)344-169 def _init_parsing_state(self):170 self.rargs = None171 self.largs = None172 self.values = None157 unmodified lines330 331 def error(self, msg):332 raise Exception(msg)333 510- def get_usage(self):511- if self.usage:512- return self.formatter.format_usage(self.usage)513- return ''334 515- def format_option_help(self, formatter=None):516- if formatter is None:517- formatter = self.formatter518- formatter.store_option_strings(self)519- result = []520- result.append(formatter.format_heading('Options'))521- formatter.indent()522- if self.option_list:523- result.append(OptionContainer.format_option_help(self, formatter))524- result.append('\n')525- formatter.dedent()526- # Drop the last '\n', or the header if no options or option groups:527- return ''.join(result[:-1])528-529- def format_epilog(self, formatter):530- return formatter.format_epilog(self.epilog)531-532- def format_help(self, formatter=None):533- if formatter is None:534- formatter = self.formatter535- result = []536- if self.usage:537- result.append(self.get_usage() + '\n')538- if self.description:539- result.append(self.format_description(formatter) + '\n')540- result.append(self.format_option_help(formatter))541- result.append(self.format_epilog(formatter))542- return ''.join(result)543-544-545-class _SimplifiedFormatter(IndentedHelpFormatter):546-547- def format_usage(self, usage):548- prefix = 'Usage: '549- indent = len(prefix)550- text_width = self.width - indent551- return '%s%s\n' % (prefix, TextWrapper(552- text_width, initial_indent='',553- subsequent_indent=' ' * indent,554- replace_whitespace=False).fill(usage))555-556- def _format_text(self, text):557- text_width = self.width - self.current_indent558- indent = ' ' * self.current_indent559-560- return TextWrapper(text_width,561- initial_indent=indent,562- subsequent_indent=indent,563- replace_whitespace=False).fill_paragraphs(text)564-565- def format_description(self, description):566- if not description:567- return ''568- self.indent()569- rv = self._format_text(description) + '\n'570- self.dedent()571- return rv572-573- def format_option_strings(self, option):574- rv = IndentedHelpFormatter.format_option_strings(self, option)575- if hasattr(option, '_negative_version'):576- rv += ' / ' + IndentedHelpFormatter.format_option_strings(577- self, option._negative_version)578- return rv579-580-335 class _SimplifiedOptionParser(OptionParser):336 337 def __init__(self, ctx, **extra):584- usage = ctx.command_path + ' ' + ctx.command.options_metavar585- OptionParser.__init__(self, usage=usage,338+ OptionParser.__init__(self, **extra)586- formatter=_SimplifiedFormatter(),587- **extra)339 self.__ctx = ctx340 590- def format_option_help(self, formatter):591- rv = OptionParser.format_option_help(self, formatter)592- extra_help = self.__ctx.command.format_extra_help(self.__ctx)593- if extra_help:594- rv = '%s\n%s' % (rv, extra_help)595- return rv596-341 def error(self, msg):342 raise UsageError(msg, self.__ctx)modified:click/core.py+89 added-35 removed
5 unmodified lines6 from .types import convert_type, BOOL7 from .utils import make_str8 from .exceptions import UsageError, Abort9 from .helpers import prompt, confirm, echo10+from .formatting import HelpFormatter11 12 from . import _optparse13 from ._compat import PY214 63 unmodified lines78 else:79 self.auto_envvar_prefix = auto_envvar_prefix.upper()80 self.auto_envvar_prefix = auto_envvar_prefix81 81- self._parser = command._make_parser(self)82 self._close_callbacks = []83 84 def __enter__(self):85 return self75 unmodified lines161 def format_usage(self):162 """Helper method to get formatted usage string for the current163 context and command.164 """165- return self.command.format_usage(self)165+ return self.command.format_usage(self).rstrip('\n')166 167 def format_help(self):168 """Helper method to get formatted help page for the current169 context and command.170 """171- return self.command.format_help(self)171+ return self.command.format_help(self).rstrip('\n')172 173 def invoke(*args, **kwargs):174 """Invokes a command callback in exactly the way it expects.175 """96 unmodified lines272 for param in self.iter_params_for_processing():273 yield param.name274 275 def _make_parser(self, ctx):276- parser = _optparse._SimplifiedOptionParser(277- ctx, description=self.help, epilog=self.epilog)276+ parser = _optparse._SimplifiedOptionParser(ctx)277 for param in self.params:278 param._add_to_parser(parser, ctx)279 return parser280 281 def format_usage(self, ctx):282 """Formats the usage line."""284- return ctx._parser.get_usage()283+ formatter = HelpFormatter()284+ formatter.write_usage(ctx.command_path,285+ self.options_metavar)286+ return formatter.getvalue()287 288 def format_help(self, ctx):289 """Formats the help."""288- return ctx._parser.format_help().rstrip()290+ formatter = HelpFormatter()291+ self._format(ctx, formatter)292+ return formatter.getvalue()293 290- def format_extra_help(self, ctx):291- pass294+ def _format(self, ctx, formatter):295+ self._format_usage(ctx, formatter)296+ self._format_help(ctx, formatter)297+ self._format_options(ctx, formatter)298+ self._format_epilog(ctx, formatter)299 300+ def _format_usage(self, ctx, formatter):301+ formatter.write_usage(ctx.command_path,302+ self.options_metavar)303+ formatter.write_paragraph()304+305+ def _format_help(self, ctx, formatter):306+ if self.help:307+ with formatter.indentation():308+ formatter.write_text(self.help)309+310+ def _format_options(self, ctx, formatter):311+ opts = []312+ for param in self.params:313+ rv = param.get_help_record(ctx)314+ if rv is not None:315+ opts.append(rv)316+317+ if opts:318+ with formatter.section('Options'):319+ formatter.write_dl(opts)320+321+ def _format_epilog(self, ctx, formatter):322+ if self.epilog:323+ with formatter.indentation():324+ formatter.write_text(self.epilog)325+326 def make_context(self, info_name, args, parent=None, **extra):327 """This function when given an info name and arguments will kick328 off the parsing and create a new :class:`Context`. It does not329 invoke the actual command callback though.8 unmodified lines338 :param extra: extra keyword arguments forwarded to the context339 constructor.340 """341 ctx = Context(self, info_name=info_name, parent=parent, **extra)342+ parser = self._make_parser(ctx)309- opts, args = ctx._parser.parse_args(args=args)343+ opts, args = parser.parse_args(args=args)344 345 for param in ctx.command.iter_params_for_processing():346 value, args = param.handle_parse_result(ctx, opts, args)347 63 unmodified lines411 echo(file=sys.stderr)412 raise Abort()413 except UsageError as e:414 if e.ctx is not None:381- echo(e.ctx.format_usage(), file=sys.stderr)415+ echo(e.ctx.format_usage() + '\n', file=sys.stderr)416 echo('Error: %s' % e.message, file=sys.stderr)417 sys.exit(2)418 except Abort:419 echo('Aborted!', file=sys.stderr)34 unmodified lines454 self.subcommand_metavar = subcommand_metavar455 456 def _make_parser(self, ctx):457 parser = Command._make_parser(self, ctx)424- parser.usage += ' ' + self.subcommand_metavar458 parser.allow_interspersed_args = False459 return parser460 428- def format_extra_help(self, ctx):429- commands = self.list_commands(ctx)430- if not commands:431- return461+ def _format_usage(self, ctx, formatter):462+ formatter.write_usage(ctx.command_path,463+ self.options_metavar + ' ' +464+ self.subcommand_metavar)465+ formatter.write_paragraph()466 433- longest = len(sorted(commands, key=len)[-1])467+ def _format_options(self, ctx, formatter):468+ Command._format_options(self, ctx, formatter)469+ self._format_commands(ctx, formatter)470 435- subcommand_info = []471+ def _format_commands(self, ctx, formatter):472+ rows = []473 for subcommand in self.list_commands(ctx):474 cmd = self.get_command(ctx, subcommand)475 # What is this, the tool lied about a command. Ignore it476 if cmd is None:477 continue478+479 help = cmd.short_help or ''442- subcommand_info.append(' %-*s %s' % (longest, subcommand, help))480+ rows.append((subcommand, help))481 444- return 'Commands:\n%s' % '\n'.join(subcommand_info)482+ if rows:483+ with formatter.section('Commands'):484+ formatter.write_dl(rows)485 486 def invoke(self, ctx):487 if not ctx.args:488 if self.invoke_without_command:224 unmodified lines713 if self.expose_value:714 ctx.params[self.name] = value715 return value, args716 717+ def get_help_record(self, ctx):718+ pass719 720+721 class Option(Parameter):722 """Options are usually optionaly values on the command line and723 have some extra features that arguments don't have.724 113 unmodified lines838 839 return name.replace('-', '_'), opts, secondary_opts840 841 def _add_to_parser(self, parser, ctx):799- help = self.help800- extra = []801- if self.default is not None and self.show_default:802- extra.append('default: %s' % self.default)803- if self.required:804- extra.append('required')805- if self.nargs != 1:806- extra.append('%d arguments' % self.nargs)807- if extra:808- help = '%s[%s]' % (help and help + ' ' or '', '; '.join(extra))809-842 kwargs = {811- 'help': help,843 'dest': self.name,844 'nargs': self.nargs,814- 'metavar': self.make_metavar(),845 }846 847 action = self.multiple and 'append' or 'store'848 2 unmodified lines851 if self.is_bool_flag and self.secondary_opts:852 pos_opt = _optparse.Option(853 *self.opts, action=action + '_const', const=True, **kwargs)854 kwargs.pop('default', None)825- kwargs.pop('help', None)855 neg_opt = _optparse.Option(856 *self.secondary_opts, action=action + '_const',828- const=False, help=_optparse.SUPPRESS_HELP, **kwargs)857+ const=False, **kwargs)858 pos_opt._negative_version = neg_opt859 parser.add_option(pos_opt)860 parser.add_option(neg_opt)861 else:3 unmodified lines865 else:866 kwargs['action'] = action867 parser.add_option(*self.opts, **kwargs)868 869+ def get_help_record(self, ctx):870+ def _write_opts(opts):871+ rv = []872+ for opt in opts:873+ if not self.is_flag:874+ opt += ' ' + self.make_metavar()875+ rv.append(opt)876+ return ', '.join(rv)877+ rv = [_write_opts(self.opts)]878+ if self.secondary_opts:879+ rv.append(_write_opts(self.secondary_opts))880+881+ help = self.help or ''882+ extra = []883+ if self.default is not None and self.show_default:884+ extra.append('default: %s' % self.default)885+ if self.required:886+ extra.append('required')887+ if self.nargs != 1:888+ extra.append('%d arguments' % self.nargs)889+ if extra:890+ help = '%s[%s]' % (help and help + ' ' or '', '; '.join(extra))891+892+ return (' / '.join(rv), help)893+894 def get_default(self, ctx):895 # If we're a non boolean flag out default is more complex because896 # we need to look at all flags in the same group to figure out897 # if we're the the default one in which case we return the flag109 unmodified linesmodified:click/formatting.py+158 added-15 removed
1 import textwrap2+from contextlib import contextmanager3 4+from .helpers import get_terminal_size5 6+7+def measure_table(rows):8+ widths = {}9+ for row in rows:10+ for idx, col in enumerate(row):11+ widths[idx] = max(widths.get(idx, 0), len(col))12+ return tuple(y for x, y in sorted(widths.items()))13+14+15+def iter_rows(rows, col_count):16+ for row in rows:17+ row = tuple(row)18+ yield row + ('',) * (col_count - len(row))19+20+21 class TextWrapper(textwrap.TextWrapper):22 23 def _cutdown(self, ucstr, space_left):24 l = 012 unmodified lines37 reversed_chunks[-1] = res38 elif not cur_line:39 cur_line.append(reversed_chunks.pop())40 24- def fill_paragraphs(self, text):25- # Remove unnecessary newlines so that we can fill properly26- p = []27- buf = []28- for line in text.splitlines():29- if not line:30- p.append(' '.join(buf))31- buf = []41+ @contextmanager42+ def extra_indent(self, indent):43+ old_initial_indent = self.initial_indent44+ old_subsequent_indent = self.subsequent_indent45+ self.initial_indent += indent46+ self.subsequent_indent += indent47+ try:48+ yield49+ finally:50+ self.initial_indent = old_initial_indent51+ self.subsequent_indent = old_subsequent_indent52+53+54+def wrap_text(text, width=78, initial_indent='', subsequent_indent='',55+ preserve_paragraphs=False):56+ """A helper function that intelligently wraps text. By default it57+ assumes that it operates on a single paragraph of text but if the58+ `preserve_paragraphs` parameter is provided it will intelligently59+ handle paragraphs (defined by two empty lines).60+61+ :param text: the text that should be rewrapped.62+ :param width: the maximum width for the text.63+ :param initial_indent: the initial indent that should be placed on the64+ first line as a string.65+ :param subsequent_indent: the indent string that should be placed on66+ each consecutive line.67+ :param preserve_paragraphs: if this flag is set then the wrapping will68+ intelligently handle paragraphs.69+ """70+ text = text.expandtabs()71+ wrapper = TextWrapper(width, initial_indent=initial_indent,72+ subsequent_indent=subsequent_indent,73+ replace_whitespace=False)74+ if not preserve_paragraphs:75+ return wrapper.fill(text)76+77+ p = []78+ buf = []79+ indent = 080+ for line in text.splitlines():81+ if not line:82+ p.append((indent, ' '.join(buf)))83+ buf = []84+ else:85+ indent = len(line) - len(line.lstrip())86+ buf.append(line.lstrip())87+ if buf:88+ p.append((indent, ' '.join(buf)))89+90+ rv = []91+ for indent, text in p:92+ with wrapper.extra_indent(' ' * indent):93+ rv.append(wrapper.fill(text))94+95+ return '\n\n'.join(rv)96+97+98+class HelpFormatter(object):99+ """This class helps with formatting text based help pages."""100+101+ def __init__(self, indent_increment=2, width=None):102+ self.indent_increment = indent_increment103+ if width is None:104+ width = min(get_terminal_size()[0], 80) - 2105+ self.width = width106+ self.current_indent = 0107+ self.buffer = []108+109+ def indent(self):110+ self.current_indent += self.indent_increment111+112+ def dedent(self):113+ self.current_indent -= self.indent_increment114+115+ def write_usage(self, prog, args=''):116+ prefix = '%*s%s' % (self.current_indent, 'Usage: ', prog)117+ self.buffer.append(prefix)118+119+ text_width = max(self.width - self.current_indent - len(prefix), 10)120+ indent = ' ' * (len(prefix) + 1)121+ self.buffer.append(wrap_text(args, text_width,122+ initial_indent=' ',123+ subsequent_indent=indent))124+125+ self.buffer.append('\n')126+127+ def write_heading(self, heading):128+ self.buffer.append('%*s%s:\n' % (self.current_indent, '', heading))129+130+ def write_paragraph(self):131+ if self.buffer:132+ self.buffer.append('\n')133+134+ def write_text(self, text):135+ text_width = max(self.width - self.current_indent, 11)136+ indent = ' ' * self.current_indent137+ self.buffer.append(wrap_text(text, text_width,138+ initial_indent=indent,139+ subsequent_indent=indent,140+ preserve_paragraphs=True))141+ self.buffer.append('\n')142+143+ def write_dl(self, rows, col_max=20, col_spacing=2):144+ rows = list(rows)145+ widths = measure_table(rows)146+ if len(widths) != 2:147+ raise TypeError('Expected two columns for definition list')148+149+ first_col = min(widths[0], col_max) + col_spacing150+151+ for first, second in iter_rows(rows, len(widths)):152+ self.buffer.append('%*s%s' % (self.current_indent, '', first))153+ if len(first) <= first_col:154+ self.buffer.append(' ' * (first_col - len(first)))155 else:33- buf.append(line)34- if buf:35- p.append(' '.join(buf))156+ self.buffer.append('\n')157+ self.buffer.append(' ' * (first_col + self.current_indent))158+ text_width = self.width - first_col - 2159+ self.buffer.append(wrap_text(160+ second, text_width, initial_indent='',161+ subsequent_indent=' ' * (first_col + self.current_indent)))162+ self.buffer.append('\n')163 37- rv = []38- for text in p:39- rv.append(self.fill(text))40- return '\n\n'.join(rv)164+ @contextmanager165+ def section(self, name):166+ self.write_paragraph()167+ self.write_heading(name)168+ self.indent()169+ try:170+ yield171+ finally:172+ self.dedent()173+174+ @contextmanager175+ def indentation(self):176+ self.indent()177+ try:178+ yield179+ finally:180+ self.dedent()181+182+ def getvalue(self):183+ return ''.join(self.buffer)modified:examples/repo/repo.py+2 added
28 unmodified lines29 @click.argument('src')30 @click.argument('dest', required=False)31 @click.option('--shallow/--deep', default=False,32 help='Makes a checkout shallow or deep. Deep by default.')33+@click.option('--with-readline/--without-readline', default=False,34+ help='Makes a checkout shallow or deep. Deep by default.')35 @pass_repo36 def clone(repo, src, dest, shallow):37 """Clones a repository.38 45 unmodified lines