Skip to content

Implement option length selection with options and environment variables #259

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 26 commits into from
Mar 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ export TLDR_CACHE_ENABLED=1
export TLDR_CACHE_MAX_AGE=720
export TLDR_PAGES_SOURCE_LOCATION="https://raw.githubusercontent.com/tldr-pages/tldr/main/pages"
export TLDR_DOWNLOAD_CACHE_LOCATION="https://github.com/tldr-pages/tldr/releases/latest/download/tldr.zip"
export TLDR_OPTIONS=short
```

### Cache
Expand Down Expand Up @@ -180,3 +181,7 @@ can either use the `--source` flag when using tldr or by specifying the followin
- it can also point to a local directory using `file:///path/to/directory`.
- `TLDR_DOWNLOAD_CACHE_LOCATION` to control where to pull a zip of all pages from.
- defaults to `https://github.com/tldr-pages/tldr/releases/latest/download/tldr.zip`.

### Command options

Pages might contain `{{[*|*]}}` patterns to let the client decide whether to show shortform or longform versions of options. This can be configured with `TLDR_OPTIONS`, which accepts values `short`, `long` and `both`
4 changes: 2 additions & 2 deletions tests/test_tldr.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def test_whole_page(page_name, monkeypatch):
sys.stdout = io.StringIO()
sys.stdout.buffer = types.SimpleNamespace()
sys.stdout.buffer.write = lambda x: sys.stdout.write(x.decode("utf-8"))
tldr.output(f_original)
tldr.output(f_original, "both")

sys.stdout.seek(0)
tldr_output = sys.stdout.read().encode("utf-8")
Expand All @@ -39,7 +39,7 @@ def test_markdown_mode(page_name):
sys.stdout = io.StringIO()
sys.stdout.buffer = types.SimpleNamespace()
sys.stdout.buffer.write = lambda x: sys.stdout.write(x.decode("utf-8"))
tldr.output(d_original.splitlines(), plain=True)
tldr.output(d_original.splitlines(), "both", plain=True)

sys.stdout.seek(0)
tldr_output = sys.stdout.read().encode("utf-8")
Expand Down
36 changes: 33 additions & 3 deletions tldr.py
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,7 @@ def colors_of(key: str) -> Tuple[str, str, List[str]]:
return (color, on_color, attrs)


def output(page: str, plain: bool = False) -> None:
def output(page: str, display_option_length: str, plain: bool = False) -> None:
def emphasise_example(x: str) -> str:
# Use ANSI escapes to enable italics at the start and disable at the end
# Also use the color yellow to differentiate from the default green
Expand Down Expand Up @@ -478,6 +478,12 @@ def emphasise_example(x: str) -> str:
line = line.replace(r'\{\{', '__ESCAPED_OPEN__')
line = line.replace(r'\}\}', '__ESCAPED_CLOSE__')

# Extract long or short options from placeholders
if display_option_length == "short":
line = re.sub(r'{{\[([^|]+)\|[^|]+?\]}}', r'\1', line)
elif display_option_length == "long":
line = re.sub(r'{{\[[^|]+\|([^|]+?)\]}}', r'\1', line)

elements = [' ' * 2 * LEADING_SPACES_NUM]
for item in COMMAND_SPLIT_REGEX.split(line):
item, replaced = PARAM_REGEX.subn(
Expand Down Expand Up @@ -603,6 +609,16 @@ def create_parser() -> ArgumentParser:
action='store_true',
help='Just print the plain page file.')

parser.add_argument('--short-options',
default=False,
action="store_true",
help='Display shortform options over longform')

parser.add_argument('--long-options',
default=False,
action="store_true",
help='Display longform options over shortform')

parser.add_argument(
'command', type=str, nargs='*', help="command to lookup", metavar='command'
).complete = {"bash": "shtab_tldr_cmd_list", "zsh": "shtab_tldr_cmd_list"}
Expand All @@ -623,7 +639,20 @@ def main() -> None:
parser = create_parser()

options = parser.parse_args()

display_option_length = "long"
if not (options.short_options or options.long_options):
if os.environ.get('TLDR_OPTIONS') == "short":
display_option_length = "short"
elif os.environ.get('TLDR_OPTIONS') == "long":
display_option_length = "long"
elif os.environ.get('TLDR_OPTIONS') == "both":
display_option_length = "both"
if options.short_options:
display_option_length = "short"
if options.long_options:
display_option_length = "long"
if options.short_options and options.long_options:
display_option_length = "both"
colorama.init(strip=options.color)
if options.color is False:
os.environ["FORCE_COLOR"] = "true"
Expand All @@ -642,6 +671,7 @@ def main() -> None:
if file_path.exists():
with file_path.open(encoding='utf-8') as open_file:
output(open_file.read().encode('utf-8').splitlines(),
display_option_length,
plain=options.markdown)
elif options.search:
search_term = options.search.lower()
Expand Down Expand Up @@ -675,7 +705,7 @@ def main() -> None:
" send a pull request to: https://github.com/tldr-pages/tldr"
).format(cmd=command))
else:
output(results[0][0], plain=options.markdown)
output(results[0][0], display_option_length, plain=options.markdown)
if results[1:]:
platforms_str = [result[1] for result in results[1:]]
are_multiple_platforms = len(platforms_str) > 1
Expand Down