From c05ceb39ff1ed0ad41d977f4f95e4395ec85b825 Mon Sep 17 00:00:00 2001 From: Jaime Date: Wed, 25 Jan 2023 20:41:46 +0100 Subject: [PATCH 1/9] Notice other versions of the same page For instance, inform if a linux page is also in common. --- tldr.py | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 59 insertions(+), 3 deletions(-) diff --git a/tldr.py b/tldr.py index a379edc..9dc7a10 100755 --- a/tldr.py +++ b/tldr.py @@ -229,6 +229,59 @@ def get_language_list() -> List[str]: return languages +def get_page_for_every_platform( + command: str, + remote: Optional[str] = None, + platforms: Optional[List[str]] = None, + languages: Optional[List[str]] = None +) -> Union[List[Tuple[str, str]], bool]: + """Gives a list of tuples result-platform ordered by priority.""" + if platforms is None: + platforms = get_platform_list() + if languages is None: + languages = get_language_list() + # only use cache + if USE_CACHE: + result = list() + for platform in platforms: + for language in languages: + if platform is None: + continue + try: + result.append(( get_page_for_platform( + command, + platform, + remote, + language, + only_use_cache=True, + ), platform) + ) + break # Don't want to look for the same page in other langs + except CacheNotExist: + continue + if result: # Return if smth was found + return result + # Know here that we don't have the info in cache + result = list() + for platform in platforms: + for language in languages: + if platform is None: + continue + try: + result.append(( get_page_for_platform(command, platform, remote, language), platform)) + break + except HTTPError as err: + if err.code != 404: + raise + except URLError: + if not PAGES_SOURCE_LOCATION.startswith('file://'): + raise + if result: # Return if smth was found + return result + + return False + + def get_page( command: str, remote: Optional[str] = None, @@ -552,20 +605,23 @@ def main() -> None: else: try: command = '-'.join(options.command).lower() - result = get_page( + results = get_page_for_every_platform( command, options.source, options.platform, options.language ) - if not result: + if not results: sys.exit(( "`{cmd}` documentation is not available.\n" "If you want to contribute it, feel free to" " send a pull request to: https://github.com/tldr-pages/tldr" ).format(cmd=command)) else: - output(result, plain=options.markdown) + output(results[0][0], plain=options.markdown) + if results[1:]: + platform_str = results[1][1] + print(f"There are other versions of this page in the {platform_str} category.") except URLError as e: sys.exit("Error fetching from tldr: {}".format(e)) From f78ee9e51ee486d126a35a78f6882cc8cc4a6106 Mon Sep 17 00:00:00 2001 From: Jaime <79403778+Jaimepas77@users.noreply.github.com> Date: Wed, 8 Feb 2023 10:22:27 +0100 Subject: [PATCH 2/9] Update tldr.py Co-authored-by: CleanMachine1 <78213164+CleanMachine1@users.noreply.github.com> --- tldr.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tldr.py b/tldr.py index 497753d..33cec8d 100755 --- a/tldr.py +++ b/tldr.py @@ -622,7 +622,7 @@ def main() -> None: output(results[0][0], plain=options.markdown) if results[1:]: platform_str = results[1][1] - print(f"There are other versions of this page in the {platform_str} category.") + print(f"There are other versions of this page under the {platform_str} platform.") except URLError as e: sys.exit("Error fetching from tldr: {}".format(e)) From 7bcb7cdc7eeea85db3a8b8d70bd116068a7cc091 Mon Sep 17 00:00:00 2001 From: Jaime Date: Wed, 8 Feb 2023 10:36:38 +0100 Subject: [PATCH 3/9] Update the code style --- tldr.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tldr.py b/tldr.py index 33cec8d..a748165 100755 --- a/tldr.py +++ b/tldr.py @@ -622,7 +622,7 @@ def main() -> None: output(results[0][0], plain=options.markdown) if results[1:]: platform_str = results[1][1] - print(f"There are other versions of this page under the {platform_str} platform.") + print("There are other versions of this page under the {} platform.".format(platform_str)) except URLError as e: sys.exit("Error fetching from tldr: {}".format(e)) From 6636dd106a912eebcff1977c8b007ec0e8ece1ed Mon Sep 17 00:00:00 2001 From: Vitor Henrique <87824454+vitorhcl@users.noreply.github.com> Date: Thu, 1 Feb 2024 17:46:20 -0300 Subject: [PATCH 4/9] feat: list all found platforms that have the page --- tldr.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tldr.py b/tldr.py index cf97fce..96052ba 100755 --- a/tldr.py +++ b/tldr.py @@ -621,8 +621,9 @@ def main() -> None: else: output(results[0][0], plain=options.markdown) if results[1:]: - platform_str = results[1][1] - print("There are other versions of this page under the {} platform.".format(platform_str)) + platforms_str = [result[1] for result in results[1:]] + single = len(platforms_str) == 1 + print(f"There {'is' if single else 'are'} other version{'' if single else 's'} of this page under the following platform{'' if single else 's'}: {', '.join(platforms_str)}.") except URLError as e: sys.exit("Error fetching from tldr: {}".format(e)) From ec78408eda6bfd19dc508d69085d9019184b1f21 Mon Sep 17 00:00:00 2001 From: Vitor Henrique <87824454+vitorhcl@users.noreply.github.com> Date: Fri, 23 Feb 2024 09:09:08 -0300 Subject: [PATCH 5/9] fix: line too long --- tldr.py | 410 ++++++++++++++++++++++++++++++-------------------------- 1 file changed, 221 insertions(+), 189 deletions(-) diff --git a/tldr.py b/tldr.py index 9216437..740e02d 100755 --- a/tldr.py +++ b/tldr.py @@ -20,22 +20,21 @@ __version__ = "3.2.0" __client_specification__ = "1.5" -REQUEST_HEADERS = {'User-Agent': 'tldr-python-client'} +REQUEST_HEADERS = {"User-Agent": "tldr-python-client"} PAGES_SOURCE_LOCATION = os.environ.get( - 'TLDR_PAGES_SOURCE_LOCATION', - 'https://raw.githubusercontent.com/tldr-pages/tldr/main/pages' -).rstrip('/') + "TLDR_PAGES_SOURCE_LOCATION", + "https://raw.githubusercontent.com/tldr-pages/tldr/main/pages", +).rstrip("/") DOWNLOAD_CACHE_LOCATION = os.environ.get( - 'TLDR_DOWNLOAD_CACHE_LOCATION', - 'https://tldr-pages.github.io/assets/tldr.zip' + "TLDR_DOWNLOAD_CACHE_LOCATION", "https://tldr-pages.github.io/assets/tldr.zip" ) -USE_NETWORK = int(os.environ.get('TLDR_NETWORK_ENABLED', '1')) > 0 -USE_CACHE = int(os.environ.get('TLDR_CACHE_ENABLED', '1')) > 0 -MAX_CACHE_AGE = int(os.environ.get('TLDR_CACHE_MAX_AGE', 24*7)) +USE_NETWORK = int(os.environ.get("TLDR_NETWORK_ENABLED", "1")) > 0 +USE_CACHE = int(os.environ.get("TLDR_CACHE_ENABLED", "1")) > 0 +MAX_CACHE_AGE = int(os.environ.get("TLDR_CACHE_MAX_AGE", 24 * 7)) URLOPEN_CONTEXT = None -if int(os.environ.get('TLDR_ALLOW_INSECURE', '0')) == 1: +if int(os.environ.get("TLDR_ALLOW_INSECURE", "0")) == 1: URLOPEN_CONTEXT = ssl.create_default_context() URLOPEN_CONTEXT.check_hostname = False URLOPEN_CONTEXT.verify_mode = ssl.CERT_NONE @@ -47,7 +46,7 @@ "openbsd": "openbsd", "netbsd": "netbsd", "sunos": "sunos", - "win32": "windows" + "win32": "windows", } @@ -56,50 +55,41 @@ class CacheNotExist(Exception): def get_language_code(language: str) -> str: - language = language.split('.')[0] - if language in ['pt_PT', 'pt_BR', 'zh_TW']: + language = language.split(".")[0] + if language in ["pt_PT", "pt_BR", "zh_TW"]: return language elif language == "pt": return "pt_PT" - return language.split('_')[0] + return language.split("_")[0] def get_default_language() -> str: - default_lang = get_language_code( - os.environ.get( - 'LANG', - 'C' - ) - ) + default_lang = get_language_code(os.environ.get("LANG", "C")) - if default_lang == 'C' or default_lang == 'POSIX': + if default_lang == "C" or default_lang == "POSIX": default_lang = None return default_lang def get_cache_dir() -> str: - if os.environ.get('XDG_CACHE_HOME', False): - return os.path.join(os.environ.get('XDG_CACHE_HOME'), 'tldr') - if os.environ.get('HOME', False): - return os.path.join(os.environ.get('HOME'), '.cache', 'tldr') + if os.environ.get("XDG_CACHE_HOME", False): + return os.path.join(os.environ.get("XDG_CACHE_HOME"), "tldr") + if os.environ.get("HOME", False): + return os.path.join(os.environ.get("HOME"), ".cache", "tldr") return os.path.join(os.path.expanduser("~"), ".cache", "tldr") def get_cache_file_path(command: str, platform: str, language: str) -> str: pages_dir = "pages" - if language and language != 'en': + if language and language != "en": pages_dir += "." + language return os.path.join(get_cache_dir(), pages_dir, platform, command) + ".md" def load_page_from_cache(command: str, platform: str, language: str) -> Optional[str]: try: - with open(get_cache_file_path( - command, - platform, - language), 'rb' - ) as cache_file: + with open(get_cache_file_path(command, platform, language), "rb") as cache_file: cache_file_contents = cache_file.read() return cache_file_contents except Exception: @@ -107,10 +97,7 @@ def load_page_from_cache(command: str, platform: str, language: str) -> Optional def store_page_to_cache( - page: str, - command: str, - platform: str, - language: str + page: str, command: str, platform: str, language: str ) -> Optional[str]: try: cache_file_path = get_cache_file_path(command, platform, language) @@ -135,10 +122,10 @@ def get_page_url(command: str, platform: str, remote: str, language: str) -> str if remote is None: remote = PAGES_SOURCE_LOCATION - if language is None or language == 'en': - language = '' + if language is None or language == "en": + language = "" else: - language = '.' + language + language = "." + language return remote + language + "/" + platform + "/" + quote(command) + ".md" @@ -148,23 +135,25 @@ def get_page_for_platform( platform: str, remote: str, language: str, - only_use_cache: bool = False + only_use_cache: bool = False, ) -> str: data_downloaded = False if USE_CACHE and have_recent_cache(command, platform, language): data = load_page_from_cache(command, platform, language) elif only_use_cache: - raise CacheNotExist("Cache for {} in {} not Found".format( - command, - platform, - )) + raise CacheNotExist( + "Cache for {} in {} not Found".format( + command, + platform, + ) + ) else: page_url = get_page_url(command, platform, remote, language) try: data = urlopen( Request(page_url, headers=REQUEST_HEADERS), timeout=10, - context=URLOPEN_CONTEXT + context=URLOPEN_CONTEXT, ).read() data_downloaded = True except Exception: @@ -179,15 +168,11 @@ def get_page_for_platform( def update_page_for_platform( - command: str, - platform: str, - remote: str, - language: str + command: str, platform: str, remote: str, language: str ) -> None: page_url = get_page_url(platform, command, remote, language) data = urlopen( - Request(page_url, headers=REQUEST_HEADERS), - context=URLOPEN_CONTEXT + Request(page_url, headers=REQUEST_HEADERS), context=URLOPEN_CONTEXT ).read() store_page_to_cache(data, command, platform, language) @@ -196,11 +181,11 @@ def get_platform() -> str: for key in OS_DIRECTORIES: if sys.platform.startswith(key): return OS_DIRECTORIES[key] - return 'linux' + return "linux" def get_platform_list() -> List[str]: - platforms = ['common'] + list(OS_DIRECTORIES.values()) + platforms = ["common"] + list(OS_DIRECTORIES.values()) current_platform = get_platform() platforms.remove(current_platform) platforms.insert(0, current_platform) @@ -208,12 +193,14 @@ def get_platform_list() -> List[str]: def get_language_list() -> List[str]: - tldr_language = get_language_code(os.environ.get('TLDR_LANGUAGE', '')) - languages = os.environ.get('LANGUAGE', '').split(':') - languages = list(map( - get_language_code, - filter(lambda x: not (x == 'C' or x == 'POSIX' or x == ''), languages) - )) + tldr_language = get_language_code(os.environ.get("TLDR_LANGUAGE", "")) + languages = os.environ.get("LANGUAGE", "").split(":") + languages = list( + map( + get_language_code, + filter(lambda x: not (x == "C" or x == "POSIX" or x == ""), languages), + ) + ) default_lang = get_default_language() @@ -228,8 +215,8 @@ def get_language_list() -> List[str]: except ValueError: pass languages.insert(0, tldr_language) - if 'en' not in languages: - languages.append('en') + if "en" not in languages: + languages.append("en") return languages @@ -237,7 +224,7 @@ def get_page_for_every_platform( command: str, remote: Optional[str] = None, platforms: Optional[List[str]] = None, - languages: Optional[List[str]] = None + languages: Optional[List[str]] = None, ) -> Union[List[Tuple[str, str]], bool]: """Gives a list of tuples result-platform ordered by priority.""" if platforms is None: @@ -252,15 +239,19 @@ def get_page_for_every_platform( if platform is None: continue try: - result.append(( get_page_for_platform( + result.append( + ( + get_page_for_platform( command, platform, remote, language, only_use_cache=True, - ), platform) + ), + platform, + ) ) - break # Don't want to look for the same page in other langs + break # Don't want to look for the same page in other langs except CacheNotExist: continue if result: # Return if smth was found @@ -272,13 +263,18 @@ def get_page_for_every_platform( if platform is None: continue try: - result.append(( get_page_for_platform(command, platform, remote, language), platform)) + result.append( + ( + get_page_for_platform(command, platform, remote, language), + platform, + ) + ) break except HTTPError as err: if err.code != 404: raise except URLError: - if not PAGES_SOURCE_LOCATION.startswith('file://'): + if not PAGES_SOURCE_LOCATION.startswith("file://"): raise if result: # Return if smth was found return result @@ -290,7 +286,7 @@ def get_page( command: str, remote: Optional[str] = None, platforms: Optional[List[str]] = None, - languages: Optional[List[str]] = None + languages: Optional[List[str]] = None, ) -> Union[str, bool]: if platforms is None: platforms = get_platform_list() @@ -322,39 +318,41 @@ def get_page( if err.code != 404: raise except URLError: - if not PAGES_SOURCE_LOCATION.startswith('file://'): + if not PAGES_SOURCE_LOCATION.startswith("file://"): raise return False DEFAULT_COLORS = { - 'name': 'bold', - 'description': '', - 'example': 'green', - 'command': 'red', - 'parameter': '' + "name": "bold", + "description": "", + "example": "green", + "command": "red", + "parameter": "", } # See more details in the README: # https://github.com/tldr-pages/tldr-python-client#colors -ACCEPTED_COLORS = [ - 'blue', 'green', 'yellow', 'cyan', 'magenta', 'white', 'grey', 'red' -] +ACCEPTED_COLORS = ["blue", "green", "yellow", "cyan", "magenta", "white", "grey", "red"] ACCEPTED_COLOR_BACKGROUNDS = [ - 'on_blue', 'on_cyan', 'on_magenta', 'on_white', - 'on_grey', 'on_yellow', 'on_red', 'on_green' + "on_blue", + "on_cyan", + "on_magenta", + "on_white", + "on_grey", + "on_yellow", + "on_red", + "on_green", ] -ACCEPTED_COLOR_ATTRS = [ - 'reverse', 'blink', 'dark', 'concealed', 'underline', 'bold' -] +ACCEPTED_COLOR_ATTRS = ["reverse", "blink", "dark", "concealed", "underline", "bold"] LEADING_SPACES_NUM = 2 -COMMAND_SPLIT_REGEX = re.compile(r'(?P{{.+?}*}})') -PARAM_REGEX = re.compile(r'(?:{{)(?P.+?)(?:}})') +COMMAND_SPLIT_REGEX = re.compile(r"(?P{{.+?}*}})") +PARAM_REGEX = re.compile(r"(?:{{)(?P.+?)(?:}})") def get_commands(platforms: Optional[List[str]] = None) -> List[str]: @@ -364,7 +362,7 @@ def get_commands(platforms: Optional[List[str]] = None) -> List[str]: commands = [] if os.path.exists(get_cache_dir()): for platform in platforms: - path = os.path.join(get_cache_dir(), 'pages', platform) + path = os.path.join(get_cache_dir(), "pages", platform) if not os.path.exists(path): continue commands += [file[:-3] for file in os.listdir(path) if file.endswith(".md")] @@ -372,7 +370,7 @@ def get_commands(platforms: Optional[List[str]] = None) -> List[str]: def colors_of(key: str) -> Tuple[str, str, List[str]]: - env_key = 'TLDR_COLOR_%s' % key.upper() + env_key = "TLDR_COLOR_%s" % key.upper() values = os.environ.get(env_key, DEFAULT_COLORS[key]).strip().split() color = None on_color = None @@ -391,40 +389,41 @@ def output(page: str, plain: bool = False) -> None: if not plain: print() for line in page: - line = line.rstrip().decode('utf-8') + line = line.rstrip().decode("utf-8") if plain: print(line) continue elif len(line) == 0: continue - elif line[0] == '#': - line = ' ' * LEADING_SPACES_NUM + \ - colored(line.replace('# ', ''), *colors_of('name')) + '\n' - sys.stdout.buffer.write(line.encode('utf-8')) - elif line[0] == '>': - line = ' ' * (LEADING_SPACES_NUM - 1) + \ - colored( - line.replace('>', '').replace('<', ''), - *colors_of('description') + elif line[0] == "#": + line = ( + " " * LEADING_SPACES_NUM + + colored(line.replace("# ", ""), *colors_of("name")) + + "\n" ) - sys.stdout.buffer.write(line.encode('utf-8')) - elif line[0] == '-': - line = '\n' + ' ' * LEADING_SPACES_NUM + \ - colored(line, *colors_of('example')) - sys.stdout.buffer.write(line.encode('utf-8')) - elif line[0] == '`': + sys.stdout.buffer.write(line.encode("utf-8")) + elif line[0] == ">": + line = " " * (LEADING_SPACES_NUM - 1) + colored( + line.replace(">", "").replace("<", ""), *colors_of("description") + ) + sys.stdout.buffer.write(line.encode("utf-8")) + elif line[0] == "-": + line = ( + "\n" + " " * LEADING_SPACES_NUM + colored(line, *colors_of("example")) + ) + sys.stdout.buffer.write(line.encode("utf-8")) + elif line[0] == "`": line = line[1:-1] # need to actually parse `` - elements = [' ' * 2 * LEADING_SPACES_NUM] + elements = [" " * 2 * LEADING_SPACES_NUM] for item in COMMAND_SPLIT_REGEX.split(line): item, replaced = PARAM_REGEX.subn( - lambda x: colored( - x.group('param'), *colors_of('parameter')), - item) + lambda x: colored(x.group("param"), *colors_of("parameter")), item + ) if not replaced: - item = colored(item, *colors_of('command')) + item = colored(item, *colors_of("command")) elements.append(item) - sys.stdout.buffer.write(''.join(elements).encode('utf-8')) + sys.stdout.buffer.write("".join(elements).encode("utf-8")) print() print() @@ -432,17 +431,17 @@ def output(page: str, plain: bool = False) -> None: def update_cache(language: Optional[List[str]] = None) -> None: if language is None: tldr_language = os.environ.get("TLDR_LANGUAGE", get_default_language()) - language = tldr_language if tldr_language else 'en' + language = tldr_language if tldr_language else "en" elif isinstance(language, list): language = language[0] try: pages_dir = "pages" - if language and language != 'en': + if language and language != "en": pages_dir += "." + language - req = urlopen(Request( - DOWNLOAD_CACHE_LOCATION, - headers=REQUEST_HEADERS - ), context=URLOPEN_CONTEXT) + req = urlopen( + Request(DOWNLOAD_CACHE_LOCATION, headers=REQUEST_HEADERS), + context=URLOPEN_CONTEXT, + ) zipfile = ZipFile(BytesIO(req.read())) pattern = re.compile(r"{}/(.+)/(.+)\.md".format(pages_dir)) cached = 0 @@ -450,10 +449,7 @@ def update_cache(language: Optional[List[str]] = None) -> None: match = pattern.match(entry) if match: store_page_to_cache( - zipfile.read(entry), - match.group(2), - match.group(1), - language + zipfile.read(entry), match.group(2), match.group(1), language ) cached += 1 print("Updated cache for {:d} entries".format(cached)) @@ -465,81 +461,112 @@ def create_parser() -> ArgumentParser: parser = ArgumentParser( prog="tldr", usage="tldr command [options]", - description="Python command line client for tldr" + description="Python command line client for tldr", ) parser.add_argument( - '-v', '--version', - action='version', - version='%(prog)s {} (Client Specification {})'.format( - __version__, - __client_specification__ - ) + "-v", + "--version", + action="version", + version="%(prog)s {} (Client Specification {})".format( + __version__, __client_specification__ + ), ) - parser.add_argument("--search", - metavar='"KEYWORDS"', - type=str, - help="Search for a specific command from a query") + parser.add_argument( + "--search", + metavar='"KEYWORDS"', + type=str, + help="Search for a specific command from a query", + ) - parser.add_argument('-u', '--update', '--update_cache', - action='store_true', - help="Update the local cache of pages and exit") + parser.add_argument( + "-u", + "--update", + "--update_cache", + action="store_true", + help="Update the local cache of pages and exit", + ) parser.add_argument( - '-p', '--platform', + "-p", + "--platform", nargs=1, default=None, type=str, - choices=['linux', 'osx', 'sunos', 'windows', 'common'], - metavar='PLATFORM', - help="Override the operating system [linux, osx, sunos, windows, common]" + choices=["linux", "osx", "sunos", "windows", "common"], + metavar="PLATFORM", + help="Override the operating system [linux, osx, sunos, windows, common]", ) - parser.add_argument('-l', '--list', - default=False, - action='store_true', - help="List all available commands for operating system") - - parser.add_argument('-s', '--source', - default=PAGES_SOURCE_LOCATION, - type=str, - help="Override the default page source") - - parser.add_argument('-c', '--color', - default=None, - action='store_const', - const=False, - help="Override color stripping") - - parser.add_argument('-r', '--render', - default=False, - action='store_true', - help='Render local markdown files' - ) + parser.add_argument( + "-l", + "--list", + default=False, + action="store_true", + help="List all available commands for operating system", + ) + + parser.add_argument( + "-s", + "--source", + default=PAGES_SOURCE_LOCATION, + type=str, + help="Override the default page source", + ) - parser.add_argument('-L', '--language', - nargs=1, - default=None, - type=str, - help='Override the default language') + parser.add_argument( + "-c", + "--color", + default=None, + action="store_const", + const=False, + help="Override color stripping", + ) - parser.add_argument('-m', '--markdown', - default=False, - action='store_true', - help='Just print the plain page file.') + parser.add_argument( + "-r", + "--render", + default=False, + action="store_true", + help="Render local markdown files", + ) parser.add_argument( - 'command', type=str, nargs='*', help="command to lookup", metavar='command' + "-L", + "--language", + nargs=1, + default=None, + type=str, + help="Override the default language", + ) + + parser.add_argument( + "-m", + "--markdown", + default=False, + action="store_true", + help="Just print the plain page file.", + ) + + parser.add_argument( + "command", type=str, nargs="*", help="command to lookup", metavar="command" ).complete = {"bash": "shtab_tldr_cmd_list", "zsh": "shtab_tldr_cmd_list"} - shtab.add_argument_to(parser, preamble={ - 'bash': r'''shtab_tldr_cmd_list(){{ + shtab.add_argument_to( + parser, + preamble={ + "bash": r"""shtab_tldr_cmd_list(){{ compgen -W "$("{py}" -m tldr --list | sed 's/[^[:alnum:]_]/ /g')" -- "$1" - }}'''.format(py=sys.executable), - 'zsh': r'''shtab_tldr_cmd_list(){{ + }}""".format( + py=sys.executable + ), + "zsh": r"""shtab_tldr_cmd_list(){{ _describe 'command' "($("{py}" -m tldr --list | sed 's/[^[:alnum:]_]/ /g'))" - }}'''.format(py=sys.executable) - }) + }}""".format( + py=sys.executable + ), + }, + ) return parser @@ -560,18 +587,20 @@ def main() -> None: parser.print_help(sys.stderr) sys.exit(1) if options.list: - print('\n'.join(get_commands(options.platform))) + print("\n".join(get_commands(options.platform))) elif options.render: for command in options.command: if os.path.exists(command): - with open(command, encoding='utf-8') as open_file: - output(open_file.read().encode('utf-8').splitlines(), - plain=options.markdown) + with open(command, encoding="utf-8") as open_file: + output( + open_file.read().encode("utf-8").splitlines(), + plain=options.markdown, + ) elif options.search: - command = '-'.join(options.command) + command = "-".join(options.command) page = None maxprob = 0 - searchquery = options.search.split(' ') + searchquery = options.search.split(" ") platforms = get_platform_list() for i in get_commands(platforms): @@ -608,25 +637,28 @@ def main() -> None: else: try: - command = '-'.join(options.command).lower() + command = "-".join(options.command).lower() results = get_page_for_every_platform( - command, - options.source, - options.platform, - options.language + command, options.source, options.platform, options.language ) if not results: - sys.exit(( - "`{cmd}` documentation is not available.\n" - "If you want to contribute it, feel free to" - " send a pull request to: https://github.com/tldr-pages/tldr" - ).format(cmd=command)) + sys.exit( + ( + "`{cmd}` documentation is not available.\n" + "If you want to contribute it, feel free to" + " send a pull request to: https://github.com/tldr-pages/tldr" + ).format(cmd=command) + ) else: output(results[0][0], plain=options.markdown) if results[1:]: platforms_str = [result[1] for result in results[1:]] single = len(platforms_str) == 1 - print(f"There {'is' if single else 'are'} other version{'' if single else 's'} of this page under the following platform{'' if single else 's'}: {', '.join(platforms_str)}.") + print( + f"There {'is' if single else 'are'} other version" + "{'' if single else 's'} of this page under the following" + "platform{'' if single else 's'}: {', '.join(platforms_str)}." + ) except URLError as e: sys.exit("Error fetching from tldr: {}".format(e)) From 409086c193e4b2c71a9ac72e70c712676bbb3482 Mon Sep 17 00:00:00 2001 From: Vitor Henrique <87824454+vitorhcl@users.noreply.github.com> Date: Fri, 23 Feb 2024 10:54:20 -0300 Subject: [PATCH 6/9] fix: revert black --- tldr.py | 410 ++++++++++++++++++++++++++------------------------------ 1 file changed, 189 insertions(+), 221 deletions(-) diff --git a/tldr.py b/tldr.py index 740e02d..9216437 100755 --- a/tldr.py +++ b/tldr.py @@ -20,21 +20,22 @@ __version__ = "3.2.0" __client_specification__ = "1.5" -REQUEST_HEADERS = {"User-Agent": "tldr-python-client"} +REQUEST_HEADERS = {'User-Agent': 'tldr-python-client'} PAGES_SOURCE_LOCATION = os.environ.get( - "TLDR_PAGES_SOURCE_LOCATION", - "https://raw.githubusercontent.com/tldr-pages/tldr/main/pages", -).rstrip("/") + 'TLDR_PAGES_SOURCE_LOCATION', + 'https://raw.githubusercontent.com/tldr-pages/tldr/main/pages' +).rstrip('/') DOWNLOAD_CACHE_LOCATION = os.environ.get( - "TLDR_DOWNLOAD_CACHE_LOCATION", "https://tldr-pages.github.io/assets/tldr.zip" + 'TLDR_DOWNLOAD_CACHE_LOCATION', + 'https://tldr-pages.github.io/assets/tldr.zip' ) -USE_NETWORK = int(os.environ.get("TLDR_NETWORK_ENABLED", "1")) > 0 -USE_CACHE = int(os.environ.get("TLDR_CACHE_ENABLED", "1")) > 0 -MAX_CACHE_AGE = int(os.environ.get("TLDR_CACHE_MAX_AGE", 24 * 7)) +USE_NETWORK = int(os.environ.get('TLDR_NETWORK_ENABLED', '1')) > 0 +USE_CACHE = int(os.environ.get('TLDR_CACHE_ENABLED', '1')) > 0 +MAX_CACHE_AGE = int(os.environ.get('TLDR_CACHE_MAX_AGE', 24*7)) URLOPEN_CONTEXT = None -if int(os.environ.get("TLDR_ALLOW_INSECURE", "0")) == 1: +if int(os.environ.get('TLDR_ALLOW_INSECURE', '0')) == 1: URLOPEN_CONTEXT = ssl.create_default_context() URLOPEN_CONTEXT.check_hostname = False URLOPEN_CONTEXT.verify_mode = ssl.CERT_NONE @@ -46,7 +47,7 @@ "openbsd": "openbsd", "netbsd": "netbsd", "sunos": "sunos", - "win32": "windows", + "win32": "windows" } @@ -55,41 +56,50 @@ class CacheNotExist(Exception): def get_language_code(language: str) -> str: - language = language.split(".")[0] - if language in ["pt_PT", "pt_BR", "zh_TW"]: + language = language.split('.')[0] + if language in ['pt_PT', 'pt_BR', 'zh_TW']: return language elif language == "pt": return "pt_PT" - return language.split("_")[0] + return language.split('_')[0] def get_default_language() -> str: - default_lang = get_language_code(os.environ.get("LANG", "C")) + default_lang = get_language_code( + os.environ.get( + 'LANG', + 'C' + ) + ) - if default_lang == "C" or default_lang == "POSIX": + if default_lang == 'C' or default_lang == 'POSIX': default_lang = None return default_lang def get_cache_dir() -> str: - if os.environ.get("XDG_CACHE_HOME", False): - return os.path.join(os.environ.get("XDG_CACHE_HOME"), "tldr") - if os.environ.get("HOME", False): - return os.path.join(os.environ.get("HOME"), ".cache", "tldr") + if os.environ.get('XDG_CACHE_HOME', False): + return os.path.join(os.environ.get('XDG_CACHE_HOME'), 'tldr') + if os.environ.get('HOME', False): + return os.path.join(os.environ.get('HOME'), '.cache', 'tldr') return os.path.join(os.path.expanduser("~"), ".cache", "tldr") def get_cache_file_path(command: str, platform: str, language: str) -> str: pages_dir = "pages" - if language and language != "en": + if language and language != 'en': pages_dir += "." + language return os.path.join(get_cache_dir(), pages_dir, platform, command) + ".md" def load_page_from_cache(command: str, platform: str, language: str) -> Optional[str]: try: - with open(get_cache_file_path(command, platform, language), "rb") as cache_file: + with open(get_cache_file_path( + command, + platform, + language), 'rb' + ) as cache_file: cache_file_contents = cache_file.read() return cache_file_contents except Exception: @@ -97,7 +107,10 @@ def load_page_from_cache(command: str, platform: str, language: str) -> Optional def store_page_to_cache( - page: str, command: str, platform: str, language: str + page: str, + command: str, + platform: str, + language: str ) -> Optional[str]: try: cache_file_path = get_cache_file_path(command, platform, language) @@ -122,10 +135,10 @@ def get_page_url(command: str, platform: str, remote: str, language: str) -> str if remote is None: remote = PAGES_SOURCE_LOCATION - if language is None or language == "en": - language = "" + if language is None or language == 'en': + language = '' else: - language = "." + language + language = '.' + language return remote + language + "/" + platform + "/" + quote(command) + ".md" @@ -135,25 +148,23 @@ def get_page_for_platform( platform: str, remote: str, language: str, - only_use_cache: bool = False, + only_use_cache: bool = False ) -> str: data_downloaded = False if USE_CACHE and have_recent_cache(command, platform, language): data = load_page_from_cache(command, platform, language) elif only_use_cache: - raise CacheNotExist( - "Cache for {} in {} not Found".format( - command, - platform, - ) - ) + raise CacheNotExist("Cache for {} in {} not Found".format( + command, + platform, + )) else: page_url = get_page_url(command, platform, remote, language) try: data = urlopen( Request(page_url, headers=REQUEST_HEADERS), timeout=10, - context=URLOPEN_CONTEXT, + context=URLOPEN_CONTEXT ).read() data_downloaded = True except Exception: @@ -168,11 +179,15 @@ def get_page_for_platform( def update_page_for_platform( - command: str, platform: str, remote: str, language: str + command: str, + platform: str, + remote: str, + language: str ) -> None: page_url = get_page_url(platform, command, remote, language) data = urlopen( - Request(page_url, headers=REQUEST_HEADERS), context=URLOPEN_CONTEXT + Request(page_url, headers=REQUEST_HEADERS), + context=URLOPEN_CONTEXT ).read() store_page_to_cache(data, command, platform, language) @@ -181,11 +196,11 @@ def get_platform() -> str: for key in OS_DIRECTORIES: if sys.platform.startswith(key): return OS_DIRECTORIES[key] - return "linux" + return 'linux' def get_platform_list() -> List[str]: - platforms = ["common"] + list(OS_DIRECTORIES.values()) + platforms = ['common'] + list(OS_DIRECTORIES.values()) current_platform = get_platform() platforms.remove(current_platform) platforms.insert(0, current_platform) @@ -193,14 +208,12 @@ def get_platform_list() -> List[str]: def get_language_list() -> List[str]: - tldr_language = get_language_code(os.environ.get("TLDR_LANGUAGE", "")) - languages = os.environ.get("LANGUAGE", "").split(":") - languages = list( - map( - get_language_code, - filter(lambda x: not (x == "C" or x == "POSIX" or x == ""), languages), - ) - ) + tldr_language = get_language_code(os.environ.get('TLDR_LANGUAGE', '')) + languages = os.environ.get('LANGUAGE', '').split(':') + languages = list(map( + get_language_code, + filter(lambda x: not (x == 'C' or x == 'POSIX' or x == ''), languages) + )) default_lang = get_default_language() @@ -215,8 +228,8 @@ def get_language_list() -> List[str]: except ValueError: pass languages.insert(0, tldr_language) - if "en" not in languages: - languages.append("en") + if 'en' not in languages: + languages.append('en') return languages @@ -224,7 +237,7 @@ def get_page_for_every_platform( command: str, remote: Optional[str] = None, platforms: Optional[List[str]] = None, - languages: Optional[List[str]] = None, + languages: Optional[List[str]] = None ) -> Union[List[Tuple[str, str]], bool]: """Gives a list of tuples result-platform ordered by priority.""" if platforms is None: @@ -239,19 +252,15 @@ def get_page_for_every_platform( if platform is None: continue try: - result.append( - ( - get_page_for_platform( + result.append(( get_page_for_platform( command, platform, remote, language, only_use_cache=True, - ), - platform, - ) + ), platform) ) - break # Don't want to look for the same page in other langs + break # Don't want to look for the same page in other langs except CacheNotExist: continue if result: # Return if smth was found @@ -263,18 +272,13 @@ def get_page_for_every_platform( if platform is None: continue try: - result.append( - ( - get_page_for_platform(command, platform, remote, language), - platform, - ) - ) + result.append(( get_page_for_platform(command, platform, remote, language), platform)) break except HTTPError as err: if err.code != 404: raise except URLError: - if not PAGES_SOURCE_LOCATION.startswith("file://"): + if not PAGES_SOURCE_LOCATION.startswith('file://'): raise if result: # Return if smth was found return result @@ -286,7 +290,7 @@ def get_page( command: str, remote: Optional[str] = None, platforms: Optional[List[str]] = None, - languages: Optional[List[str]] = None, + languages: Optional[List[str]] = None ) -> Union[str, bool]: if platforms is None: platforms = get_platform_list() @@ -318,41 +322,39 @@ def get_page( if err.code != 404: raise except URLError: - if not PAGES_SOURCE_LOCATION.startswith("file://"): + if not PAGES_SOURCE_LOCATION.startswith('file://'): raise return False DEFAULT_COLORS = { - "name": "bold", - "description": "", - "example": "green", - "command": "red", - "parameter": "", + 'name': 'bold', + 'description': '', + 'example': 'green', + 'command': 'red', + 'parameter': '' } # See more details in the README: # https://github.com/tldr-pages/tldr-python-client#colors -ACCEPTED_COLORS = ["blue", "green", "yellow", "cyan", "magenta", "white", "grey", "red"] +ACCEPTED_COLORS = [ + 'blue', 'green', 'yellow', 'cyan', 'magenta', 'white', 'grey', 'red' +] ACCEPTED_COLOR_BACKGROUNDS = [ - "on_blue", - "on_cyan", - "on_magenta", - "on_white", - "on_grey", - "on_yellow", - "on_red", - "on_green", + 'on_blue', 'on_cyan', 'on_magenta', 'on_white', + 'on_grey', 'on_yellow', 'on_red', 'on_green' ] -ACCEPTED_COLOR_ATTRS = ["reverse", "blink", "dark", "concealed", "underline", "bold"] +ACCEPTED_COLOR_ATTRS = [ + 'reverse', 'blink', 'dark', 'concealed', 'underline', 'bold' +] LEADING_SPACES_NUM = 2 -COMMAND_SPLIT_REGEX = re.compile(r"(?P{{.+?}*}})") -PARAM_REGEX = re.compile(r"(?:{{)(?P.+?)(?:}})") +COMMAND_SPLIT_REGEX = re.compile(r'(?P{{.+?}*}})') +PARAM_REGEX = re.compile(r'(?:{{)(?P.+?)(?:}})') def get_commands(platforms: Optional[List[str]] = None) -> List[str]: @@ -362,7 +364,7 @@ def get_commands(platforms: Optional[List[str]] = None) -> List[str]: commands = [] if os.path.exists(get_cache_dir()): for platform in platforms: - path = os.path.join(get_cache_dir(), "pages", platform) + path = os.path.join(get_cache_dir(), 'pages', platform) if not os.path.exists(path): continue commands += [file[:-3] for file in os.listdir(path) if file.endswith(".md")] @@ -370,7 +372,7 @@ def get_commands(platforms: Optional[List[str]] = None) -> List[str]: def colors_of(key: str) -> Tuple[str, str, List[str]]: - env_key = "TLDR_COLOR_%s" % key.upper() + env_key = 'TLDR_COLOR_%s' % key.upper() values = os.environ.get(env_key, DEFAULT_COLORS[key]).strip().split() color = None on_color = None @@ -389,41 +391,40 @@ def output(page: str, plain: bool = False) -> None: if not plain: print() for line in page: - line = line.rstrip().decode("utf-8") + line = line.rstrip().decode('utf-8') if plain: print(line) continue elif len(line) == 0: continue - elif line[0] == "#": - line = ( - " " * LEADING_SPACES_NUM - + colored(line.replace("# ", ""), *colors_of("name")) - + "\n" + elif line[0] == '#': + line = ' ' * LEADING_SPACES_NUM + \ + colored(line.replace('# ', ''), *colors_of('name')) + '\n' + sys.stdout.buffer.write(line.encode('utf-8')) + elif line[0] == '>': + line = ' ' * (LEADING_SPACES_NUM - 1) + \ + colored( + line.replace('>', '').replace('<', ''), + *colors_of('description') ) - sys.stdout.buffer.write(line.encode("utf-8")) - elif line[0] == ">": - line = " " * (LEADING_SPACES_NUM - 1) + colored( - line.replace(">", "").replace("<", ""), *colors_of("description") - ) - sys.stdout.buffer.write(line.encode("utf-8")) - elif line[0] == "-": - line = ( - "\n" + " " * LEADING_SPACES_NUM + colored(line, *colors_of("example")) - ) - sys.stdout.buffer.write(line.encode("utf-8")) - elif line[0] == "`": + sys.stdout.buffer.write(line.encode('utf-8')) + elif line[0] == '-': + line = '\n' + ' ' * LEADING_SPACES_NUM + \ + colored(line, *colors_of('example')) + sys.stdout.buffer.write(line.encode('utf-8')) + elif line[0] == '`': line = line[1:-1] # need to actually parse `` - elements = [" " * 2 * LEADING_SPACES_NUM] + elements = [' ' * 2 * LEADING_SPACES_NUM] for item in COMMAND_SPLIT_REGEX.split(line): item, replaced = PARAM_REGEX.subn( - lambda x: colored(x.group("param"), *colors_of("parameter")), item - ) + lambda x: colored( + x.group('param'), *colors_of('parameter')), + item) if not replaced: - item = colored(item, *colors_of("command")) + item = colored(item, *colors_of('command')) elements.append(item) - sys.stdout.buffer.write("".join(elements).encode("utf-8")) + sys.stdout.buffer.write(''.join(elements).encode('utf-8')) print() print() @@ -431,17 +432,17 @@ def output(page: str, plain: bool = False) -> None: def update_cache(language: Optional[List[str]] = None) -> None: if language is None: tldr_language = os.environ.get("TLDR_LANGUAGE", get_default_language()) - language = tldr_language if tldr_language else "en" + language = tldr_language if tldr_language else 'en' elif isinstance(language, list): language = language[0] try: pages_dir = "pages" - if language and language != "en": + if language and language != 'en': pages_dir += "." + language - req = urlopen( - Request(DOWNLOAD_CACHE_LOCATION, headers=REQUEST_HEADERS), - context=URLOPEN_CONTEXT, - ) + req = urlopen(Request( + DOWNLOAD_CACHE_LOCATION, + headers=REQUEST_HEADERS + ), context=URLOPEN_CONTEXT) zipfile = ZipFile(BytesIO(req.read())) pattern = re.compile(r"{}/(.+)/(.+)\.md".format(pages_dir)) cached = 0 @@ -449,7 +450,10 @@ def update_cache(language: Optional[List[str]] = None) -> None: match = pattern.match(entry) if match: store_page_to_cache( - zipfile.read(entry), match.group(2), match.group(1), language + zipfile.read(entry), + match.group(2), + match.group(1), + language ) cached += 1 print("Updated cache for {:d} entries".format(cached)) @@ -461,112 +465,81 @@ def create_parser() -> ArgumentParser: parser = ArgumentParser( prog="tldr", usage="tldr command [options]", - description="Python command line client for tldr", + description="Python command line client for tldr" ) parser.add_argument( - "-v", - "--version", - action="version", - version="%(prog)s {} (Client Specification {})".format( - __version__, __client_specification__ - ), + '-v', '--version', + action='version', + version='%(prog)s {} (Client Specification {})'.format( + __version__, + __client_specification__ + ) ) - parser.add_argument( - "--search", - metavar='"KEYWORDS"', - type=str, - help="Search for a specific command from a query", - ) + parser.add_argument("--search", + metavar='"KEYWORDS"', + type=str, + help="Search for a specific command from a query") - parser.add_argument( - "-u", - "--update", - "--update_cache", - action="store_true", - help="Update the local cache of pages and exit", - ) + parser.add_argument('-u', '--update', '--update_cache', + action='store_true', + help="Update the local cache of pages and exit") parser.add_argument( - "-p", - "--platform", + '-p', '--platform', nargs=1, default=None, type=str, - choices=["linux", "osx", "sunos", "windows", "common"], - metavar="PLATFORM", - help="Override the operating system [linux, osx, sunos, windows, common]", - ) - - parser.add_argument( - "-l", - "--list", - default=False, - action="store_true", - help="List all available commands for operating system", - ) - - parser.add_argument( - "-s", - "--source", - default=PAGES_SOURCE_LOCATION, - type=str, - help="Override the default page source", + choices=['linux', 'osx', 'sunos', 'windows', 'common'], + metavar='PLATFORM', + help="Override the operating system [linux, osx, sunos, windows, common]" ) - parser.add_argument( - "-c", - "--color", - default=None, - action="store_const", - const=False, - help="Override color stripping", - ) - - parser.add_argument( - "-r", - "--render", - default=False, - action="store_true", - help="Render local markdown files", - ) + parser.add_argument('-l', '--list', + default=False, + action='store_true', + help="List all available commands for operating system") + + parser.add_argument('-s', '--source', + default=PAGES_SOURCE_LOCATION, + type=str, + help="Override the default page source") + + parser.add_argument('-c', '--color', + default=None, + action='store_const', + const=False, + help="Override color stripping") + + parser.add_argument('-r', '--render', + default=False, + action='store_true', + help='Render local markdown files' + ) - parser.add_argument( - "-L", - "--language", - nargs=1, - default=None, - type=str, - help="Override the default language", - ) + parser.add_argument('-L', '--language', + nargs=1, + default=None, + type=str, + help='Override the default language') - parser.add_argument( - "-m", - "--markdown", - default=False, - action="store_true", - help="Just print the plain page file.", - ) + parser.add_argument('-m', '--markdown', + default=False, + action='store_true', + help='Just print the plain page file.') parser.add_argument( - "command", type=str, nargs="*", help="command to lookup", metavar="command" + 'command', type=str, nargs='*', help="command to lookup", metavar='command' ).complete = {"bash": "shtab_tldr_cmd_list", "zsh": "shtab_tldr_cmd_list"} - shtab.add_argument_to( - parser, - preamble={ - "bash": r"""shtab_tldr_cmd_list(){{ + shtab.add_argument_to(parser, preamble={ + 'bash': r'''shtab_tldr_cmd_list(){{ compgen -W "$("{py}" -m tldr --list | sed 's/[^[:alnum:]_]/ /g')" -- "$1" - }}""".format( - py=sys.executable - ), - "zsh": r"""shtab_tldr_cmd_list(){{ + }}'''.format(py=sys.executable), + 'zsh': r'''shtab_tldr_cmd_list(){{ _describe 'command' "($("{py}" -m tldr --list | sed 's/[^[:alnum:]_]/ /g'))" - }}""".format( - py=sys.executable - ), - }, - ) + }}'''.format(py=sys.executable) + }) return parser @@ -587,20 +560,18 @@ def main() -> None: parser.print_help(sys.stderr) sys.exit(1) if options.list: - print("\n".join(get_commands(options.platform))) + print('\n'.join(get_commands(options.platform))) elif options.render: for command in options.command: if os.path.exists(command): - with open(command, encoding="utf-8") as open_file: - output( - open_file.read().encode("utf-8").splitlines(), - plain=options.markdown, - ) + with open(command, encoding='utf-8') as open_file: + output(open_file.read().encode('utf-8').splitlines(), + plain=options.markdown) elif options.search: - command = "-".join(options.command) + command = '-'.join(options.command) page = None maxprob = 0 - searchquery = options.search.split(" ") + searchquery = options.search.split(' ') platforms = get_platform_list() for i in get_commands(platforms): @@ -637,28 +608,25 @@ def main() -> None: else: try: - command = "-".join(options.command).lower() + command = '-'.join(options.command).lower() results = get_page_for_every_platform( - command, options.source, options.platform, options.language + command, + options.source, + options.platform, + options.language ) if not results: - sys.exit( - ( - "`{cmd}` documentation is not available.\n" - "If you want to contribute it, feel free to" - " send a pull request to: https://github.com/tldr-pages/tldr" - ).format(cmd=command) - ) + sys.exit(( + "`{cmd}` documentation is not available.\n" + "If you want to contribute it, feel free to" + " send a pull request to: https://github.com/tldr-pages/tldr" + ).format(cmd=command)) else: output(results[0][0], plain=options.markdown) if results[1:]: platforms_str = [result[1] for result in results[1:]] single = len(platforms_str) == 1 - print( - f"There {'is' if single else 'are'} other version" - "{'' if single else 's'} of this page under the following" - "platform{'' if single else 's'}: {', '.join(platforms_str)}." - ) + print(f"There {'is' if single else 'are'} other version{'' if single else 's'} of this page under the following platform{'' if single else 's'}: {', '.join(platforms_str)}.") except URLError as e: sys.exit("Error fetching from tldr: {}".format(e)) From 8c8a5bca8284ea3c3fb8f25e8a9c4869dddbacf4 Mon Sep 17 00:00:00 2001 From: Vitor Henrique <87824454+vitorhcl@users.noreply.github.com> Date: Fri, 23 Feb 2024 10:55:17 -0300 Subject: [PATCH 7/9] fix: revert black --- tldr.py | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/tldr.py b/tldr.py index 9216437..27d12c1 100755 --- a/tldr.py +++ b/tldr.py @@ -252,13 +252,14 @@ def get_page_for_every_platform( if platform is None: continue try: - result.append(( get_page_for_platform( + result.append( + (get_page_for_platform( command, platform, remote, language, only_use_cache=True, - ), platform) + ), platform) ) break # Don't want to look for the same page in other langs except CacheNotExist: @@ -272,7 +273,17 @@ def get_page_for_every_platform( if platform is None: continue try: - result.append(( get_page_for_platform(command, platform, remote, language), platform)) + result.append( + ( + get_page_for_platform( + command, + platform, + remote, + language + ), + platform + ) + ) break except HTTPError as err: if err.code != 404: @@ -626,7 +637,11 @@ def main() -> None: if results[1:]: platforms_str = [result[1] for result in results[1:]] single = len(platforms_str) == 1 - print(f"There {'is' if single else 'are'} other version{'' if single else 's'} of this page under the following platform{'' if single else 's'}: {', '.join(platforms_str)}.") + print( + f"There {'is' if single else 'are'} other version" + "{'' if single else 's'} of this page under the following" + "platform{'' if single else 's'}: {', '.join(platforms_str)}." + ) except URLError as e: sys.exit("Error fetching from tldr: {}".format(e)) From f6a83d96e8d477c9c5a47ca08276eee1bdb5bb84 Mon Sep 17 00:00:00 2001 From: "K.B.Dharun Krishna" Date: Wed, 5 Jun 2024 15:40:15 +0530 Subject: [PATCH 8/9] fix: string formatting of msg Signed-off-by: K.B.Dharun Krishna --- tldr.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tldr.py b/tldr.py index 489def1..be2785f 100755 --- a/tldr.py +++ b/tldr.py @@ -630,8 +630,9 @@ def main() -> None: single = len(platforms_str) == 1 print( f"There {'is' if single else 'are'} other version" - "{'' if single else 's'} of this page under the following" - "platform{'' if single else 's'}: {', '.join(platforms_str)}." + f"{'s' if not single else ''} of this page under the " + f"following platform{'s' if not single else ''}: " + f"{', '.join(platforms_str)}." ) except URLError as e: sys.exit("Error fetching from tldr: {}".format(e)) From 432006dba94532db543b108960f05e571a3478dc Mon Sep 17 00:00:00 2001 From: "K.B.Dharun Krishna" Date: Thu, 6 Jun 2024 10:41:39 +0530 Subject: [PATCH 9/9] cleanup: update print msg section Signed-off-by: K.B.Dharun Krishna --- tldr.py | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/tldr.py b/tldr.py index be2785f..4a88c0f 100755 --- a/tldr.py +++ b/tldr.py @@ -627,13 +627,17 @@ def main() -> None: output(results[0][0], plain=options.markdown) if results[1:]: platforms_str = [result[1] for result in results[1:]] - single = len(platforms_str) == 1 - print( - f"There {'is' if single else 'are'} other version" - f"{'s' if not single else ''} of this page under the " - f"following platform{'s' if not single else ''}: " - f"{', '.join(platforms_str)}." - ) + are_multiple_platforms = len(platforms_str) > 1 + if are_multiple_platforms: + print( + f"Found {len(platforms_str)} pages with the same name" + f" under the platforms: {', '.join(platforms_str)}." + ) + else: + print( + f"Found 1 page with the same name" + f" under the platform: {platforms_str[0]}." + ) except URLError as e: sys.exit("Error fetching from tldr: {}".format(e))