From e6ce412db0a1cc1a84065cd721b7f29fe46dd6a2 Mon Sep 17 00:00:00 2001 From: Benjamin Renard Date: Fri, 19 Nov 2021 16:13:36 +0100 Subject: [PATCH] Config: Implement custom argparse TextHelpFormatter to keep line return --- mylib/config.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/mylib/config.py b/mylib/config.py index d75075b..54d4060 100644 --- a/mylib/config.py +++ b/mylib/config.py @@ -8,8 +8,10 @@ from getpass import getpass from logging.config import fileConfig import logging import os +import re import stat import sys +import textwrap import argcomplete import keyring @@ -388,6 +390,25 @@ class ConfigSection: return '\n'.join(lines) +class RawWrappedTextHelpFormatter(argparse.RawDescriptionHelpFormatter): + + def _split_lines(self, text, width): + result = [] + for line in textwrap.dedent(text).splitlines(): + # Keep empty line + if line == "": + result.append(line) + continue + # Split ident prefix and line text + m = re.match('^( *)(.*)$', line) + ident = m.group(1) + line_text = m.group(2) + # Wrap each lines and add in result with ident prefix + for l in textwrap.wrap(line_text, width - len(ident)): + result.append(ident + l) + return result + + class Config: """ Configuration helper """ @@ -543,6 +564,7 @@ class Config: self.options_parser = argparse.ArgumentParser( description=kwargs.pop('description', self.appname), + formatter_class=RawWrappedTextHelpFormatter, **kwargs) self.options_parser.add_argument(