Merge pull request #1850 from janLuke/fix/make-default-short-help
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Fix and refactor make_default_short_help (issue #1849)
authored by David Lord · committed by GitHub · parents 30e7f76, d48b59b · Browse files · 3 files·+79 added−22 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+79 added−22 removed
- tests:+36 added−0 removed
- other:+43 added−22 removed
Provenance
- Commit
82a83fd- Tree
338fde6- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
30e7f76- Parent 2
d48b59b
3 files changed+79 added−22 removed
modified:src/click/utils.py+41 added-22 removed
45 unmodified lines46 return value.decode("utf-8", "replace")47 return str(value)48 49 50-def make_default_short_help(help, max_length=45):51- """Return a condensed version of help string."""52- line_ending = help.find("\n\n")53- if line_ending != -1:54- help = help[:line_ending]50+def make_default_short_help(help: str, max_length: int = 45) -> str:51+ """Returns a condensed version of help string."""52+ # Consider only the first paragraph.53+ paragraph_end = help.find("\n\n")54+55+ if paragraph_end != -1:56+ help = help[:paragraph_end]57+58+ # Collapse newlines, tabs, and spaces.59 words = help.split()56- total_length = 057- result = []58- done = False60 61+ if not words:62+ return ""63+64+ # The first paragraph started with a "no rewrap" marker, ignore it.65 if words[0] == "\b":66 words = words[1:]67 63- for word in words:64- if word[-1:] == ".":65- done = True66- new_length = 1 + len(word) if result else len(word)67- if total_length + new_length > max_length:68- result.append("...")69- done = True70- else:71- if result:72- result.append(" ")73- result.append(word)74- if done:68+ total_length = 069+ last_index = len(words) - 170+71+ for i, word in enumerate(words):72+ total_length += len(word) + (i > 0)73+74+ if total_length > max_length: # too long, truncate75 break76- total_length += new_length76 77+ if word[-1] == ".": # sentence end, truncate without "..."78- return "".join(result)78+ return " ".join(words[: i + 1])79 80+ if total_length == max_length and i != last_index:81+ break # not at sentence end, truncate with "..."82+ else:83+ return " ".join(words) # no truncation needed84 85+ # Account for the length of the suffix.86+ total_length += len("...")87+88+ # remove words until the length is short enough89+ while i > 0:90+ total_length -= len(words[i]) + (i > 0)91+92+ if total_length <= max_length:93+ break94+95+ i -= 196+97+ return " ".join(words[:i]) + "..."98+99+100 class LazyFile:101 """A lazy file works like a regular file but it does not fully open102 the file but it does perform some basic checks early to see if the103 filename parameter does make sense. This is useful for safely opening446 unmodified linesmodified:tests/test_utils.py+36 added
442 unmodified lines443 assert "hello" in click.utils._expand_args(["$CLICK_TEST"])444 assert "setup.cfg" in click.utils._expand_args(["*.cfg"])445 assert os.path.join("docs", "conf.py") in click.utils._expand_args(["**/conf.py"])446 assert "*.not-found" in click.utils._expand_args(["*.not-found"])447+448+449+@pytest.mark.parametrize(450+ ("value", "max_length", "expect"),451+ [452+ pytest.param("", 10, "", id="empty"),453+ pytest.param("123 567 90", 10, "123 567 90", id="equal length, no dot"),454+ pytest.param("123 567 9. aaaa bbb", 10, "123 567 9.", id="sentence < max"),455+ pytest.param("123 567\n\n 9. aaaa bbb", 10, "123 567", id="paragraph < max"),456+ pytest.param("123 567 90123.", 10, "123 567...", id="truncate"),457+ pytest.param("123 5678 xxxxxx", 10, "123...", id="length includes suffix"),458+ pytest.param(459+ "token in ~/.netrc ciao ciao",460+ 20,461+ "token in ~/.netrc...",462+ id="ignore dot in word",463+ ),464+ ],465+)466+@pytest.mark.parametrize(467+ "alter",468+ [469+ pytest.param(None, id=""),470+ pytest.param(471+ lambda text: "\n\b\n" + " ".join(text.split(" ")) + "\n", id="no-wrap mark"472+ ),473+ ],474+)475+def test_make_default_short_help(value, max_length, alter, expect):476+ assert len(expect) <= max_length477+478+ if alter:479+ value = alter(value)480+481+ out = click.utils.make_default_short_help(value, max_length)482+ assert out == expectmodified:CHANGES.rst+2 added
208 unmodified lines209 - The ``MultiCommand.resultcallback`` decorator is renamed to210 ``result_callback``. The old name is deprecated. :issue:`1160`211 - Fix issues with ``CliRunner`` output when using ``echo_stdin=True``.212 :issue:`1101`213+- Fix a bug of ``click.utils.make_default_short_help`` for which the214+ returned string could be as long as ``max_width + 3``. :issue:`1849`215 216 217 Version 7.1.2218 -------------635 unmodified lines