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 23 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://tldr-pages.github.io/assets/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 `{{[*|*]}}` pattern to let the client decice whether to show shortfrom or longform versions of options. This can be configured with `TLDR_OPTIONS` and it 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, True, True)

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(), True, True, plain=True)

sys.stdout.seek(0)
tldr_output = sys.stdout.read().encode("utf-8")
Expand Down
41 changes: 38 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, short: bool, long: bool, 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,13 @@ 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 not (short and long):
if short:
line = re.sub(r'{{\[([^|]+)\|[^|]+?\]}}', r'\1', line)
elif 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 +610,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 +640,23 @@ def main() -> None:
parser = create_parser()

options = parser.parse_args()

short = False
long = True
if not (options.short_options or options.long_options):
if os.environ.get('TLDR_OPTIONS') == "short":
short = True
long = False
elif os.environ.get('TLDR_OPTIONS') == "long":
short = False
long = True
elif os.environ.get('TLDR_OPTIONS') == "both":
short = True
long = True
if options.short_options:
short = True
long = False
if options.long_options:
long = True
colorama.init(strip=options.color)
if options.color is False:
os.environ["FORCE_COLOR"] = "true"
Expand All @@ -642,6 +675,8 @@ 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(),
short,
long,
plain=options.markdown)
elif options.search:
search_term = options.search.lower()
Expand Down Expand Up @@ -675,7 +710,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], short, long, plain=options.markdown)
if results[1:]:
platforms_str = [result[1] for result in results[1:]]
are_multiple_platforms = len(platforms_str) > 1
Expand Down