Compare commits

...

191 commits

Author SHA1 Message Date
Niklas Mohrin
37b0dee39f
Support XDG directory spec on macOS by switching app_dirs2 to etcetera (#467)
Closes #311

Similar to how `bat` does it, we now have a global struct which holds
all the queried system directories. We prefer the XDG directories, but
use the "native" directories as a fallback. This should ensure that when
MacOs users upgrade from an older version, their existing config and
cache are still used. After deleting the old directories, the new ones
should be used by tealdeer automatically.
2026-08-06 00:37:37 +02:00
Niklas Mohrin
28ed785001
Fix 1.97 clippy lints 2026-07-26 23:52:43 +02:00
Nikolaos Karaolidis
f8a2003bc2
Add updates.warn_cache_age config option (#492)
This is useful when the cache is managed externally, e.g. provisioned
from a Nix store path or by a package manager, where the directory's
mtime doesn't reflect the cache's real age, causing a spurious warning
on every invocation. Today the only way to silence it is `--quiet`,
which must be passed every call and hides all other output too.
2026-07-07 14:24:06 +02:00
RedHare
df5113ddaa
Added AI Policy to README (#489)
Addresses #479, and adds a section for an AI policy based on what is
outlined by @niklasmohrin in that issue. The AI Policy is located below
the "Development" section.
2026-07-04 23:05:15 +02:00
dependabot[bot]
51593d27eb
Bump actions/checkout from 6 to 7 (#493) 2026-07-04 22:59:46 +02:00
xtqqczze
d0108b23e4
Fix clippy lints on all targets (#481) 2026-05-07 15:07:27 +02:00
xtqqczze
4d33e8a279
Remove tldr-c entry from benchmark results in README.md (#480)
`tldr-c-client` is unmaintained.
2026-05-06 16:36:37 +02:00
Ellis Clayton
1252261d66
Support tilde (~) expansion on config paths (#476)
Allows directories in the configuration file (cache & custom pages) to
be relative to the user's home directory by expanding the common `~`
path prefix notation. Works for the current user only (`~diferentUser/`
syntax is not supported, and will cause an error if attempted).

Works for Linux/Unix (via `HOME` env var) and Windows (via `USERPROFILE`
env var).

Examples (assuming a user called "foo" on a Linux system):

```
~/my/custom-pages # /home/foo/custom-pages
~ # /home/foo
~bar/cache # error
```
2026-05-03 21:47:29 +02:00
Niklas Mohrin
24e7f383b8
Fix Rust 1.95 clippy lints 2026-04-17 22:08:42 +02:00
Niklas Mohrin
6c65c8f71c
Fix off-boundary string access in formatter (#474)
Closes #473

This regression was introduced in
593e9309b9 (#414) and leads to a panic
when trying to display pages where characters line up like in the issue
or the test. I checked other places and found that a similar panic could
occur when parsing language strings, so I added code to ignore them
instead.

- Add regression test
- Fix prefix check
- Skip non-ASCII locales
2026-04-17 22:01:45 +02:00
Pavel Timofeev
b8f7c0cc2d
Add display.indent config option (#471)
Fixes #394.
2026-04-17 21:59:34 +02:00
Pavel Timofeev
b19517097a
Add builtin tldr tealdeer page (#472)
Fixes #218.
2026-04-14 00:31:31 +02:00
dependabot[bot]
6f91c3a765
Bump actions/download-artifact from 7 to 8 (#469)
Bumps
[actions/download-artifact](https://github.com/actions/download-artifact)
from 7 to 8.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/actions/download-artifact/releases">actions/download-artifact's
releases</a>.</em></p>
<blockquote>
<h2>v8.0.0</h2>
<h2>v8 - What's new</h2>
<h3>Direct downloads</h3>
<p>To support direct uploads in <code>actions/upload-artifact</code>,
the action will no longer attempt to unzip all downloaded files.
Instead, the action checks the <code>Content-Type</code> header ahead of
unzipping and skips non-zipped files. Callers wishing to download a
zipped file as-is can also set the new <code>skip-decompress</code>
parameter to <code>false</code>.</p>
<h3>Enforced checks (breaking)</h3>
<p>A previous release introduced digest checks on the download. If a
download hash didn't match the expected hash from the server, the action
would log a warning. Callers can now configure the behavior on mismatch
with the <code>digest-mismatch</code> parameter. To be secure by
default, we are now defaulting the behavior to <code>error</code> which
will fail the workflow run.</p>
<h3>ESM</h3>
<p>To support new versions of the @actions/* packages, we've upgraded
the package to ESM.</p>
<h2>What's Changed</h2>
<ul>
<li>Don't attempt to un-zip non-zipped downloads by <a
href="https://github.com/danwkennedy"><code>@​danwkennedy</code></a> in
<a
href="https://redirect.github.com/actions/download-artifact/pull/460">actions/download-artifact#460</a></li>
<li>Add a setting to specify what to do on hash mismatch and default it
to <code>error</code> by <a
href="https://github.com/danwkennedy"><code>@​danwkennedy</code></a> in
<a
href="https://redirect.github.com/actions/download-artifact/pull/461">actions/download-artifact#461</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/actions/download-artifact/compare/v7...v8.0.0">https://github.com/actions/download-artifact/compare/v7...v8.0.0</a></p>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="70fc10c6e5"><code>70fc10c</code></a>
Merge pull request <a
href="https://redirect.github.com/actions/download-artifact/issues/461">#461</a>
from actions/danwkennedy/digest-mismatch-behavior</li>
<li><a
href="f258da9a50"><code>f258da9</code></a>
Add change docs</li>
<li><a
href="ccc058e5fb"><code>ccc058e</code></a>
Fix linting issues</li>
<li><a
href="bd7976ba57"><code>bd7976b</code></a>
Add a setting to specify what to do on hash mismatch and default it to
<code>error</code></li>
<li><a
href="ac21fcf45e"><code>ac21fcf</code></a>
Merge pull request <a
href="https://redirect.github.com/actions/download-artifact/issues/460">#460</a>
from actions/danwkennedy/download-no-unzip</li>
<li><a
href="15999bff51"><code>15999bf</code></a>
Add note about package bumps</li>
<li><a
href="974686ed50"><code>974686e</code></a>
Bump the version to <code>v8</code> and add release notes</li>
<li><a
href="fbe48b1d27"><code>fbe48b1</code></a>
Update test names to make it clearer what they do</li>
<li><a
href="96bf374a61"><code>96bf374</code></a>
One more test fix</li>
<li><a
href="b8c4819ef5"><code>b8c4819</code></a>
Fix skip decompress test</li>
<li>Additional commits viewable in <a
href="https://github.com/actions/download-artifact/compare/v7...v8">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=actions/download-artifact&package-manager=github_actions&previous-version=7&new-version=8)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)


</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-03-02 14:53:06 +01:00
dependabot[bot]
41739c5bf9
Bump actions/upload-artifact from 6 to 7 (#468)
Bumps
[actions/upload-artifact](https://github.com/actions/upload-artifact)
from 6 to 7.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/actions/upload-artifact/releases">actions/upload-artifact's
releases</a>.</em></p>
<blockquote>
<h2>v7.0.0</h2>
<h2>v7 What's new</h2>
<h3>Direct Uploads</h3>
<p>Adds support for uploading single files directly (unzipped). Callers
can set the new <code>archive</code> parameter to <code>false</code> to
skip zipping the file during upload. Right now, we only support single
files. The action will fail if the glob passed resolves to multiple
files. The <code>name</code> parameter is also ignored with this
setting. Instead, the name of the artifact will be the name of the
uploaded file.</p>
<h3>ESM</h3>
<p>To support new versions of the <code>@actions/*</code> packages,
we've upgraded the package to ESM.</p>
<h2>What's Changed</h2>
<ul>
<li>Add proxy integration test by <a
href="https://github.com/Link"><code>@​Link</code></a>- in <a
href="https://redirect.github.com/actions/upload-artifact/pull/754">actions/upload-artifact#754</a></li>
<li>Upgrade the module to ESM and bump dependencies by <a
href="https://github.com/danwkennedy"><code>@​danwkennedy</code></a> in
<a
href="https://redirect.github.com/actions/upload-artifact/pull/762">actions/upload-artifact#762</a></li>
<li>Support direct file uploads by <a
href="https://github.com/danwkennedy"><code>@​danwkennedy</code></a> in
<a
href="https://redirect.github.com/actions/upload-artifact/pull/764">actions/upload-artifact#764</a></li>
</ul>
<h2>New Contributors</h2>
<ul>
<li><a href="https://github.com/Link"><code>@​Link</code></a>- made
their first contribution in <a
href="https://redirect.github.com/actions/upload-artifact/pull/754">actions/upload-artifact#754</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/actions/upload-artifact/compare/v6...v7.0.0">https://github.com/actions/upload-artifact/compare/v6...v7.0.0</a></p>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="bbbca2ddaa"><code>bbbca2d</code></a>
Support direct file uploads (<a
href="https://redirect.github.com/actions/upload-artifact/issues/764">#764</a>)</li>
<li><a
href="589182c5a4"><code>589182c</code></a>
Upgrade the module to ESM and bump dependencies (<a
href="https://redirect.github.com/actions/upload-artifact/issues/762">#762</a>)</li>
<li><a
href="47309c993a"><code>47309c9</code></a>
Merge pull request <a
href="https://redirect.github.com/actions/upload-artifact/issues/754">#754</a>
from actions/Link-/add-proxy-integration-tests</li>
<li><a
href="02a8460834"><code>02a8460</code></a>
Add proxy integration test</li>
<li>See full diff in <a
href="https://github.com/actions/upload-artifact/compare/v6...v7">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=actions/upload-artifact&package-manager=github_actions&previous-version=6&new-version=7)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)


</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-03-02 14:52:53 +01:00
Niklas Mohrin
47a936e736
Suggest trying different TLS backend when update fails (#465)
Closes #453

- Add note about changing tls_backend setting
- impl Display for TlsBackend
- Remove trailing slash in default archive source to make URL in error
look nicer
2026-02-21 00:32:23 +01:00
Niklas Mohrin
593e9309b9
Placeholder escaping (#414)
Closes #402

This adds special handling for escaped placeholders as required by the
client spec. The added tests include examples from current pages that
rely on this behavior.

The text replacements use `str::replace` which constructs a new
allocated `String`. I considered using a custom `replace_inplace` method
on `&mut str` (which works if the replacement string is at most as long
as the pattern to be replaced), but decided against it because I think
that the performance improvement is not significant enough to justify
adding `unsafe` code. It is also possible to avoid `unsafe` by
re-checking UTF-8 validity after all modifications, but the code still
felt a bit out of place for tealdeer. We can always add these
optimizations later if we want to.
2026-02-20 23:44:36 +01:00
Niklas Mohrin
8b97afe7aa
Add workflow_dispatch trigger for GitHub Pages workflow 2026-01-25 18:39:52 +01:00
Niklas Mohrin
75e5462312
Update CHANGELOG.md 2026-01-25 18:29:32 +01:00
dependabot[bot]
5ee1f28021
Bump actions/upload-artifact from 5 to 6 (#456)
Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 5 to 6.
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/v5...v6)

---
updated-dependencies:
- dependency-name: actions/upload-artifact
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-01-01 18:55:53 +01:00
dependabot[bot]
3a6fd99c85
Bump actions/download-artifact from 6 to 7 (#457)
Bumps [actions/download-artifact](https://github.com/actions/download-artifact) from 6 to 7.
- [Release notes](https://github.com/actions/download-artifact/releases)
- [Commits](https://github.com/actions/download-artifact/compare/v6...v7)

---
updated-dependencies:
- dependency-name: actions/download-artifact
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-01-01 18:55:41 +01:00
dependabot[bot]
c5d62e5987
Bump actions/checkout from 5 to 6 (#454)
Bumps [actions/checkout](https://github.com/actions/checkout) from 5 to 6.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v5...v6)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-12-01 20:32:38 +01:00
Niklas Mohrin
b3cd7b1c21
Release v1.8.1 2025-11-11 22:27:52 +01:00
Niklas Mohrin
e769114d8b
Enable ureq's socks-proxy feature (#451) 2025-11-11 17:33:19 +01:00
dependabot[bot]
e1213158e4
Bump actions/upload-artifact from 4 to 5 (#447)
Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 4 to 5.
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/upload-artifact
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-11-02 00:19:23 +01:00
dependabot[bot]
6c1d702769
Bump actions/download-artifact from 5 to 6 (#448)
Bumps [actions/download-artifact](https://github.com/actions/download-artifact) from 5 to 6.
- [Release notes](https://github.com/actions/download-artifact/releases)
- [Commits](https://github.com/actions/download-artifact/compare/v5...v6)

---
updated-dependencies:
- dependency-name: actions/download-artifact
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-11-02 00:18:45 +01:00
Niklas Mohrin
d49c4a9e05
Release v1.8.0 2025-10-03 22:59:18 +02:00
Niklas Mohrin
49626977ff
Run cargo +nightly clippy --fix and formatting (#442) 2025-10-03 22:44:39 +02:00
Niklas Mohrin
9a83b58d51
Bump MSRV to 1.85 and update dependencies (#441)
The latest version of base64ct requires 1.85, and I don't want to think about whether older versions of crypto libraries are safe.
2025-10-03 22:38:02 +02:00
Niklas Mohrin
2b127fd67e
Highlight code examples in user docs (#440)
* Highlight code examples in user docs
* Add missing quotes to archive_source example
2025-10-03 20:59:22 +02:00
Niklas Mohrin
911508ce33
Add search.platforms config option and search all platforms by default (#435) 2025-10-03 20:15:34 +02:00
hex1c
5b306756af
Add display.show_title option to display command titles in output (#439) 2025-10-03 19:53:25 +02:00
Niklas Mohrin
abb7e8ac55
Remove native-tls from default feature set (#436) 2025-09-22 16:06:36 +02:00
Niklas Mohrin
92b6c64c87
Merge pull request #430 from niklasmohrin/language-config
Add `search.languages` and `updates.download_languages` settings
2025-09-22 00:05:24 +02:00
Niklas Mohrin
c741146db5
Add updates.download_languages setting 2025-09-22 00:00:09 +02:00
Niklas Mohrin
a74b7120bd
Add search.languages setting 2025-09-21 23:59:50 +02:00
Niklas Mohrin
3fa96a5bb2
Add test config::test::language::with_encoding 2025-09-21 23:59:13 +02:00
Niklas Mohrin
7e014093cf
Move existing tests from config module into test submodule 2025-09-21 23:59:13 +02:00
Niklas Mohrin
94f9030d36
Move Language related functionality into config module 2025-09-21 23:59:05 +02:00
dependabot[bot]
5cfb817e99
Bump actions/download-artifact from 4 to 5 (#433)
Bumps [actions/download-artifact](https://github.com/actions/download-artifact) from 4 to 5.
- [Release notes](https://github.com/actions/download-artifact/releases)
- [Commits](https://github.com/actions/download-artifact/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/download-artifact
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Niklas Mohrin <dev@niklasmohrin.de>
2025-09-03 17:17:51 +02:00
dependabot[bot]
4377366c97
Bump actions/checkout from 4 to 5 (#434)
Bumps [actions/checkout](https://github.com/actions/checkout) from 4 to 5.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-09-03 16:52:36 +02:00
Niklas Mohrin
630b7f4423
Allow references in Config (#429)
For #251, I want to use the `Language<'_>` type inside `Config`. The languages will either refer to values read from the config file, or to static strings from `get_languages_from_env`, so just using `Language<'static>` is not an option.

Instead, some input for the `Config` needs to be persisted in the main function for the duration of the program so that the config can reference it. At first I was hoping that this input would be the `contents` string from `RawConfig::load`, but as it turns out you cannot (in general) deserialize strings from toml without having to alter them, for example when they contain escapes like `\n`. Thus, the toml parser seemingly doesn't even try and just throws an error when deserializing into a borrowed string (even if it could in theory just return the correct substring from the input). Given that `RawConfig` should stay static then, the raw config itself is the next best thing to keep alive and have the config reference into.

While this change might seem a bit drastic for little benefit, I am actually pretty happy with it because I want to unify the configuration anyways at some point so that the CLI arguments, environment variables, and the config file are merged at the beginning of the program and then only a single config is used for the everything (no more `enable_styles` everywhere!). At this time, the `Config` would have references into `Cli` anyways, and having the `ConfigLoader` as an entity for this merging also seems natural.
2025-08-05 23:46:49 +02:00
Niklas Mohrin
1e87db7ab7
Cache rewrite (#416) 2025-08-01 16:03:01 +02:00
Niklas Mohrin
d1be7d6bb9
Introduce Language struct (#425)
* Remove unneeded Clone bound on Dedup
* Introduce Language struct to represent language strings
* Move language directory name logic into own method on Language type
2025-06-06 23:25:30 +02:00
Niklas Mohrin
43ab2cb920
Bump MSRV to 1.80 (#426) 2025-06-06 23:13:47 +02:00
Niklas Mohrin
bc820c5f10
Upload binaries from build step as artifact (#423) 2025-06-06 22:52:44 +02:00
MHS-0
9bb95ad11d
Add an option to specify a custom config file to be used (#422)
Co-authored-by: Niklas Mohrin <dev@niklasmohrin.de>
2025-05-31 21:43:39 +02:00
Niklas Mohrin
769ef4da20
Merge branch 'v1.7.x' 2025-03-18 23:51:51 +01:00
Niklas Mohrin
8f433e7774
Release v1.7.2 2025-03-18 23:38:12 +01:00
Niklas Mohrin
81a0662dbc
Run CI on backport branches and on dispatch 2025-03-18 23:04:24 +01:00
Niklas Mohrin
9f43adb7f9
Require zip >= 2.3.0 2025-03-18 22:58:26 +01:00
Erick Guan
3d8d488f66
Replace reqwest with ureq (#417)
ureq is a blocking HTTP client. ureq is simpler than reqwest. This
brings:
- smaller binary size
- cleaner configuration interfaces
2025-03-09 22:06:47 +01:00
Nachiket Kanore
c6de583c46
Only create a single temporary directory in integration tests (#411) 2025-03-02 12:03:09 +01:00
Niklas Mohrin
009af7063f
Move most of main to try_main (#400)
Currently, `main` uses `print_error` and `process::exit` in several
places. These could be unified by propagating errors via `Result`s.
There is one place left that manually calls `print_error`, because the
error should be followed by help instructions printed without any
highlighting.
2025-02-26 23:04:41 +01:00
lyj
55f401df30
Add args: --edit-page and --edit-patch (#388)
Fix https://github.com/tealdeer-rs/tealdeer/issues/383

Co-authored-by: Niklas Mohrin <dev@niklasmohrin.de>
2025-02-26 22:03:18 +01:00
Erick Guan
09ef7f534e
Allow configuring TLS backend (#386) 2025-02-26 00:27:44 +01:00
Predrag Minic
120e2a92c2
Add configuration option for archive_source (#337)
This allows for specifying a custom archive URL as an alternative approach to Custom Pages.

Co-authored-by: Niklas Mohrin <dev@niklasmohrin.de>
2025-01-12 12:24:02 +01:00
Christoph Loy
09d44110f8
Add tests for osx/macos alias (#407)
Co-authored-by: Niklas Mohrin <dev@niklasmohrin.de>
2025-01-12 12:04:22 +01:00
Christoph Loy
b9f116d629
Add common platform to CLI (#401) 2025-01-12 11:50:32 +01:00
Matěj Kafka
00c7778125
Resolve paths in config [directories] relative to the config directory (#395) 2025-01-05 00:17:44 +01:00
Niklas Mohrin
826630737c
Merge pull request #399 from niklasmohrin/tests
Various test improvements
2025-01-03 00:36:56 +01:00
Niklas Mohrin
dbab55a2b4
Use only one test thread
Otherwise the builds made by `TestEnv::command` will conflict with each
other. This manifested itself on Windows with

> linking with `link.exe` failed: exit code: 1104
> LINK : fatal error LNK1104: cannot open file '...'
2025-01-02 23:55:36 +01:00
Niklas Mohrin
e7b434d06a
Prefer config file over TEALDEER_CACHE_DIR in integration tests 2025-01-02 23:55:36 +01:00
Niklas Mohrin
fc19206029
Add ignore-online-tests feature
Since these tests require internet access, they are undesirable in
reproducible builds [1] (and in general, I guess). The overall goal is
to shrink this list to a minimum. At some point we might remove the
feature again and ignore online tests by default. Before putting much
thought into refactoring the remaining tests, we should wait until we
have introduced the `updates.archive_url` option. Then, we could run a
local webserver that serves a known file. Until then, having the feature
already helps discourage using `--update` in tests that don't need it
and allows for quicker test execution locally if wanted.

- [1]: edf04b75c1/pkgs/by-name/te/tealdeer/package.nix (L34-L44)
2025-01-02 23:55:36 +01:00
Niklas Mohrin
e85de336ed
Structure test fixtures like page cache 2025-01-02 23:55:35 +01:00
Niklas Mohrin
909bad9c65
Fix feature selection in integration tests 2025-01-02 23:55:35 +01:00
Niklas Mohrin
ceee231891
Merge pull request #398 from niklasmohrin/dependencies
Update dependencies to hush dependabot
2025-01-01 19:33:59 +01:00
Niklas Mohrin
0c55a4b82a
Run cargo update --recursive -p rustls 2025-01-01 19:22:25 +01:00
Niklas Mohrin
e3a06eefe3
Run cargo update -p hashbrown 2025-01-01 19:21:36 +01:00
Niklas Mohrin
6869837e79
Run cargo update -p url to bump idna 2025-01-01 19:21:04 +01:00
Niklas Mohrin
ee5418b5a8
Run cargo clippy --fix (Rust 1.83) (#397) 2025-01-01 19:07:40 +01:00
Niklas Mohrin
1d9153e37e
Release v1.7.1 2024-11-14 22:11:34 +01:00
Niklas Mohrin
d719f21f7b
Bump futures-util (0.3.30 is yanked) 2024-11-14 21:59:23 +01:00
Blair Noctis
fb7492b0b5
Upgrade yansi: 0.5.1 -> 1.0.1 (#389)
- Adapt to `thing.paint(style)` API; was `style.paint(thing)`
- Remove `yansi::Paint::enable_windows_ascii()` in style usage decision;
  removed in yansi commit b186eb5bfb, which introduced "automatic"
  support for Windows: "If support is not available, styling is disabled
  and no styling sequences are emitted", fitting the `Auto` option
- Respect `--color=always` even if we know it won't work

---------

Co-authored-by: Niklas Mohrin <dev@niklasmohrin.de>
2024-11-14 16:07:30 +01:00
Danilo Bargen
d44613cf59 Release v1.7.0 2024-10-02 23:02:32 +02:00
Danilo Bargen
713f6f913c
Run cargo update (#381) 2024-10-02 22:44:22 +02:00
Niklas Mohrin
ec2daa495c
Replace atty with std::io::IsTerminal (#380) 2024-10-02 20:32:17 +00:00
Danilo Bargen
fc6d644152
Update all URLs to point to new GitHub organization (#379)
See https://github.com/tealdeer-rs/tealdeer/issues/376 for details.
2024-09-30 11:27:19 +02:00
Danilo Bargen
8995f9f07e
Merge pull request #374 from dbrgn/updates-20240812
Update Dependencies
2024-08-13 00:15:16 +02:00
Danilo Bargen
7c245040b9
Command line help: Add hint about platform overrides (#375)
- Rename PLATFORMS to PLATFORM
- Add hint about specifying platform multiple times
2024-08-13 00:14:19 +02:00
Danilo Bargen
4f51ba090f Upgrade zip: 0.6.6 → 2.1.6 2024-08-12 23:09:55 +02:00
Danilo Bargen
60855cedcf Upgrade toml: 0.5.11 → 0.8.19 2024-08-12 23:02:28 +02:00
Danilo Bargen
9096d536b1 Upgrade reqwest: 0.11.27 → 0.12.5 2024-08-12 23:02:22 +02:00
Danilo Bargen
13a3d58c8b Upgrade predicates: 2.1.5 → 3.1.2 2024-08-12 22:57:32 +02:00
Danilo Bargen
13f2c4c714 Upgrade env_logger: 0.10 → 0.11 2024-08-12 22:54:58 +02:00
Danilo Bargen
65495da5a5 Run cargo update 2024-08-12 22:54:03 +02:00
Danilo Bargen
f3d74850a8
Make clippy happy (#373) 2024-08-06 21:46:40 +00:00
Danilo Bargen
290afe385d
Merge pull request #368 from dbrgn/365-apple-silicon-builds
CI: Create release builds for Apple silicon (ARM)
2024-06-17 01:28:56 +02:00
Danilo Bargen
7620a67306 CI: Set name for every workflow 2024-06-17 01:07:29 +02:00
Danilo Bargen
706c1408a7 CI: Don't publish docs for 0.x test releases 2024-06-17 01:02:26 +02:00
Danilo Bargen
64f90a625e CI: Create release builds for Apple silicon (ARM) 2024-06-17 00:59:42 +02:00
Danilo Bargen
83b2bdaf33
Merge pull request #298 from dbrgn/clap-v4
Migrate to Clap v4, bump MSRV to 1.75
2024-06-17 00:44:53 +02:00
Danilo Bargen
64f3fbbbc6 Apply clippy suggestions 2024-06-17 00:35:04 +02:00
Danilo Bargen
86293c8723 Bump MSRV to 1.75 2024-06-17 00:35:04 +02:00
Danilo Bargen
de1684edb6 Update to clap v4 2024-06-17 00:35:04 +02:00
Adam Henley
3a14232105
Generate docs only upon release (#362)
Signed-off-by: Adam Henley <adamazing@gmail.com>
2024-06-06 17:17:20 +02:00
dependabot[bot]
9957dcea74
Bump peaceiris/actions-mdbook from 1 to 2 (#360)
Bumps [peaceiris/actions-mdbook](https://github.com/peaceiris/actions-mdbook) from 1 to 2.
- [Release notes](https://github.com/peaceiris/actions-mdbook/releases)
- [Changelog](https://github.com/peaceiris/actions-mdbook/blob/main/CHANGELOG.md)
- [Commits](https://github.com/peaceiris/actions-mdbook/compare/v1...v2)

---
updated-dependencies:
- dependency-name: peaceiris/actions-mdbook
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-04-10 18:51:53 +02:00
dependabot[bot]
7633e46541
Bump peaceiris/actions-gh-pages from 3 to 4 (#359)
Bumps [peaceiris/actions-gh-pages](https://github.com/peaceiris/actions-gh-pages) from 3 to 4.
- [Release notes](https://github.com/peaceiris/actions-gh-pages/releases)
- [Changelog](https://github.com/peaceiris/actions-gh-pages/blob/main/CHANGELOG.md)
- [Commits](https://github.com/peaceiris/actions-gh-pages/compare/v3...v4)

---
updated-dependencies:
- dependency-name: peaceiris/actions-gh-pages
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-04-10 18:50:44 +02:00
K.B.Dharun Krishna
ee6d2418f1
Add BSD platform support and update workflows (#354) 2024-04-10 16:05:51 +02:00
Linus Walker
c8f2408373
Performance optimization with cargo flags (#355) 2024-03-03 18:35:09 +01:00
Zacchary Dempsey-Plante
17c08f0261
Change custom page files to use a .md extension (#322)
* Change custom page files to use a `.md` extension.
* Add a breaking change warning to the documentation for the usage of custom pages.
* Add a temporary check for old custom pages to assist in the migration to the new naming convention.

Co-authored-by: Danilo Bargen <mail@dbrgn.ch>
2024-02-15 19:27:56 +00:00
Zacchary Dempsey-Plante
ad69985e42
Update the Nix package link in the documentation (#353) 2024-02-11 20:58:06 +00:00
Danilo Bargen
2e731d7d17
Bump MSRV to 1.64 (#352) 2024-02-11 15:20:11 +01:00
Nicolai Fröhlich
d04e671c46
Add release build target "linux-aarch64-musl" for platform "linux/arm64" (#351) 2024-01-17 23:30:03 +01:00
Felix Yan
5bdcd6ae9c
Update Arch Linux package URL in installing.md (#348)
The old URL returns 404 now.
2023-11-21 12:34:22 +01:00
Niklas Mohrin
efbdebb426
Update Github actions badge (#346) 2023-10-21 14:51:16 +02:00
Niklas Mohrin
a82bc4b8d2
Add "Tips and Tricks" chapter to user manual (#342) 2023-10-02 21:06:09 +02:00
JJ Style
9e1489bbc5
Allow querying multiple platforms (#300) 2023-08-27 21:52:20 +00:00
Andrea Frigido
1764cee1bd
Cargo.toml: Update license field following SPDX 2.1 license expression standard (#336) 2023-08-13 19:13:06 +00:00
Niklas Mohrin
4d2fc26dbe
Include completion/* in published crate (#333) 2023-07-10 18:22:20 +02:00
K.B.Dharun Krishna
7bd5ac5664
Update CI workflows (#324) 2023-07-06 23:50:14 +02:00
Iliia Maleki
de9cf431a8
Completions: Add checks for wrong tldr --list output (#327) 2023-07-06 16:22:50 +02:00
Adam Henley
45b3db6dc4
Guard Fish completion when cache is empty (#331)
Signed-off-by: Adam Henley <adamazing@gmail.com>
2023-07-06 16:20:46 +02:00
qknogxxb
8c6754ae78
Line iterator: Improve test functions (#316) 2023-07-05 23:33:39 +02:00
Danilo Bargen
94d56c01a7
Allow building with native-tls (#303)
Right now we only support building with Rustls. However, there are quite
a few architectures that aren't yet supported by "ring" (the crypto
library used by Rustls), for example MIPS, PowerPC or SPARC.

To offer an alternative, I added the "native-tls" feature that can be
used instead of "native-roots". When used, the native TLS stack is used
instead of Rustls (i.e. SChannel on Windows, Secure Transport on macOS
and OpenSSL otherwise).
2023-02-14 18:21:07 +01:00
Danilo Bargen
84621cda81
Merge pull request #293 from dbrgn/documentation-fixes
Documentation fixes: Some leftovers, fixes and improvements.
2023-02-12 19:07:28 +01:00
Danilo Bargen
fb755ba8dc Docs: Consistent capitalization of tealdeer
Capitalize at the start of a sentence, lowercase otherwise.
2023-02-12 18:54:05 +01:00
Danilo Bargen
c9ec88354a Docs: Remove section about overriding cache dir
The env var `TEALDEER_CACHE_DIR` is deprecated. The new way to configure
the cache dir is documented in the "[directories]" section.
2023-02-12 18:49:39 +01:00
Danilo Bargen
74d1ade884 Docs: Mention building with bundled roots 2023-02-12 18:49:39 +01:00
Danilo Bargen
b07a6728f3 Docs: Remove note about OpenSSL
OpenSSL is not used anymore since version 1.5.0.
2023-02-12 18:49:39 +01:00
Danilo Bargen
2fa1994c76 CHANGELOG: Fix typo 2023-02-12 18:49:39 +01:00
qknogxxb
72362769de
Line iterator: Drop empty line without allocating (#314)
Co-authored-by: Niklas Mohrin <dev@niklasmohrin.de>
2023-02-12 17:45:53 +00:00
Blair Noctis
0c8cb42664
Docs: Add Debian to packaged list (#315) 2023-02-10 22:28:45 +00:00
tveness
76d9d0bbda
Obey 1.67 clippy lints (#313) 2023-02-07 21:56:41 +01:00
Y.D.X
c077ff05e4
Docs: Fix typo (irregular space → regular space) (#310)
It was a no-break space (U+00A0), which causes mdBook to ignore the line break and [render wrongly](https://dbrgn.github.io/tealdeer/installing.html#package-managers).

Instead, a regular space (U+0020) should be used.
2023-01-11 10:22:49 +00:00
Danilo Bargen
b5f2c6ff39 Upgrade env_logger: 0.9 → 0.10 2022-12-24 15:03:41 +01:00
Danilo Bargen
e75f814294 Run cargo update 2022-12-24 15:03:41 +01:00
Mohit Raj
fc8266d1c9
Docs: Add scoop package manager as supported installation method (#305) 2022-12-18 23:40:27 +01:00
Danilo Bargen
76bb4e72bc Update CHANGELOG
Forgot to add myself 🙃
2022-10-24 15:04:24 +02:00
Danilo Bargen
7c371a6852 Release v1.6.1 2022-10-24 14:42:37 +02:00
Danilo Bargen
b10f8a9485
Run cargo update (#299) 2022-10-22 20:24:57 +00:00
Danilo Bargen
ab5148f237
Fix path source for custom pages dir (#297) 2022-10-22 22:00:29 +02:00
Cyrus Yip
86c850282e
Docs: improve grammar (#296) 2022-10-11 12:08:41 +00:00
Danilo Bargen
357f0e7e71 Release v1.6.0 2022-10-02 00:36:58 +02:00
Danilo Bargen
7ded00eda0
Run cargo update (#291) 2022-10-01 22:23:26 +00:00
Danilo Bargen
6f72ce778d
Merge pull request #290 from dbrgn/remove-deprecated-commands
Remove deprecated commands
2022-10-02 00:05:00 +02:00
Danilo Bargen
2ebf86b265 Remove deprecated -m/--markdown command 2022-10-01 23:54:37 +02:00
Danilo Bargen
efe1b57696 Remove deprecated -o/--os command 2022-10-01 23:53:32 +02:00
Danilo Bargen
0c93a4cfe9 Remove deprecated --config-path command 2022-10-01 23:52:03 +02:00
Danilo Bargen
99c86a4aff
Merge pull request #276 from dbrgn/cache-dir-config
Allow overriding cache directory through config
2022-10-01 12:32:41 +02:00
Danilo Bargen
c44faf2b09 Lazy creation of cache directory 2022-10-01 12:18:44 +02:00
Danilo Bargen
3f528ba5cb Impl From<RawX> for more config types
- StyleConfig
- DisplayConfig
- UpdatesConfig
2022-10-01 12:18:34 +02:00
Danilo Bargen
d702a1fab6 Cache: Add pages_dir helper method
Additionally, rename `cache_dir` to `pages_dir` where terminology was
wrong.
2022-10-01 12:18:34 +02:00
Danilo Bargen
3e7dfb3c71 Cache: Make URL a parameter, not a field 2022-10-01 12:18:33 +02:00
Danilo Bargen
fb89303e85 Move custom_pages_dir business logic from RawConfig to Config
This also introduces the path source information for that directory,
which was previously unknown.
2022-10-01 12:18:30 +02:00
Danilo Bargen
7338933de5 Add integration test for cache_dir 2022-10-01 12:13:40 +02:00
Danilo Bargen
afbdfa6746 Bring back path source for cache directory 2022-10-01 12:13:40 +02:00
Danilo Bargen
33f0f108d8 Allow overriding cache directory through config
- Config: Add `cache_dir` to `[directories]` section
- Logic to handle legacy env var, config override and default cache dir
  selection is now in the `Config::try_from(RawConfig)` impl
- Deprecate old `TEALDEER_CACHE_DIR` env variable
- Update docs

Co-authored-by: Hans Gaiser <hansg91@gmail.com>
2022-10-01 12:13:39 +02:00
Danilo Bargen
026ae72742
Switch from ansi_term to yansi (#288)
ansi_term is not actively maintained anymore (see
https://rustsec.org/advisories/RUSTSEC-2021-0139). Replace it with a
suitable alternative.

I looked at termcolor, owo-colors and yansi and picked yansi:

- It is very simple
- It does not do terminal color support checking (we already do that in
  tealdeer)
- Its color enum type is almost identical to the one from ansi_term, so
  migrating is easy

The only change from a config API point of view is that "purple" is now
renamed to "magenta", but "purple" still works.
2022-09-27 23:55:50 +02:00
Danilo Bargen
f45a502383
Run cargo update (#287) 2022-09-24 20:54:01 +00:00
Olav de Haas
f4a94112f4
Add custom pages to list output (#285)
Fixes #205.
2022-09-24 21:27:35 +02:00
Niklas Mohrin
aa67a59d5b
Merge pull request #284 from niklasmohrin/edition-and-lints
Switch to 2021 Edition and maintenance
2022-08-21 23:18:39 +02:00
Niklas Mohrin
65cbe80e9d
Add comment to empty rustfmt.toml 2022-08-21 22:39:02 +02:00
Niklas Mohrin
a6023a5234
Small fixes in ci.yml
- Add `profile: minimal`
- Install `rustfmt` when installing the toolchain, not afterwards
- Use stable toolchain for `rustfmt`
- Replace `override` with `default`. I think this better reflects the
  "use what we just installed" intent.
2022-08-21 22:39:02 +02:00
Niklas Mohrin
db492bc0cf
Upgrade to 2021 edition of Rust
To do so, we need to bump the MSRV to 1.56 (released 10/2021). While at
it, I actually bumped it all the way to 1.62, where the latest version,
(1.62.1) has been released on July 19, which is just more than one month
ago. Additionally, I removed `clippy.toml` and instead specified the
MSRV in `Cargo.toml`. This will also print an error when trying to
compile with an older compiler.
2022-08-21 22:32:07 +02:00
Niklas Mohrin
e94ee92db4
cargo clippy --fix 2022-08-21 21:53:10 +02:00
bagohart
b369678794
added missing fish completion for language (#280) 2022-07-18 10:01:03 +00:00
Kian-Meng Ang
97b4395e25
Fix typos (#277) 2022-06-20 12:35:17 +00:00
Danilo Bargen
543fa2290d
Merge pull request #274 from newsch/android-platform
Add support for Android platform
2022-06-14 23:11:08 +02:00
Evan Lloyd New-Schmidt
abbbbf01ed Add PlatformType::current for android target 2022-06-14 15:50:18 -04:00
Evan Lloyd New-Schmidt
4a5410fd0b Add support for android platform
tldr added android-specific commands under a new 'android' platform
last year: <https://github.com/tldr-pages/tldr/issues/5462>
2022-06-02 12:36:20 -04:00
Danilo Bargen
0f82aa5950
Create macOS release builds with bundled root certificates (#272)
As reported in https://github.com/dbrgn/tealdeer/issues/244, some users
on macOS had problems with `rustls-tls-native-roots`. Since we did not
find the root cause of this, we'll build macOS release builds with
`rustls-tls-webpki-roots` instead.

Fixes #244.
2022-05-06 10:43:30 +00:00
Danilo Bargen
d138ce23e4
Merge pull request #271 from dbrgn/updates
Updates
2022-05-03 22:54:56 +02:00
Danilo Bargen
750ebf653c CI: Bump rustfmt toolchain to 1.60 2022-05-03 22:31:58 +02:00
Danilo Bargen
62b6405685 Fix clap deprecation warnings 2022-05-03 22:10:18 +02:00
Danilo Bargen
3629002d5c Upgrade zip: 0.5 → 0.6 2022-05-03 21:49:44 +02:00
Danilo Bargen
6e09af2f8b Run cargo update 2022-05-03 21:47:15 +02:00
Simon Perdrisat
786933e507
Docs: Add MacPorts in the list of package managers (#270) 2022-04-09 15:10:22 +00:00
Danilo Bargen
5a1a21b8ab
Add note about auto-updates when cache is missing (#254) 2022-02-06 22:53:48 +01:00
Danilo Bargen
716ff15779
Merge pull request #262 from dbrgn/fix-completions
Clean up shell completions
2022-01-22 01:31:51 +01:00
Danilo Bargen
cc22760e5a Align help text and completion descriptions 2022-01-21 09:15:52 +01:00
Danilo Bargen
cab6666ffb Fix completions: Remove -p for pager 2022-01-21 09:14:30 +01:00
cyqsimon
d5dbe3084b
Add no-auto-update flag (#257)
* Added `no-auto-update`
* Updated usage.txt
* Add `no-auto-update` to completion scripts
* Apply review suggestions
2022-01-21 09:12:10 +01:00
Danny Moesch
2177297871
Move shell completion scripts to their own directory (#259)
* Move shell completion scripts to their own directory
* Remove completion scripts from published Cargo package
2022-01-20 09:10:18 +01:00
Danny Moesch
3b4451f8fa
Move definition of CLI arguments and options into own file (#258) 2022-01-19 23:49:23 +01:00
cyqsimon
ef7432c762 Enforce default rustfmt settings (#257) 2022-01-16 20:16:58 +01:00
Danilo Bargen
b5443b75b6
Merge pull request #253 from dbrgn/handle-download-errors
Handle cache download errors. Fixes #252.
2022-01-09 21:24:22 +01:00
Danilo Bargen
77a6d48381 Pages download: Check return status 2022-01-09 21:14:30 +01:00
Danilo Bargen
71b6e037a7 When decompressing ZIP fails, propagate error
Do not unwrap. Instead, propagate the error with a anyhow context.
2022-01-09 21:14:30 +01:00
Danilo Bargen
04804ae650
Merge pull request #231 from tranzystorek-io/fix-pager
Move pager configuration near render logic. Fixes #169.
2022-01-09 15:13:57 +01:00
Marcin Puc
4a9763a783 Ensure that pager configuration is run at most once 2022-01-09 13:08:10 +01:00
Marcin Puc
82e4b97f92 Move pager configuration near render logic 2022-01-09 01:27:42 +01:00
Danilo Bargen
d502fcdd6d
Merge pull request #249 from dbrgn/anyhow
Use anyhow for error handling
2022-01-09 01:13:43 +01:00
Danilo Bargen
5262234846 Remove error module and clean up 2022-01-09 01:04:24 +01:00
Danilo Bargen
fd307757d7 Port cache and output modules to anyhow results 2022-01-09 01:04:07 +01:00
Danilo Bargen
405a2c9c8f Port config module to anyhow results 2022-01-09 01:04:07 +01:00
Danilo Bargen
9e97d454f0 Add anyhow dependency 2022-01-08 22:08:29 +01:00
Danilo Bargen
84277cc31e
Cache: Return error if HTTP client cannot be created (#247)
Apparently `Client::new` can panic (see #244), so let's return the error instead.
2022-01-08 22:01:36 +01:00
Danilo Bargen
eadfe97335 CHANGELOG: Mention the switch to Rustls 2022-01-02 20:51:44 +01:00
Danilo Bargen
47a4d6d7ca Docs: Remove note about patch concatenation (#245) 2022-01-02 02:04:52 +01:00
Danilo Bargen
b09f250370
Use clap 3 stable (#243) 2022-01-01 15:10:20 +01:00
Danilo Bargen
8228d31451 upload-asset script: Change release name 2022-01-01 14:43:58 +01:00
59 changed files with 5075 additions and 2685 deletions

6
.github/dependabot.yml vendored Normal file
View file

@ -0,0 +1,6 @@
version: 2
updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "monthly"

View file

@ -1,90 +1,90 @@
name: CI
on:
push:
branches:
- main
- "v*.x"
pull_request:
schedule:
- cron: '30 3 * * 2'
name: CI
workflow_dispatch:
jobs:
test:
name: run tests
strategy:
matrix:
platform: [ubuntu-latest, macos-latest, windows-latest]
rust: [1.54, stable]
toolchain: [stable, 1.87.0] # MSRV
include:
- platform: windows-latest
exe_suffix: .exe
runs-on: ${{ matrix.platform }}
steps:
- uses: actions/checkout@v2
- uses: actions-rs/toolchain@v1
- uses: actions/checkout@v7
- uses: dtolnay/rust-toolchain@master
with:
toolchain: ${{ matrix.rust }}
override: true
toolchain: ${{ matrix.toolchain }}
- run: mkdir artifacts
- name: Build with default features
uses: actions-rs/cargo@v1
run: |
cargo build
cp target/debug/tldr${{ matrix.exe_suffix}} artifacts/tldr-default${{ matrix.exe_suffix}}
- name: Build with logging and Rustls with webpki roots
run: |
cargo build --features logging,rustls-with-webpki-roots --no-default-features
cp target/debug/tldr${{ matrix.exe_suffix}} artifacts/tldr-logging-rustls-webpki${{ matrix.exe_suffix}}
- name: Build with native TLS backend
run: |
# expects runners have the proper Native SSL library
cargo build --features native-tls --no-default-features
cp target/debug/tldr${{ matrix.exe_suffix}} artifacts/tldr-native-tls${{ matrix.exe_suffix}}
- uses: actions/upload-artifact@v7
with:
command: build
- name: Build with all features
uses: actions-rs/cargo@v1
with:
command: build
args: --all-features
name: tldr-debug-build-${{ matrix.platform }}-rust-${{ matrix.toolchain }}
path: artifacts/
- name: Run tests
uses: actions-rs/cargo@v1
with:
command: test
args: --all-features
run: cargo test -- --test-threads 1
clippy:
name: run clippy lints
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions-rs/toolchain@v1
with:
toolchain: stable
components: clippy
override: true
- uses: actions-rs/clippy-check@v1
with:
token: ${{ secrets.GITHUB_TOKEN }}
args: --all-features
- uses: actions/checkout@v7
- uses: dtolnay/rust-toolchain@master
with:
toolchain: stable
components: clippy
- name: run clippy lints
run: cargo clippy --all-targets --features logging
fmt:
name: run rustfmt
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions-rs/toolchain@v1
with:
toolchain: 1.54
override: true
- run: rustup component add rustfmt
- uses: actions-rs/cargo@v1
with:
command: fmt
args: --all -- --check
- uses: actions/checkout@v7
- uses: dtolnay/rust-toolchain@master
with:
toolchain: stable
components: rustfmt
- name: run rustfmt
run: cargo fmt --all -- --check
docs:
name: build docs
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v7
- name: Setup mdBook
uses: peaceiris/actions-mdbook@v1
uses: peaceiris/actions-mdbook@v2
with:
mdbook-version: '0.4.4'
- uses: actions-rs/toolchain@v1
- name: Setup toolchain
uses: dtolnay/rust-toolchain@master
with:
toolchain: stable
override: true
toolchain: stable
- name: Build
uses: actions-rs/cargo@v1
with:
command: build
run: cargo build
- name: Ensure that docs can be built
run: cd docs && mdbook build
- name: Generate usage string

View file

@ -1,25 +1,25 @@
name: github pages
name: GitHub Pages
on:
push:
branches:
- main
tags:
- "v[1-9]*" # push events matching `v` followed by anything larger than 0, e.g. v1.0, v20.15.10
workflow_dispatch:
jobs:
deploy:
runs-on: ubuntu-20.04
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v7
- name: Setup mdBook
uses: peaceiris/actions-mdbook@v1
uses: peaceiris/actions-mdbook@v2
with:
mdbook-version: '0.4.4'
- run: cd docs && mdbook build
- name: Deploy
uses: peaceiris/actions-gh-pages@v3
uses: peaceiris/actions-gh-pages@v4
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./docs/book

View file

@ -1,3 +1,4 @@
name: Release
on:
push:
tags:
@ -5,41 +6,41 @@ on:
jobs:
create-release:
runs-on: ubuntu-20.04
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v7
- name: Create release for tag
if: startsWith(github.ref, 'refs/tags/')
run: |
source ./scripts/upload-asset.sh
# Create: <token> <repo> <tag>
create_release ${{ secrets.GITHUB_TOKEN }} ${{ github.repository }} ${GITHUB_REF#refs/*/} "Tealdeer version ${GITHUB_REF#refs/*/v}.\n\nFor the full changelog, see https://github.com/dbrgn/tealdeer/blob/main/CHANGELOG.md.\n\nBinaries were generated automatically in CI, and are therefore unsigned. For a fully trusted release, please build from source."
create_release ${{ secrets.GITHUB_TOKEN }} ${{ github.repository }} ${GITHUB_REF#refs/*/} "Tealdeer version ${GITHUB_REF#refs/*/v}.\n\nFor the full changelog, see https://github.com/tealdeer-rs/tealdeer/blob/main/CHANGELOG.md.\n\nBinaries were generated automatically in CI, and are therefore unsigned. For a fully trusted release, please build from source."
upload-completions:
needs:
- create-release
runs-on: ubuntu-20.04
runs-on: ubuntu-latest
strategy:
matrix:
target: ["bash", "fish", "zsh"]
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v7
- name: Upload completion
if: startsWith(github.ref, 'refs/tags/')
run: |
source ./scripts/upload-asset.sh
# Upload: <token> <repo> <tag> <file> <name>
upload_release_file ${{ secrets.GITHUB_TOKEN }} ${{ github.repository }} ${GITHUB_REF#refs/*/} ${{ matrix.target }}_tealdeer completions_${{ matrix.target }}
upload_release_file ${{ secrets.GITHUB_TOKEN }} ${{ github.repository }} ${GITHUB_REF#refs/*/} completion/${{ matrix.target }}_tealdeer completions_${{ matrix.target }}
upload-license:
needs:
- create-release
runs-on: ubuntu-20.04
runs-on: ubuntu-latest
strategy:
matrix:
target: ["MIT", "APACHE"]
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v7
- name: Upload license
if: startsWith(github.ref, 'refs/tags/')
run: |
@ -48,12 +49,14 @@ jobs:
upload_release_file ${{ secrets.GITHUB_TOKEN }} ${{ github.repository }} ${GITHUB_REF#refs/*/} LICENSE-${{ matrix.target }} LICENSE-${{ matrix.target }}.txt
build-linux:
runs-on: ubuntu-20.04
runs-on: ubuntu-latest
strategy:
matrix:
include:
- arch: "x86_64"
libc: "musl"
- arch: "aarch64"
libc: "musl"
- arch: "i686"
libc: "musl"
- arch: "armv7"
@ -63,42 +66,50 @@ jobs:
- arch: "arm"
libc: "musleabihf"
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v7
- name: Pull Docker image
run: docker pull messense/rust-musl-cross:${{ matrix.arch }}-${{ matrix.libc }}
- name: Build in Docker
run: docker run --rm -i -v "$(pwd)":/home/rust/src messense/rust-musl-cross:${{ matrix.arch }}-${{ matrix.libc }} cargo build --release
- name: Strip binary
run: docker run --rm -i -v "$(pwd)":/home/rust/src messense/rust-musl-cross:${{ matrix.arch }}-${{ matrix.libc }} musl-strip -s /home/rust/src/target/${{ matrix.arch }}-unknown-linux-${{ matrix.libc }}/release/tldr
- uses: actions/upload-artifact@v2
- uses: actions/upload-artifact@v7
with:
name: "tealdeer-linux-${{ matrix.arch }}-${{ matrix.libc }}"
path: "target/${{ matrix.arch }}-unknown-linux-${{ matrix.libc }}/release/tldr"
build-macos:
runs-on: macos-11
runs-on: macos-latest
strategy:
matrix:
include:
- arch: "x86_64"
- arch: "aarch64"
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v7
- name: Setup toolchain
uses: dtolnay/rust-toolchain@master
with:
toolchain: stable
targets: "${{ matrix.arch }}-apple-darwin"
- name: Build
uses: actions-rs/cargo@v1
run: cargo build --release --target ${{ matrix.arch }}-apple-darwin
- uses: actions/upload-artifact@v7
with:
command: build
args: --release --target x86_64-apple-darwin
- uses: actions/upload-artifact@v2
with:
name: "tealdeer-macos-x86_64"
path: "target/x86_64-apple-darwin/release/tldr"
name: "tealdeer-macos-${{ matrix.arch }}"
path: "target/${{ matrix.arch }}-apple-darwin/release/tldr"
build-windows:
runs-on: windows-2022
runs-on: windows-latest
steps:
- uses: actions/checkout@v2
- name: Build
uses: actions-rs/cargo@v1
- uses: actions/checkout@v7
- name: Setup toolchain
uses: dtolnay/rust-toolchain@master
with:
command: build
args: --release --target x86_64-pc-windows-msvc
- uses: actions/upload-artifact@v2
toolchain: stable
- name: Build
run: cargo build --release --target x86_64-pc-windows-msvc
- uses: actions/upload-artifact@v7
with:
name: "tealdeer-windows-x86_64-msvc"
path: "target/x86_64-pc-windows-msvc/release/tldr.exe"
@ -109,20 +120,22 @@ jobs:
- build-linux
- build-macos
- build-windows
runs-on: ubuntu-20.04
runs-on: ubuntu-latest
strategy:
matrix:
target:
- linux-x86_64-musl
- linux-aarch64-musl
- linux-i686-musl
- linux-armv7-musleabihf
- linux-arm-musleabi
- linux-arm-musleabihf
- macos-x86_64
- macos-aarch64
- windows-x86_64-msvc
steps:
- uses: actions/checkout@v2
- uses: actions/download-artifact@v2
- uses: actions/checkout@v7
- uses: actions/download-artifact@v8
- name: Upload binary
if: startsWith(github.ref, 'refs/tags/')
run: |

View file

@ -13,6 +13,302 @@ Possible log types:
- `[docs]` for documentation changes.
- `[chore]` for maintenance work.
### [v1.5.1][v1.5.1], [v1.6.2][v1.6.2], [v1.7.3][v1.7.3] (2026-01-25)
Today I am releasing three patch updates for outdated versions of tealdeer.
They are minimal patches for Linux distributions that ship old versions of
tealdeer which recently broke due to an upstream change. If you can choose
freely which version of tealdeer to use, I recommend using the latest version of
tealdeer, 1.8.1. For more details, see the "Notes to package maintainers"
section below.
All three updates contain only a single change compared to their respective
previous versions which changes the `ARCHIVE_URL` constant used for updating the
page cache. The reason for this change is that the upstream tldr-pages
repository shut down the domain that clients were previously required to use.
Note that this issue is already fixed in tealdeer 1.8.0 where we introduced a
config file option for changing the URL used at runtime. The versions 1.8.0 and
1.8.1 also use the new domain of the tldr-pages archive by default, so no action
is needed for users of those versions.
#### Changes
- [fixed] Update `ARCHIVE_URL`
#### Notes to package maintainers
I have _not_ updated the lockfile for any of these releases, so the locked
dependency versions are still the same as they were for the previous release in
the respective v1.x series. Updating the lockfile for tealdeer 1.5.0 to remove
any `cargo audit` warnings while also maintaining compatibility with Rust 1.54
also brings larger changes through transitive dependencies, which contradicts my
plan to make this update easy to plug into existing build pipelines.
If you want to build / distribute tealdeer v1.5.1, v1.6.2, or v1.7.3, please use
an up to date Rust toolchain to permit updates to newer versions of (transitive)
dependencies. Do not use the lockfile, instead update to the newest available
dependency versions.
For the same reason, there are no artifacts attached to the GitHub releases of
these versions.
### [v1.8.1][v1.8.1] (2025-11-11)
This patch release tweaks the enabled features for ureq, the library we use to
perform HTTP requests when updating the cache. In particular, support for socks
proxies is now enabled.
#### Changes:
- [added] Enable ureq's socks-proxy feature ([#451])
### [v1.8.0][v1.8.0] (2025-10-03)
One year and one day have passed since tealdeer version 1.7.0 was released, so
it's time for an update! Tealdeer 1.8 comes with a complete rewrite of the page
cache and contains many long awaited improvements around it.
Firstly, tealdeer now supports language-specific downloads. This means that only
the pages matching the configured languages are downloaded when updating the
cache. The languages used for searching pages can be configured separately to
the ones used for updating, so it is possible to download pages in languages
that are not usually queried.
Next to configuring which languages are used for searching, it is now also
possible to specify which platforms are used in the config file. Importantly,
the default behavior for page search has changed so that all platforms are
searched if no page is found for the platform that tealdeer is running on. To
restore the behavior of tealdeer 1.7, users should set
```toml
[search]
platforms = ["current", "common"]
```
in their config file.
Coming back to updating, the default build configuration of tealdeer now
includes multiple TLS backends. This means that tealdeer does not have to be
rebuilt to try out a different TLS backend. The used backend can be chosen in
the config file. By default, tealdeer comes with support for rustls using webpki
certificates or system certificates. Native TLS is supported, but not enabled by
default to avoid build troubles with OpenSSL and musl.
For details, please refer to the [user documentation].
#### Changes:
- [added] Resolve paths in config `[directories]` relative to the config directory ([#306])
- [added] Add `common` platform to CLI ([#401])
- [added] Add configuration option for `archive_source` ([#337])
- [added] Allows configuring TLS backend ([#386])
- [added] Add args: `--edit-page` and `--edit-patch` ([#388])
- [added] Add an option to specify a custom config file to be used ([#422])
- [added] Upload binaries from build step as artifact ([#423])
- [added] Add `search.languages` and `updates.download_languages` settings ([#430])
- [added] Add `search.platforms` config option and search all platforms by default ([#435])
- [added] Add `display.show_title` option to display command titles in output ([#439])
- [chore] Various test improvements ([#399])
- [chore] Add tests for osx/macos alias ([#407])
- [chore] Move most of `main` to `try_main` ([#400])
- [chore] Only create a single temporary directory in integration tests ([#411])
- [chore] Replace reqwest with ureq ([#417])
- [chore] Introduce Language struct ([#425])
- [chore] Cache rewrite ([#416])
- [chore] Allow references in `Config` ([#429])
- [docs] Highlight code examples in user docs ([#440])
- [removed] Remove native-tls from default feature set ([#436])
#### Contributors to this version:
- [Christoph Loy][@beatbrot]
- [Erick Guan][@erickguan]
- [@MHS-0][@MHS-0]
- [Matěj Kafka][@MatejKafka]
- [Nachiket Kanore][@nachiketkanore]
- [Niklas Mohrin][@niklasmohrin]
- [Predrag Minic][@mipedja]
- [@hex1c][@hex1c]
- [lyj][@lengyijun]
Thanks!
#### Notes to package maintainers
1. The MSRV has been bumped to 1.85.
2. Consider whether you want to include the `native-tls` feature in your build
of tealdeer. The feature is disabled for the binaries in the GitHub release
because we target musl, but it might work out of the box for your
distribution.
3. We have added the `ignore-online-tests` feature to automatically mark all
tests that require an internet connection as skipped, so you can use this
feature instead of maintaining a list of these tests yourself.
### [v1.7.2][v1.7.2] (2025-03-18)
This patch release updates the `zip` dependency to mitigate a potential security
vulnerability. A successful attack against tealdeer users would require
manipulation of the tldr pages archive downloaded during an update. As the
archive is downloaded from a trusted source (the tldr-pages organization), it
seems very unlikely that running a version of tealdeer prior to 1.7.2 poses a
security risk. Nevertheless, it cannot hurt to rule out any chance of an attack
by updating tealdeer to version 1.7.2.
For more details, please see https://github.com/advisories/GHSA-94vh-gphv-8pm8.
- [security] Require `zip >= 2.3.0`
- [chore] Run CI on backport branches and on dispatch
### [v1.7.1][v1.7.1] (2024-11-14)
This patch release updates the `yansi` dependency to version 1, so that the
previous versions of `yansi` can be removed from the package sets of Linux
distributions. This change should not impact the behavior of tealdeer.
#### Changes:
- [chore] Upgrade yansi: 0.5.1 -> 1.0.1 ([#389])
#### Contributors to this version:
- [Blair Noctis][@nc7s]
Thanks!
### [v1.7.0][v1.7.0] (2024-10-02)
It's been 24 months since the last release, time for tealdeer 1.7.0! Thanks to
16 individual contributors, a few nice changes and features are included in
this release.
One change is that you can **query multiple platforms at once**. For example:
tldr --platform openbsd --platform linux df
This will show the `df` page for OpenBSD (if available), followed by Linux (if
available), with fallback to the current platform on which tealdeer runs.
What's that `openbsd` thing up there? Yes, there's now **support for the BSD
platforms `freebsd`, `netbsd` and `openbsd`**.
And since we're already talking about platform support: Our **binary releases
now include builds for ARM64 (aka `aarch64`) on macOS (Apple Silicon, M1/M2/M3)
and Linux**. _(Keep in mind that binary releases are generated in CI and are
unsigned. For a trusted build, please compile from source.)_
There's also a breaking change for the folks using [custom pages and
patches](https://tealdeer-rs.github.io/tealdeer/usage_custom_pages.html): These
files now use a `.md` extension. Old files will continue to work, but will
result a deprecation warning being printed when used.
On a personal note, this will be the last release from me
([Danilo](https://github.com/dbrgn/)) as primary maintainer of tealdeer. For
details, see [#376](https://github.com/tealdeer-rs/tealdeer/issues/376).
#### Changes:
- [added] Allow querying multiple platforms ([#300])
- [added] Add BSD platform support ([#354])
- [added] Allow building with native-tls in addition to rustls ([#303])
- [changed] Change custom page files to use a `.md` file extension ([#322])
- [changed] Update to clap v4 for doing command line parsing ([#298])
- [changed] Performance optimization in LineIterator ([#314])
- [changed] Performance optimizations by tweaking Cargo flags ([#355])
- [changed] Include completions in published crate ([#333])
- [changed] Minimal supported Rust version is now 1.75 ([#298])
- [fixed] Fix bash/zsh/fish completions when cache is empty ([#327], [#331])
- [docs] Publish docs only when tagging a release ([#362])
- [docs] List Scoop and Debian packages ([#305], [#315])
- [docs] Add "Tips and Tricks" chapter to user manual ([#342])
- [docs] Various docs improvements ([#293])
- [chore] Improvements to CI workflows ([#324])
- [chore] Update Cargo.toml license field following SPDX 2.1 ([#336])
- [chore] Dependency updates
#### Contributors to this version:
- [Adam Henley][@adamazing]
- [Andrea Frigido][@frisoft]
- [Blair Noctis][@nc7s]
- [Danilo Bargen][@dbrgn]
- [Felix Yan][@felixonmars]
- [Iliia Maleki][@iliya-malecki]
- [JJ Style][@jj-style]
- [K.B.Dharun Krishna][@kbdharun]
- [Linus Walker][@Walker-00]
- [Mohit Raj][@agrmohit]
- [Nicolai Fröhlich][@nifr]
- [Niklas Mohrin][@niklasmohrin]
- [@qknogxxb][@qknogxxb]
- [@tveness][@tveness]
- [Y.D.X.][@YDX-2147483647]
- [Zacchary Dempsey-Plante][@zedseven]
Thanks!
### [v1.6.1][v1.6.1] (2022-10-24)
#### Changes:
- [fixed] Fix path source for custom pages dir ([#297])
- [chore] Update dependendencies ([#299])
#### Contributors to this version:
- [Cyrus Yip][@CyrusYip]
- [Danilo Bargen][@dbrgn]
Thanks!
### [v1.6.0][v1.6.0] (2022-10-02)
It's been 9 months since the last release already! This is not a huge update
feature-wise, but it still contains a few nice new improvements and a few
bugfixes, contributed by 11 different people. The most important new feature is
probably the option to override the cache directory through the config file.
The `TEALDEER_CACHE_DIR` env variable is now deprecated.
A note to packagers: Shell completions have been moved to the `completion/`
subdirectory! Packaging scripts might need to be updated.
#### Changes:
- [added] Allow overriding cache directory through config ([#276])
- [added] Add `--no-auto-update` CLI flag ([#257])
- [added] Show note about auto-updates when cache is missing ([#254])
- [added] Add support for android platform ([#274])
- [added] Add custom pages to list output ([#285])
- [fixed] Cache: Return error if HTTP client cannot be created ([#247])
- [fixed] Handle cache download errors ([#253])
- [fixed] Do not page output of `tldr --update` ([#231])
- [fixed] Create macOS release builds with bundled root certificates ([#272])
- [fixed] Clean up and fix shell completions ([#262])
- [deprecated] The `TEALDEER_CACHE_DIR` env variable is now deprecated ([#276])
- [removed] The `--config-path` command was removed, use `--show-paths` instead ([#290])
- [removed] The `-o/--os` command was removed, use `-p/--platform` instead ([#290])
- [removed] The `-m/--markdown` command was removed, use `-r/--raw` instead ([#290])
- [chore] Move shell completion scripts to their own directory ([#259])
- [chore] Update dependencies ([#271], [#287], [#291])
- [chore] Use anyhow for error handling ([#249])
- [chore] Switch to Rust 2021 edition ([#284])
#### Contributors to this version:
- [@bagohart][@bagohart]
- [@cyqsimon][@cyqsimon]
- [Danilo Bargen][@dbrgn]
- [Danny Mösch][@SimplyDanny]
- [Evan Lloyd New-Schmidt][@newsch]
- [Hans Gaiser][@hgaiser]
- [Kian-Meng Ang][@kianmeng]
- [Marcin Puc][@tranzystorek-io]
- [Niklas Mohrin][@niklasmohrin]
- [Olav de Haas][@Olavhaasie]
- [Simon Perdrisat][@gagarine]
Thanks!
### [v1.5.0][v1.5.0] (2021-12-31)
@ -24,7 +320,7 @@ The highlights:
- **Custom pages and patches**: You can now create your own local-only tldr
pages. But not just that, you can also extend existing upstream pages with
your own examples. For more details, see
[the docs](https://dbrgn.github.io/tealdeer/usage_custom_pages.html).
[the docs](https://tealdeer-rs.github.io/tealdeer/usage_custom_pages.html).
- **Change argument parsing from docopt to clap**: We replaced docopt.rs as
argument parsing library with clap v3, resulting in almost 1 MiB smaller
binaries and a 22% speed increase when rendering a tldr page.
@ -35,7 +331,7 @@ The highlights:
`-p/--platform` and implemented transparent lowercasing of the page names.
- **Docs**: The README based documentation has reached its limits. There are
now new mdbook based docs over at
[dbrgn.github.io/tealdeer/](https://dbrgn.github.io/tealdeer/), we hope these
[tealdeer-rs.github.io/tealdeer/](https://tealdeer-rs.github.io/tealdeer/), we hope these
make using tealdeer easier. Of course, documentation improvements are
welcome! Also, if you're confused about how to use a certain feature, feel
free to open an issue, this way we can improve the docs.
@ -43,10 +339,10 @@ The highlights:
Note that the MSRV (Minimal Supported Rust Version) of the project
[changed][i190]:
> When publishing a Tealdeer release, the Rust version required to build it
> When publishing a tealdeer release, the Rust version required to build it
> should be stable for at least a month.
Changes:
#### Changes:
- [added] Support custom pages and patches ([#142][i142])
- [added] Multi-language support ([#125][i125], [#161][i161])
@ -61,6 +357,7 @@ Changes:
- [fixed] Create cache directory path if it does not exist ([#174][i174])
- [fixed] Use default style if user-defined style is missing ([#210][i210])
- [changed] Switch from docopt to clap for argument parsing ([#108][i108])
- [changed] Switch from OpenSSL to Rustls ([#187][i187])
- [changed] Performance improvements ([#187][i187])
- [changed] Send all progress logging messages to stderr ([#171][i171])
- [changed] Rename `-o/--os` to `-p/--platform` ([#217][i217])
@ -68,15 +365,15 @@ Changes:
- [deprecated] The `--config-path` command is deprecated, use `--show-paths` instead ([#162][i162])
- [deprecated] The `-o/--os` command is deprecated, use `-p/--platform` instead ([#217][i217])
- [deprecated] The `-m/--markdown` command is deprecated, use `-r/--raw` instead ([#108][i108])
- [docs] New docs at [dbrgn.github.io/tealdeer/](https://dbrgn.github.io/tealdeer/)
- [docs] Add comparative benchmarks with hyperfine ([#163][i163], [README](https://github.com/dbrgn/tealdeer#goals))
- [docs] New docs at [tealdeer-rs.github.io/tealdeer/](https://tealdeer-rs.github.io/tealdeer/)
- [docs] Add comparative benchmarks with hyperfine ([#163][i163], [README](https://github.com/tealdeer-rs/tealdeer#goals))
- [chore] Download tldr pages archive from their website, not from GitHub ([#213][i213])
- [chore] Bump MSRV to 1.54 and change MSRV policy ([#190][i190])
- [chore] The `master` branch was renamed to `main`
- [chore] All release binaries are now generated in CI. Binaries for macOS and Windows are also provided. ([#240][i240])
- [chore] Update all dependencies
Contributors to this version:
#### Contributors to this version:
- [@bl-ue][@bl-ue]
- [Cameron Tod][@cam8001]
@ -105,7 +402,7 @@ co-maintainer. Thank you for your help!
- [fixed] Syntax error in zsh completion file ([#138][i138])
Contributors to this version:
#### Contributors to this version:
- [Danilo Bargen][@dbrgn]
- [Bruno A. Muciño][@mucinoab]
@ -122,7 +419,7 @@ Thanks!
- [changed] Make `--list` option comply with official spec ([#112][i112])
- [changed] Move cache age warning to stderr ([#113][i113])
Contributors to this version:
#### Contributors to this version:
- [Atul Bhosale][@Atul9]
- [Danilo Bargen][@dbrgn]
@ -148,7 +445,7 @@ Thanks!
- [fixed] Fix Fish autocompletion on macOS ([#87][i87])
- [fixed] Fix compilation on Windows by disabling pager ([#99][i99])
Contributors to this version:
#### Contributors to this version:
- [Bruno Heridet][@Delapouite]
- [Danilo Bargen][@dbrgn]
@ -174,7 +471,7 @@ Thanks!
- [changed] Move to Rust 2018, require Rust 1.32 ([#69][i69] / [#84][i84])
- [fixed] Add (back) support for proxies ([#68][i68])
Contributors to this version:
#### Contributors to this version:
- [Bar Hatsor][@Bassets]
- [Danilo Bargen][@dbrgn]
@ -197,7 +494,7 @@ Thanks!
- [changed] Require at least Rust 1.28 to build (previous: 1.19)
- [fixed] Fix building on systems with openssl 1.1.1 ([#47][i47])
Contributors to this version:
#### Contributors to this version:
- [Danilo Bargen][@dbrgn]
- [@equal-l2][@equal-l2]
@ -230,29 +527,43 @@ Thanks!
- First crates.io release
[user documentation]: https://tealdeer-rs.github.io/tealdeer/
[@0ndorio]: https://github.com/0ndorio
[@adamazing]: https://github.com/adamazing
[@agrmohit]: https://github.com/agrmohit
[@aldanor]: https://github.com/aldanor
[@Atul9]: https://github.com/Atul9
[@BachoSeven]: https://github.com/BachoSeven
[@bagohart]: https://github.com/bagohart
[@Bassets]: https://github.com/Bassets
[@black7375]: https://github.com/black7375
[@bl-ue]: https://github.com/bl-ue
[@Calinou]: https://github.com/Calinou
[@cam8001]: https://github.com/cam8001
[@cho-m]: https://github.com/cho-m
[@cyqsimon]: https://github.com/cyqsimon
[@CyrusYip]: https://github.com/CyrusYip
[@das-g]: https://github.com/das-g
[@dbrgn]: https://github.com/dbrgn
[@Delapouite]: https://github.com/Delapouite
[@dmaahs2017]: https://github.com/dmaahs2017
[@equal-l2]: https://github.com/equal-l2
[@felixonmars]: https://github.com/felixonmars
[@frisoft]: https://github.com/frisoft
[@gagarine]: https://github.com/gagarine
[@hgaiser]: https://github.com/hgaiser
[@ilai-deutel]: https://github.com/ilai-deutel
[@iliya-malecki]: https://github.com/iliya-malecki
[@invakid404]: https://github.com/invakid404
[@james2doyle]: https://github.com/james2doyle
[@jcgruenhage]: https://github.com/jcgruenhage
[@jdvr]: https://github.com/jdvr
[@jedahan]: https://github.com/jedahan
[@jesdazrez]: https://github.com/jesdazrez
[@jj-style]: https://github.com/jj-style
[@kbdharun]: https://github.com/kbdharun
[@kianmeng]: https://github.com/kianmeng
[@kornelski]: https://github.com/kornelski
[@korrat]: https://github.com/korrat
[@laxect]: https://github.com/laxect
@ -262,8 +573,13 @@ Thanks!
[@mucinoab]: https://github.com/mucinoab
[@mystal]: https://github.com/mystal
[@natpen]: https://github.com/natpen
[@nc7s]: https://github.com/nc7s
[@newsch]: https://github.com/newsch
[@nifr]: https://github.com/nifr
[@niklasmohrin]: https://github.com/niklasmohrin
[@Olavhaasie]: https://github.com/Olavhaasie
[@Plommonsorbet]: https://github.com/Plommonsorbet
[@qknogxxb]: https://github.com/qknogxxb
[@rithvikvibhu]: https://github.com/rithvikvibhu
[@SimplyDanny]: https://github.com/SimplyDanny
[@sondr3]: https://github.com/sondr3
@ -271,58 +587,138 @@ Thanks!
[@tranzystorek-io]: https://github.com/tranzystorek-io
[@tveness]: https://github.com/tveness
[@Voultapher]: https://github.com/Voultapher
[@Walker-00]: https://github.com/Walker-00
[@YDX-2147483647]: https://github.com/YDX-2147483647
[@zedseven]: https://github.com/zedseven
[@beatbrot]: https://github.com/beatbrot
[@erickguan]: https://github.com/erickguan
[@MHS-0]: https://github.com/MHS-0
[@MatejKafka]: https://github.com/MatejKafka
[@nachiketkanore]: https://github.com/nachiketkanore
[@mipedja]: https://github.com/mipedja
[@hex1c]: https://github.com/hex1c
[@lengyijun]: https://github.com/lengyijun
[v1.0.0]: https://github.com/dbrgn/tealdeer/compare/v0.4.0...v1.0.0
[v1.1.0]: https://github.com/dbrgn/tealdeer/compare/v1.0.0...v1.1.0
[v1.2.0]: https://github.com/dbrgn/tealdeer/compare/v1.1.0...v1.2.0
[v1.3.0]: https://github.com/dbrgn/tealdeer/compare/v1.2.0...v1.3.0
[v1.4.0]: https://github.com/dbrgn/tealdeer/compare/v1.3.0...v1.4.0
[v1.4.1]: https://github.com/dbrgn/tealdeer/compare/v1.4.0...v1.4.1
[v1.5.0]: https://github.com/dbrgn/tealdeer/compare/v1.4.1...v1.5.0
[v1.0.0]: https://github.com/tealdeer-rs/tealdeer/compare/v0.4.0...v1.0.0
[v1.1.0]: https://github.com/tealdeer-rs/tealdeer/compare/v1.0.0...v1.1.0
[v1.2.0]: https://github.com/tealdeer-rs/tealdeer/compare/v1.1.0...v1.2.0
[v1.3.0]: https://github.com/tealdeer-rs/tealdeer/compare/v1.2.0...v1.3.0
[v1.4.0]: https://github.com/tealdeer-rs/tealdeer/compare/v1.3.0...v1.4.0
[v1.4.1]: https://github.com/tealdeer-rs/tealdeer/compare/v1.4.0...v1.4.1
[v1.5.0]: https://github.com/tealdeer-rs/tealdeer/compare/v1.4.1...v1.5.0
[v1.5.1]: https://github.com/tealdeer-rs/tealdeer/compare/v1.5.0...v1.5.1
[v1.6.0]: https://github.com/tealdeer-rs/tealdeer/compare/v1.5.0...v1.6.0
[v1.6.1]: https://github.com/tealdeer-rs/tealdeer/compare/v1.6.0...v1.6.1
[v1.6.2]: https://github.com/tealdeer-rs/tealdeer/compare/v1.6.1...v1.6.2
[v1.7.0]: https://github.com/tealdeer-rs/tealdeer/compare/v1.6.1...v1.7.0
[v1.7.1]: https://github.com/tealdeer-rs/tealdeer/compare/v1.7.0...v1.7.1
[v1.7.2]: https://github.com/tealdeer-rs/tealdeer/compare/v1.7.1...v1.7.2
[v1.7.3]: https://github.com/tealdeer-rs/tealdeer/compare/v1.7.2...v1.7.3
[v1.8.0]: https://github.com/tealdeer-rs/tealdeer/compare/v1.7.2...v1.8.0
[v1.8.1]: https://github.com/tealdeer-rs/tealdeer/compare/v1.8.0...v1.8.1
[i34]: https://github.com/dbrgn/tealdeer/issues/34
[i43]: https://github.com/dbrgn/tealdeer/issues/43
[i44]: https://github.com/dbrgn/tealdeer/issues/44
[i47]: https://github.com/dbrgn/tealdeer/issues/47
[i48]: https://github.com/dbrgn/tealdeer/issues/48
[i57]: https://github.com/dbrgn/tealdeer/issues/57
[i58]: https://github.com/dbrgn/tealdeer/issues/58
[i61]: https://github.com/dbrgn/tealdeer/issues/61
[i68]: https://github.com/dbrgn/tealdeer/issues/68
[i69]: https://github.com/dbrgn/tealdeer/issues/69
[i71]: https://github.com/dbrgn/tealdeer/issues/71
[i75]: https://github.com/dbrgn/tealdeer/issues/75
[i77]: https://github.com/dbrgn/tealdeer/issues/77
[i84]: https://github.com/dbrgn/tealdeer/issues/84
[i86]: https://github.com/dbrgn/tealdeer/issues/86
[i87]: https://github.com/dbrgn/tealdeer/issues/87
[i89]: https://github.com/dbrgn/tealdeer/issues/89
[i95]: https://github.com/dbrgn/tealdeer/issues/95
[i97]: https://github.com/dbrgn/tealdeer/issues/97
[i99]: https://github.com/dbrgn/tealdeer/issues/99
[i108]: https://github.com/dbrgn/tealdeer/pull/108
[i111]: https://github.com/dbrgn/tealdeer/issues/111
[i112]: https://github.com/dbrgn/tealdeer/issues/112
[i113]: https://github.com/dbrgn/tealdeer/issues/113
[i115]: https://github.com/dbrgn/tealdeer/issues/115
[i125]: https://github.com/dbrgn/tealdeer/pull/125
[i138]: https://github.com/dbrgn/tealdeer/issues/138
[i142]: https://github.com/dbrgn/tealdeer/pull/142
[i148]: https://github.com/dbrgn/tealdeer/pull/148
[i157]: https://github.com/dbrgn/tealdeer/pull/157
[i161]: https://github.com/dbrgn/tealdeer/pull/161
[i162]: https://github.com/dbrgn/tealdeer/pull/162
[i163]: https://github.com/dbrgn/tealdeer/pull/163
[i168]: https://github.com/dbrgn/tealdeer/pull/168
[i171]: https://github.com/dbrgn/tealdeer/pull/171
[i174]: https://github.com/dbrgn/tealdeer/pull/174
[i176]: https://github.com/dbrgn/tealdeer/pull/176
[i187]: https://github.com/dbrgn/tealdeer/pull/187
[i190]: https://github.com/dbrgn/tealdeer/issues/190
[i197]: https://github.com/dbrgn/tealdeer/pull/197
[i210]: https://github.com/dbrgn/tealdeer/pull/210
[i213]: https://github.com/dbrgn/tealdeer/pull/213
[i215]: https://github.com/dbrgn/tealdeer/pull/215
[i217]: https://github.com/dbrgn/tealdeer/pull/217
[i227]: https://github.com/dbrgn/tealdeer/pull/227
[i240]: https://github.com/dbrgn/tealdeer/pull/240
[i34]: https://github.com/tealdeer-rs/tealdeer/issues/34
[i43]: https://github.com/tealdeer-rs/tealdeer/issues/43
[i44]: https://github.com/tealdeer-rs/tealdeer/issues/44
[i47]: https://github.com/tealdeer-rs/tealdeer/issues/47
[i48]: https://github.com/tealdeer-rs/tealdeer/issues/48
[i57]: https://github.com/tealdeer-rs/tealdeer/issues/57
[i58]: https://github.com/tealdeer-rs/tealdeer/issues/58
[i61]: https://github.com/tealdeer-rs/tealdeer/issues/61
[i68]: https://github.com/tealdeer-rs/tealdeer/issues/68
[i69]: https://github.com/tealdeer-rs/tealdeer/issues/69
[i71]: https://github.com/tealdeer-rs/tealdeer/issues/71
[i75]: https://github.com/tealdeer-rs/tealdeer/issues/75
[i77]: https://github.com/tealdeer-rs/tealdeer/issues/77
[i84]: https://github.com/tealdeer-rs/tealdeer/issues/84
[i86]: https://github.com/tealdeer-rs/tealdeer/issues/86
[i87]: https://github.com/tealdeer-rs/tealdeer/issues/87
[i89]: https://github.com/tealdeer-rs/tealdeer/issues/89
[i95]: https://github.com/tealdeer-rs/tealdeer/issues/95
[i97]: https://github.com/tealdeer-rs/tealdeer/issues/97
[i99]: https://github.com/tealdeer-rs/tealdeer/issues/99
[i108]: https://github.com/tealdeer-rs/tealdeer/pull/108
[i111]: https://github.com/tealdeer-rs/tealdeer/issues/111
[i112]: https://github.com/tealdeer-rs/tealdeer/issues/112
[i113]: https://github.com/tealdeer-rs/tealdeer/issues/113
[i115]: https://github.com/tealdeer-rs/tealdeer/issues/115
[i125]: https://github.com/tealdeer-rs/tealdeer/pull/125
[i138]: https://github.com/tealdeer-rs/tealdeer/issues/138
[i142]: https://github.com/tealdeer-rs/tealdeer/pull/142
[i148]: https://github.com/tealdeer-rs/tealdeer/pull/148
[i157]: https://github.com/tealdeer-rs/tealdeer/pull/157
[i161]: https://github.com/tealdeer-rs/tealdeer/pull/161
[i162]: https://github.com/tealdeer-rs/tealdeer/pull/162
[i163]: https://github.com/tealdeer-rs/tealdeer/pull/163
[i168]: https://github.com/tealdeer-rs/tealdeer/pull/168
[i171]: https://github.com/tealdeer-rs/tealdeer/pull/171
[i174]: https://github.com/tealdeer-rs/tealdeer/pull/174
[i176]: https://github.com/tealdeer-rs/tealdeer/pull/176
[i187]: https://github.com/tealdeer-rs/tealdeer/pull/187
[i190]: https://github.com/tealdeer-rs/tealdeer/issues/190
[i197]: https://github.com/tealdeer-rs/tealdeer/pull/197
[i210]: https://github.com/tealdeer-rs/tealdeer/pull/210
[i213]: https://github.com/tealdeer-rs/tealdeer/pull/213
[i215]: https://github.com/tealdeer-rs/tealdeer/pull/215
[i217]: https://github.com/tealdeer-rs/tealdeer/pull/217
[i227]: https://github.com/tealdeer-rs/tealdeer/pull/227
[#231]: https://github.com/tealdeer-rs/tealdeer/pull/231
[i240]: https://github.com/tealdeer-rs/tealdeer/pull/240
[#247]: https://github.com/tealdeer-rs/tealdeer/pull/247
[#249]: https://github.com/tealdeer-rs/tealdeer/pull/249
[#253]: https://github.com/tealdeer-rs/tealdeer/pull/253
[#254]: https://github.com/tealdeer-rs/tealdeer/pull/254
[#257]: https://github.com/tealdeer-rs/tealdeer/pull/257
[#259]: https://github.com/tealdeer-rs/tealdeer/pull/259
[#262]: https://github.com/tealdeer-rs/tealdeer/pull/262
[#271]: https://github.com/tealdeer-rs/tealdeer/pull/271
[#272]: https://github.com/tealdeer-rs/tealdeer/pull/272
[#274]: https://github.com/tealdeer-rs/tealdeer/pull/274
[#276]: https://github.com/tealdeer-rs/tealdeer/pull/276
[#284]: https://github.com/tealdeer-rs/tealdeer/pull/284
[#285]: https://github.com/tealdeer-rs/tealdeer/pull/285
[#287]: https://github.com/tealdeer-rs/tealdeer/pull/287
[#290]: https://github.com/tealdeer-rs/tealdeer/pull/290
[#291]: https://github.com/tealdeer-rs/tealdeer/pull/291
[#293]: https://github.com/tealdeer-rs/tealdeer/pull/293
[#297]: https://github.com/tealdeer-rs/tealdeer/pull/297
[#298]: https://github.com/tealdeer-rs/tealdeer/pull/298
[#299]: https://github.com/tealdeer-rs/tealdeer/pull/299
[#300]: https://github.com/tealdeer-rs/tealdeer/pull/300
[#303]: https://github.com/tealdeer-rs/tealdeer/pull/303
[#305]: https://github.com/tealdeer-rs/tealdeer/pull/305
[#306]: https://github.com/tealdeer-rs/tealdeer/pull/306
[#314]: https://github.com/tealdeer-rs/tealdeer/pull/314
[#315]: https://github.com/tealdeer-rs/tealdeer/pull/315
[#322]: https://github.com/tealdeer-rs/tealdeer/pull/322
[#324]: https://github.com/tealdeer-rs/tealdeer/pull/324
[#327]: https://github.com/tealdeer-rs/tealdeer/pull/327
[#331]: https://github.com/tealdeer-rs/tealdeer/pull/331
[#333]: https://github.com/tealdeer-rs/tealdeer/pull/333
[#336]: https://github.com/tealdeer-rs/tealdeer/pull/336
[#337]: https://github.com/tealdeer-rs/tealdeer/pull/337
[#342]: https://github.com/tealdeer-rs/tealdeer/pull/342
[#354]: https://github.com/tealdeer-rs/tealdeer/pull/354
[#355]: https://github.com/tealdeer-rs/tealdeer/pull/355
[#362]: https://github.com/tealdeer-rs/tealdeer/pull/362
[#386]: https://github.com/tealdeer-rs/tealdeer/pull/386
[#388]: https://github.com/tealdeer-rs/tealdeer/pull/388
[#389]: https://github.com/tealdeer-rs/tealdeer/pull/389
[#399]: https://github.com/tealdeer-rs/tealdeer/pull/399
[#400]: https://github.com/tealdeer-rs/tealdeer/pull/400
[#401]: https://github.com/tealdeer-rs/tealdeer/pull/401
[#407]: https://github.com/tealdeer-rs/tealdeer/pull/407
[#411]: https://github.com/tealdeer-rs/tealdeer/pull/411
[#416]: https://github.com/tealdeer-rs/tealdeer/pull/416
[#417]: https://github.com/tealdeer-rs/tealdeer/pull/417
[#422]: https://github.com/tealdeer-rs/tealdeer/pull/422
[#423]: https://github.com/tealdeer-rs/tealdeer/pull/423
[#425]: https://github.com/tealdeer-rs/tealdeer/pull/425
[#426]: https://github.com/tealdeer-rs/tealdeer/pull/426
[#429]: https://github.com/tealdeer-rs/tealdeer/pull/429
[#430]: https://github.com/tealdeer-rs/tealdeer/pull/430
[#435]: https://github.com/tealdeer-rs/tealdeer/pull/435
[#436]: https://github.com/tealdeer-rs/tealdeer/pull/436
[#439]: https://github.com/tealdeer-rs/tealdeer/pull/439
[#440]: https://github.com/tealdeer-rs/tealdeer/pull/440
[#451]: https://github.com/tealdeer-rs/tealdeer/pull/451

1915
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -4,33 +4,33 @@ authors = [
"Niklas Mohrin <dev@niklasmohrin.de>",
]
description = "Fetch and show tldr help pages for many CLI commands. Full featured offline client with caching support."
homepage = "https://github.com/dbrgn/tealdeer/"
license = "MIT/Apache-2.0"
homepage = "https://github.com/tealdeer-rs/tealdeer/"
license = "MIT OR Apache-2.0"
name = "tealdeer"
readme = "README.md"
repository = "https://github.com/dbrgn/tealdeer/"
documentation = "https://dbrgn.github.io/tealdeer/"
version = "1.5.0"
include = ["/src/**/*", "/tests/**/*", "/Cargo.toml", "/README.md", "/LICENSE-*", "/screenshot.png", "/bash_tealdeer", "/fish_tealdeer"]
edition = "2018"
repository = "https://github.com/tealdeer-rs/tealdeer/"
documentation = "https://tealdeer-rs.github.io/tealdeer/"
version = "1.8.1"
include = ["/src/**/*", "/tests/**/*", "/Cargo.toml", "/README.md", "/LICENSE-*", "/screenshot.png", "completion/*"]
rust-version = "1.87" # MSRV
edition = "2021"
[[bin]]
name = "tldr"
path = "src/main.rs"
[dependencies]
ansi_term = "0.12.0"
app_dirs = { version = "2", package = "app_dirs2" }
atty = "0.2"
clap = { version = "=3.0.0-rc.11", features = ["std", "derive", "suggestions", "color"], default-features = false }
env_logger = { version = "0.9", optional = true }
anyhow = "1"
clap = { version = "4", features = ["std", "derive", "help", "usage", "cargo", "error-context", "color", "wrap_help"], default-features = false }
env_logger = { version = "0.11", optional = true }
etcetera = "0.11.0"
log = "0.4"
reqwest = { version = "0.11.3", features = ["blocking", "rustls-tls", "rustls-tls-native-roots"], default-features = false }
serde = "1.0.21"
serde_derive = "1.0.21"
toml = "0.5.1"
walkdir = "2.0.1"
zip = { version = "0.5", default-features = false, features = ["deflate"] }
ureq = { version = "3.0.8", default-features = false, features = ["gzip", "socks-proxy"] }
toml = "0.8.19"
yansi = "1"
zip = { version = "5.1.1", default-features = false, features = ["deflate"] }
[target.'cfg(not(windows))'.dependencies]
pager = "0.16"
@ -38,12 +38,24 @@ pager = "0.16"
[dev-dependencies]
assert_cmd = "2.0.1"
escargot = "0.5"
predicates = "2.0.2"
predicates = "3.1.2"
tempfile = "3.1.0"
filetime = "0.2.10"
[features]
# native-tls is not enabled by default, because it is difficult to build for musl
default = ["rustls-with-webpki-roots", "rustls-with-native-roots"]
logging = ["env_logger"]
# At least one of variants for `ureq` HTTP client must be selected.
native-tls = ["ureq/native-tls", "ureq/platform-verifier"]
rustls-with-webpki-roots = ["ureq/rustls"] # ureq uses WebPKI roots by default
rustls-with-native-roots = ["ureq/rustls", "ureq/platform-verifier"]
ignore-online-tests = []
[profile.release]
strip = true
opt-level = 3
lto = true
codegen-units = 1

View file

@ -14,12 +14,12 @@ Rust: Simplified, example based and community-driven man pages.
If you pronounce "tldr" in English, it sounds somewhat like "tealdeer". Hence the project name :)
In case you're in a hurry and just want to quickly try tealdeer, you can find static
binaries on the [GitHub releases page](https://github.com/dbrgn/tealdeer/releases/)!
binaries on the [GitHub releases page](https://github.com/tealdeer-rs/tealdeer/releases/)!
## Docs (Installing, Usage, Configuration)
User documentation is available at <https://dbrgn.github.io/tealdeer/>!
User documentation is available at <https://tealdeer-rs.github.io/tealdeer/>!
The docs are generated using [mdbook](https://rust-lang.github.io/mdBook/index.html).
They can be edited through the markdown files in the `docs/src/` directory.
@ -52,7 +52,6 @@ Docker container using sharkdp's [`hyperfine`][hyperfine-gh]
| [`fast-tldr`][fast-tldr-gh] | Haskell | 17.0 | 0.6 | no example highlighting |
| [`tldr-hs`][hs-gh] | Haskell | 25.1 | 0.5 | no example highlighting |
| [`tldr-bash`][bash-gh] | Bash | 30.0 | 0.8 | |
| [`tldr-c`][c-gh] | C | 38.4 | 1.0 | |
| [`tldr-python-client`][python-gh] | Python | 87.0 | 2.4 | |
| [`tldr-node-client`][node-gh] | JavaScript / NodeJS | 407.1 | 12.9 | |
@ -87,9 +86,20 @@ To run lints:
$ cargo clean && cargo clippy
### AI Policy
Using AI is generally discouraged. However, if it is used as part of a contribution, the contributor MUST:
1. Clearly mark what parts (if any) of a contribution were created with the help of AI tools. This includes issue and pull request comments.
2. Check all output of AI tools before sharing it with others in the tealdeer project.
3. Not post slop, spam, or low quality contributions. This includes pull request descriptions and comments with excessive text and markdown flair.
4. Leave small or easy tasks to new contributors who want to learn without the use of AI. This is to maintain the presence of the `good-first-issue` tag.
5. Be respectful of everyone's time: *maintainers and other contributors will be reviewing your PRs.*
## MSRV (Minimally Supported Rust Version)
When publishing a Tealdeer release, the Rust version required to build it
When publishing a tealdeer release, the Rust version required to build it
should be stable for at least a month.
@ -113,20 +123,19 @@ Thanks to @severen for coming up with the name "tealdeer"!
[node-gh]: https://github.com/tldr-pages/tldr-node-client
[c-gh]: https://github.com/tldr-pages/tldr-c-client
[hs-gh]: https://github.com/psibi/tldr-hs
[fast-tldr-gh]: https://github.com/gutjuri/fast-tldr
[bash-gh]: https://4e4.win/tldr
[outfieldr-gh]: https://gitlab.com/ve-nt/outfieldr
[python-gh]: https://github.com/tldr-pages/tldr-python-client
[benchmark-dockerfile]: https://github.com/dbrgn/tealdeer/blob/main/benchmarks/Dockerfile
[benchmark-dockerfile]: https://github.com/tealdeer-rs/tealdeer/blob/main/benchmarks/Dockerfile
[client-spec]: https://github.com/tldr-pages/tldr/blob/main/CLIENT-SPECIFICATION.md
[hyperfine-gh]: https://github.com/sharkdp/hyperfine
[outfieldr-comment-tls]: https://github.com/dbrgn/tealdeer/issues/129#issuecomment-833596765
[outfieldr-comment-tls]: https://github.com/tealdeer-rs/tealdeer/issues/129#issuecomment-833596765
<!-- Badges -->
[github-actions]: https://github.com/dbrgn/tealdeer/actions?query=branch%3Amain
[github-actions-badge]: https://github.com/dbrgn/tealdeer/workflows/CI/badge.svg
[github-actions]: https://github.com/tealdeer-rs/tealdeer/actions?query=branch%3Amain
[github-actions-badge]: https://github.com/tealdeer-rs/tealdeer/actions/workflows/ci.yml/badge.svg?branch=main
[crates-io]: https://crates.io/crates/tealdeer
[crates-io-badge]: https://img.shields.io/crates/v/tealdeer.svg

View file

@ -7,7 +7,7 @@ Run linting:
Set variables:
$ export VERSION=X.Y.Z
$ export GPG_KEY=EA456E8BAF0109429583EED83578F667F2F3A5FA
$ export GPG_KEY=20EE002D778AE197EF7D0D2CB993FF98A90C9AB1
Update version numbers:

View file

@ -18,7 +18,7 @@
FROM rust AS tealdeer-builder
WORKDIR /build
RUN git clone https://github.com/dbrgn/tealdeer.git \
RUN git clone https://github.com/tealdeer-rs/tealdeer.git \
&& cd tealdeer \
&& cargo build --release \
&& mkdir /build-outputs \

View file

@ -1 +0,0 @@
msrv = "1.54"

View file

@ -6,7 +6,7 @@ _tealdeer()
_init_completion || return
case $prev in
-h|--help|-v|--version|-l|--list|-u|--update|-c|--clear-cache|-p|--pager|-r|--raw|--show-paths|--seed-config|-q|--quiet)
-h|--help|-v|--version|-l|--list|-u|--update|--no-auto-update|-c|--clear-cache|--pager|-r|--raw|--show-paths|--seed-config|-q|--quiet)
return
;;
-f|--render)
@ -14,7 +14,7 @@ _tealdeer()
return
;;
-p|--platform)
COMPREPLY=( $(compgen -W 'linux macos sunos windows' -- "${cur}") )
COMPREPLY=( $(compgen -W 'linux macos sunos windows android freebsd netbsd openbsd' -- "${cur}") )
return
;;
--color)
@ -27,8 +27,9 @@ _tealdeer()
COMPREPLY=( $( compgen -W '$( _parse_help "$1" )' -- "$cur" ) )
return
fi
COMPREPLY=( $(compgen -W '$( tldr -l | tr -d , )' -- "${cur}") )
if tldrlist=$(tldr -l 2>/dev/null); then
COMPREPLY=( $(compgen -W '$( echo "$tldrlist" | tr -d , )' -- "${cur}") )
fi
}
complete -F _tealdeer tldr

28
completion/fish_tealdeer Normal file
View file

@ -0,0 +1,28 @@
#
# Completions for the tealdeer implementation of tldr
# https://github.com/tealdeer-rs/tealdeer/
#
complete -c tldr -s h -l help -d 'Print the help message.' -f
complete -c tldr -s v -l version -d 'Show version information.' -f
complete -c tldr -s l -l list -d 'List all commands in the cache.' -f
complete -c tldr -s f -l render -d 'Render a specific markdown file.' -r
complete -c tldr -s p -l platform -d 'Override the operating system.' -xa 'linux macos sunos windows android freebsd netbsd openbsd'
complete -c tldr -s L -l language -d 'Override the language' -x
complete -c tldr -s u -l update -d 'Update the local cache.' -f
complete -c tldr -l no-auto-update -d 'If auto update is configured, disable it for this run.' -f
complete -c tldr -s c -l clear-cache -d 'Clear the local cache.' -f
complete -c tldr -l pager -d 'Use a pager to page output.' -f
complete -c tldr -s r -l raw -d 'Display the raw markdown instead of rendering it.' -f
complete -c tldr -s q -l quiet -d 'Suppress informational messages.' -f
complete -c tldr -l show-paths -d 'Show file and directory paths used by tealdeer.' -f
complete -c tldr -l seed-config -d 'Create a basic config.' -f
complete -c tldr -l color -d 'Controls when to use color.' -xa 'always auto never'
function __tealdeer_entries
if set entries (tldr --list 2>/dev/null)
string replace -a -i -r "\,\s" "\n" $entries
end
end
complete -f -c tldr -a '(__tealdeer_entries)'

View file

@ -2,8 +2,9 @@
_applications() {
local -a commands
commands=(${(uonzf)"$(tldr --list 2>/dev/null)"//:/\\:})
_describe -t commands 'command' commands
if commands=(${(uonzf)"$(tldr --list 2>/dev/null)"//:/\\:}); then
_describe -t commands 'command' commands
fi
}
_tealdeer() {
@ -19,9 +20,14 @@ _tealdeer() {
macos
sunos
windows
android
freebsd
netbsd
openbsd
))'
"($I -L --language)"{-L,--language}"[Override the language settings]:lang"
"($I -u --update)"{-u,--update}"[Update the local cache]"
"($I)--no-auto-update[If auto update is configured, disable it for this run]"
"($I -c --clear-cache)"{-c,--clear-cache}"[Clear the local cache]"
"($I)--pager[Use a pager to page output]"
"($I -r --raw)"{-r,--raw}"[Display the raw markdown instead of rendering it]"

View file

@ -8,5 +8,7 @@
- [Configuration](./config.md)
- [Section: \[display\]](./config_display.md)
- [Section: \[style\]](./config_style.md)
- [Section: \[search\]](./config_search.md)
- [Section: \[updates\]](./config_updates.md)
- [Section: \[directories\]](./config_directories.md)
- [Tips and Tricks](./tips_and_tricks.md)

View file

@ -9,11 +9,15 @@ The configuration file path follows OS conventions (e.g.
`$XDG_CONFIG_HOME/tealdeer/config.toml` on Linux). The paths can be queried
with the following command:
$ tldr --show-paths
```shell
$ tldr --show-paths
```
Creating the config file can be done manually or with the help of `tldr`:
$ tldr --seed-config
```shell
$ tldr --seed-config
```
On Linux, this will usually be `~/.config/tealdeer/config.toml`.
@ -22,13 +26,14 @@ On Linux, this will usually be `~/.config/tealdeer/config.toml`.
Here's an example configuration file. Note that this example does not contain
all possible config options. For details on the things that can be configured,
please refer to the subsections of this documentation page
([display](config_display.html), [style](config_style.html),
([display](config_display.html), [style](config_style.html), [search](config_search.html),
[updates](config_updates.html) or [directories](config_directories.html)).
```toml
[display]
compact = false
use_pager = true
show_title = false
[style.command_name]
foreground = "red"
@ -52,11 +57,3 @@ auto_update = true
The directory where the configuration file resides may be overwritten by the
environment variable `TEALDEER_CONFIG_DIR`. Remember to use an absolute path.
Variable expansion will not be performed on the path.
## Override Cache Directory
Similarly, the cache directory where the pages are downloaded to, also follows
OS conventions. On Linux, it will usually be at `~/.cache/tealdeer/`. The path
can be overwritten using the environment variable `TEALDEER_CACHE_DIR`.
Remember to use an absolute path. Variable expansion will not be performed on
the path.

View file

@ -2,11 +2,28 @@
This section allows overriding some directory paths.
## `cache_dir`
Override the cache directory. Remember to use an absolute path. Variable
expansion will not be performed on the path. If the directory does not yet
exist, it will be created.
```toml
[directories]
cache_dir = "/home/myuser/.tealdeer-cache/"
```
If no `cache_dir` is specified, tealdeer will fall back to a location that
follows OS conventions. On Linux, it will usually be at `~/.cache/tealdeer/`.
Use `tldr --show-paths` to show the path that is being used.
## `custom_pages_dir`
Set the directory to be used to look up [custom
pages](usage_custom_pages.html). Remember to use an absolute path. Variable
expansion will not be performed on the path.
[directories]
custom_pages_dir = "/home/myuser/custom-tldr-pages/"
```toml
[directories]
custom_pages_dir = "/home/myuser/custom-tldr-pages/"
```

View file

@ -6,8 +6,10 @@ In the `display` section you can configure the output format.
Specifies whether the pager should be used by default or not (default `false`).
[display]
use_pager = true
```toml
[display]
use_pager = true
```
When enabled, `less -R` is used as pager. To override the pager command used,
set the `PAGER` environment variable.
@ -19,5 +21,51 @@ NOTE: This feature is not available on Windows.
Set this to enforce more compact output, where empty lines are stripped out
(default `false`).
[display]
compact = true
```toml
[display]
compact = true
```
## `show_title`
Display the command name at the top of the page output (default `false`).
```toml
[display]
show_title = true
```
When enabled, the command name will be displayed at the top of the output,
styled with the `command_name` style configuration.
## `indent`
Controls the indentation of the output via two sub-keys.
### `indent.base`
Specifies the number of spaces used to indent descriptions, example text, and titles (default `2`).
```toml
[display.indent]
base = 2
```
### `indent.command`
Specifies the number of spaces used to indent example code lines (default `6`).
```toml
[display.indent]
command = 6
```
You can also configure both subkeys in a single line like this:
```toml
[display]
indent = {
base = 2,
command = 6,
}
```

33
docs/src/config_search.md Normal file
View file

@ -0,0 +1,33 @@
# Section: \[search\]
This config section is used to configure the page search in the cache.
The settings apply to `tldr <page>` and `tldr --list`.
## `languages`
The list of languages that should be considered when searching.
If unspecified, the list of languages will be inferred from the `LANG` and `LANGUAGE` environment variables.
Either way, the language used can be overwritten using the `--language` command line flag.
```toml
[search]
# Show pages in German if available, otherwise show in English
languages = ["de", "en"]
```
## `platforms`
The list of platforms that should be considered when searching.
In addition to the platforms listed in the help text of the `--platform` flag, there are two special platforms available:
- `"current"`: equals the platform that tealdeer was compiled for
- `"all"`: adds all remaining platforms to the list
Tealdeer searches the platforms in order of appearance in this list.
The default list of platforms is `["current", "common", "all"]`.
The list of platforms can be overwritten using the `--platform` command line flag.
```toml
[search]
# Search for linux and common, and then search windows before trying the remaining platforms
platforms = ["linux", "common", "windows", "all"]
```

View file

@ -22,20 +22,26 @@ Using the config file, the style (e.g. colors or underlines) can be customized.
Colors can be specified in one of three ways:
- Color string (`black`, `red`, `green`, `yellow`, `blue`, `purple`, `cyan`, `white`):
- Color string (`black`, `red`, `green`, `yellow`, `blue`, `magenta`, `cyan`, `white`):
Example:
foreground = "green"
```toml
foreground = "green"
```
- 256 color ANSI code (*Tealdeer v1.5.0+*)
- 256 color ANSI code (*tealdeer v1.5.0+*)
Example:
foreground = { ansi = 4 }
```toml
foreground = { ansi = 4 }
```
- 24-bit RGB color (*Tealdeer v1.5.0+*)
- 24-bit RGB color (*tealdeer v1.5.0+*)
Example:
background = { rgb = { r = 255, g = 255, b = 255 } }
```toml
background = { rgb = { r = 255, g = 255, b = 255 } }
```

View file

@ -1,8 +1,10 @@
# Section: \[updates\]
This config section contains settings related to updating the tealdeer cache.
## Automatic updates
tealdeer can refresh the cache automatically when it is outdated. This
Tealdeer can refresh the cache automatically when it is outdated. This
behavior can be configured in the `updates` section and is disabled by
default.
@ -11,8 +13,10 @@ default.
Specifies whether the auto-update feature should be enabled (defaults to
`false`).
[updates]
auto_update = true
```toml
[updates]
auto_update = true
```
### `auto_update_interval_hours`
@ -20,7 +24,68 @@ Duration, since the last cache update, after which the cache will be
refreshed (defaults to 720 hours). This parameter is ignored if `auto_update`
is set to `false`.
[updates]
auto_update = true
auto_update_interval_hours = 24
```toml
[updates]
auto_update = true
auto_update_interval_hours = 24
```
### `warn_cache_age`
Controls when a warning is printed if the cache has not been updated in a while.
By default, the warning is shown once the cache is older than 30 days. Set this
to `"never"` to silence the warning. This is useful if, for some reason, the
modification time does not reflect its actual age.
```toml
[updates]
warn_cache_age = "never"
```
## Download configuration
### `download_languages`
The list of languages which should be downloaded when updating.
If unspecified, the languages listed in the `search.languages` setting are used.
Thus, this setting is the most useful to instruct tealdeer to download pages in additional languages that are not searched by default.
Either way, the language used can be overwritten using the `--language` command line flag.
```toml
[search]
languages = ["de", "en"]
[updates]
# sometimes I like to read the Italian description
download_languages = ["de", "en", "it"]
```
### `archive_source`
URL for the location of the tldr pages archive. By default the pages are
fetched from the latest `tldr-pages/tldr` GitHub release.
```toml
[updates]
archive_source = "https://my-company.example.com/tldr/"
```
### `tls_backend`
Specifies which TLS backend to use. Try changing this setting if you encounter certificate errors.
Available options:
- `rustls-with-native-roots` - [Rustls][rustls] (a TLS library in Rust) with native roots
- `rustls-with-webpki-roots` - Rustls with [WebPKI][rustls-webpki] roots
- `native-tls` - Native TLS
- SChannel on Windows
- Secure Transport on macOS
- OpenSSL on other platforms
```toml
[updates]
tls_backend = "native-tls"
```
[rustls]: https://github.com/rustls/rustls
[rustls-webpki]: https://github.com/rustls/webpki

View file

@ -1,6 +1,6 @@
# Installing
There are a few different ways to install Tealdeer:
There are a few different ways to install tealdeer:
- Through [package managers](#package-managers)
- Through [static binaries](#static-binaries-linux)
@ -14,49 +14,61 @@ autocompletions](#autocompletion).
Tealdeer has been added to a few package managers:
- Arch Linux: [`tealdeer`](https://archlinux.org/packages/community/x86_64/tealdeer/)
- Arch Linux: [`tealdeer`](https://archlinux.org/packages/extra/x86_64/tealdeer/)
- Debian: [`tealdeer`](https://tracker.debian.org/tealdeer)
- Fedora: [`tealdeer`](https://src.fedoraproject.org/rpms/rust-tealdeer)
- FreeBSD: [`sysutils/tealdeer`](https://www.freshports.org/sysutils/tealdeer/)
- Funtoo: [`app-misc/tealdeer`](https://github.com/funtoo/core-kit/tree/1.4-release/app-misc/tealdeer)
- Homebrew: [`tealdeer`](https://formulae.brew.sh/formula/tealdeer)
- MacPorts: [`tealdeer`](https://ports.macports.org/port/tealdeer/)
- NetBSD: [`sysutils/tealdeer`](https://pkgsrc.se/sysutils/tealdeer)
- Nix: [`tealdeer`](https://nixos.org/nixos/packages.html#tealdeer)
- Nix: [`tealdeer`](https://search.nixos.org/packages?query=tealdeer)
- openSUSE: [`tealdeer`](https://software.opensuse.org/package/tealdeer?search_term=tealdeer)
- Scoop: [`tealdeer`](https://github.com/ScoopInstaller/Main/blob/master/bucket/tealdeer.json)
- Solus: [`tealdeer`](https://packages.getsol.us/shannon/t/tealdeer/)
- Void Linux: [`tealdeer`](https://github.com/void-linux/void-packages/tree/master/srcpkgs/tealdeer)
## Static Binaries (Linux)
Static binary builds (currently for Linux only) are available on the
[GitHub releases page](https://github.com/dbrgn/tealdeer/releases).
[GitHub releases page](https://github.com/tealdeer-rs/tealdeer/releases).
Simply download the binary for your platform and run it!
## Through `cargo install`
Build and install the tool via cargo...
$ cargo install tealdeer
*(Note: You might need to install OpenSSL development headers, otherwise you get
a "failed to run custom build command for openssl-sys" error message. The
package is called `libssl-dev` on Ubuntu.)*
```shell
$ cargo install tealdeer
```
## Build From Source
Debug build with logging enabled:
Release build:
$ cargo build --features logging
```shell
$ cargo build --release
```
Release build without logging:
Release build with native TLS support:
$ cargo build --release
```shell
$ cargo build --release --features native-tls
```
To enable the log output, set the `RUST_LOG` env variable:
Debug build with logging support:
$ export RUST_LOG=tldr=debug
```shell
$ cargo build --features logging
```
(To enable logging at runtime, export the `RUST_LOG=tldr=debug` env variable.)
## Autocompletion
- *Bash*: copy `bash_tealdeer` to `/usr/share/bash-completion/completions/tldr`
- *Fish*: copy `fish_tealdeer` to `~/.config/fish/completions/tldr.fish`
- *Zsh*: copy `zsh_tealdeer` to `/usr/share/zsh/site-functions/_tldr`
Shell completion scripts are located in the folder `completion`.
Just copy them to their designated location:
- *Bash*: `cp completion/bash_tealdeer /usr/share/bash-completion/completions/tldr`
- *Fish*: `cp completion/fish_tealdeer ~/.config/fish/completions/tldr.fish`
- *Zsh*: `cp completion/zsh_tealdeer /usr/share/zsh/site-functions/_tldr`

View file

@ -1,13 +1,14 @@
# Tealdeer: Introduction
Tealdeer very fast implementation of [tldr](https://github.com/tldr-pages/tldr)
in Rust: Simplified, example based and community-driven man pages.
Tealdeer is a very fast implementation of
[tldr](https://github.com/tldr-pages/tldr) in Rust: Simplified, example based
and community-driven man pages.
![Screenshot](screenshot-default.png)
This documentation shows how to install, use and configure Tealdeer.
This documentation shows how to install, use and configure tealdeer.
## Links
- [GitHub Project Page](https://github.com/dbrgn/tealdeer)
- [GitHub Project Page](https://github.com/tealdeer-rs/tealdeer)
- [TLDR Pages Project](https://tldr.sh/)

View file

@ -0,0 +1,52 @@
# Tips and Tricks
This page features some example use cases of Tealdeer.
## Showing a random page on shell start
To display a randomly selected page, you can invoke `tldr` twice: One time to
select a page and a second time to display this page. To randomly select a page,
we use `shuf` from the GNU coreutils:
```bash
tldr --quiet $(tldr --quiet --list | shuf -n1)
```
You can also add the above command to your `.bashrc` (or similar shell
configuration file) to display a random page every time you start a new shell
session.
## Displaying all pages with their summary
If you want to extend the output of `tldr --list` with the first line summary of
each page, you can run the following Python script:
```python
#!/usr/bin/env python3
import subprocess
commands = subprocess.run(
["tldr", "--quiet", "--list"],
capture_output=True,
encoding="utf-8",
).stdout.splitlines()
for command in commands:
output = subprocess.run(
["tldr", "--quiet", command],
capture_output=True,
encoding="utf-8",
).stdout
description = output.lstrip().split("\n\n")[0]
description = " ".join(description.split())
print(f"{command} => {description}")
```
Note that there are a lot of pages and the script will run Tealdeer once for
every page, so the script may take a couple of seconds to finish.
## Extending this chapter
If you have an interesting setup with Tealdeer, feel free to share your
configuration on [our Github repository](https://github.com/tealdeer-rs/tealdeer).

View file

@ -1,29 +1,33 @@
tealdeer 1.5.0
tealdeer 1.8.1: A fast TLDR client
Danilo Bargen <mail@dbrgn.ch>, Niklas Mohrin <dev@niklasmohrin.de>
A fast TLDR client
USAGE:
tldr [OPTIONS] [COMMAND]...
Usage: tldr [OPTIONS] [COMMAND]...
ARGS:
<COMMAND>... The command to show (e.g. `tar` or `git log`)
Arguments:
[COMMAND]... The command to show (e.g. `tar` or `git log`)
OPTIONS:
-l, --list List all commands in the cache
-f, --render <FILE> Render a specific markdown file
-p, --platform <PLATFORM> Override the operating system [possible values: linux, macos,
windows, sunos, osx]
-L, --language <LANGUAGE> Override the language
-u, --update Update the local cache
-c, --clear-cache Clear the local cache
--pager Use a pager to page output
-r, --raw Display the raw markdown instead of rendering it
-q, --quiet Suppress informational messages
--show-paths Show file and directory paths used by tealdeer
--config-path Show config file path
--seed-config Create a basic config
--color <WHEN> Control whether to use color [possible values: always, auto, never]
-v, --version Print the version
-h, --help Print help information
Options:
-l, --list List all commands in the cache
--edit-page Edit custom page with `EDITOR`
--edit-patch Edit custom patch with `EDITOR`
-f, --render <FILE> Render a specific markdown file
-p, --platform <PLATFORM> Override the operating system, can be specified multiple times in order
of preference [possible values: linux, macos, sunos, windows, android,
freebsd, netbsd, openbsd, common]
-L, --language <LANGUAGE> Override the language
-u, --update Update the local cache
--no-auto-update If auto update is configured, disable it for this run
-c, --clear-cache Clear the local cache
--config-path <FILE> Override config file location
--pager Use a pager to page output
-r, --raw Display the raw markdown instead of rendering it
-q, --quiet Suppress informational messages
--show-paths Show file and directory paths used by tealdeer
--seed-config Create a basic config
--color <WHEN> Control whether to use color [possible values: always, auto, never]
-v, --version Print the version
-h, --help Print help
To view the user documentation, please visit https://dbrgn.github.io/tealdeer/.
To view the user documentation, please visit https://tealdeer-rs.github.io/tealdeer/.
To view usage examples, run tldr tldr or tldr tealdeer.

View file

@ -1,5 +1,13 @@
# Custom Pages and Patches
> ⚠️ **Breaking change in version 1.7.0:** The file name extension for custom
> pages and patches was changed:
>
> - `<name>.page``<name>.page.md`
> - `<name>.patch``<name>.patch.md`
>
> If you have custom pages or patches, you need to rename them.
Tealdeer allows creating new custom pages, overriding existing pages as well as
extending existing pages.
@ -15,31 +23,36 @@ file](config_directories.html).
To document internal command line tools, or if you want to replace an existing
tldr page with one that's better suited for you, place a file with the name
`<command>.page` in the custom pages directory. When calling `tldr <command>`,
`<command>.page.md` in the custom pages directory. When calling `tldr <command>`,
your custom page will be shown instead of the upstream version in the cache.
Path:
$CUSTOM_PAGES_DIR/<command>.page
```plain
$CUSTOM_PAGES_DIR/<command>.page.md
```
Example:
~/.local/share/tealdeer/pages/ufw.page
```plain
~/.local/share/tealdeer/pages/ufw.page.md
```
## Custom Patches
Sometimes you don't want to fully replace an existing upstream page, but just
want to extend it with your own examples that you frequently need. In this
case, use a file called `<command>.patch`, it will be appended to existing
case, use a file called `<command>.patch.md`, it will be appended to existing
pages.
> **Note:** Because the patch file will be concatenated directly to the page
> file, it needs to start with an empty line.
Path:
$CUSTOM_PAGES_DIR/<command>.patch
```plain
$CUSTOM_PAGES_DIR/<command>.patch.md
```
Example:
~/.local/share/tealdeer/pages/ufw.patch
```plain
~/.local/share/tealdeer/pages/ufw.patch.md
```

View file

@ -1,24 +0,0 @@
#
# Completions for the tealdeer implementation of tldr
# https://github.com/dbrgn/tealdeer/
#
complete -c tldr -s h -l help -d 'Print the help message.' -f
complete -c tldr -s v -l version -d 'Show version information.' -f
complete -c tldr -s l -l list -d 'List all commands in the cache.' -f
complete -c tldr -s f -l render -d 'Render a specific markdown file.' -r
complete -c tldr -s p -l platform -d 'Override the operating system.' -xa 'linux macos sunos windows'
complete -c tldr -s u -l update -d 'Update the local cache.' -f
complete -c tldr -s c -l clear-cache -d 'Clear the local cache.' -f
complete -c tldr -s p -l pager -d 'Use a pager to page output.' -f
complete -c tldr -s r -l raw -d 'Display the raw markdown instead of rendering it.' -f
complete -c tldr -s q -l quiet -d 'Suppress informational messages.' -f
complete -c tldr -l show-paths -d 'Show file and directory paths used by tealdeer.' -f
complete -c tldr -l seed-config -d 'Create a basic config.' -f
complete -c tldr -l color -d 'Controls when to use color.' -xa 'always auto never'
function __tealdeer_entries
tldr --list | string replace -a -i -r "\,\s" "\n"
end
complete -f -c tldr -a '(__tealdeer_entries)'

42
pages/tealdeer.md Normal file
View file

@ -0,0 +1,42 @@
# tldr
> This is a builtin page that shows information for your installed tealdeer version.
> More information: <https://tealdeer-rs.github.io/tealdeer/>.
> This page shows tealdeer specific functionality. See tldr tldr for more examples.
- Render a local markdown file as a tldr page:
`tldr --render {{path/to/file.md}}`
- Show the raw markdown source of a page instead of rendering it:
`tldr --raw {{command}}`
- Show file and directory paths used by tealdeer:
`tldr --show-paths`
- Create an initial config file:
`tldr --seed-config`
- Override config file location:
`tldr --config-path <FILE>`
- Open a custom page for a command in `$EDITOR` (creates it if it doesn't exist):
`tldr --edit-page {{command}}`
- Open a custom patch for a command in `$EDITOR` (appended to the existing page):
`tldr --edit-patch {{command}}`
- Clear the local cache:
`tldr --clear-cache`
- If auto update is configured, disable it for this run:
`tldr --no-auto-update`

1
rustfmt.toml Normal file
View file

@ -0,0 +1 @@
# Empty file, use defaults and disregard global settings

View file

@ -29,7 +29,7 @@ create_release() {
--header "Authorization: Bearer $token" \
--header "Content-Type:application/json" \
"https://api.github.com/repos/$repo/releases" \
-d '{"tag_name":"'"$tag"'","name":"'"${tag/v/Release }"'","draft":true,"body":"'"${description/\"/\\\"}"'"}'
-d '{"tag_name":"'"$tag"'","name":"'"${tag/v/Version }"'","draft":true,"body":"'"${description/\"/\\\"}"'"}'
)
if [ "$http_code" == "201" ]; then
echo "Release for tag $tag created."

View file

@ -1,32 +1,39 @@
use std::{
env,
ffi::OsStr,
fs::{self, File},
io::{BufReader, Cursor, Read, Seek},
io::{Cursor, ErrorKind, Read},
path::{Path, PathBuf},
time::{Duration, SystemTime},
};
use app_dirs::{get_app_root, AppDataType};
use log::debug;
use reqwest::{blocking::Client, Proxy};
use std::time::{Duration, SystemTime};
use walkdir::{DirEntry, WalkDir};
use anyhow::{anyhow, bail, ensure, Context, Result};
use log::{debug, info};
use ureq::{
http::StatusCode,
tls::{RootCerts, TlsConfig, TlsProvider},
Agent,
};
use zip::ZipArchive;
use crate::{
error::TealdeerError::{self, CacheError, UpdateError},
types::{PathSource, PlatformType},
config::{Language, TlsBackend},
types::PlatformType,
};
static CACHE_DIR_ENV_VAR: &str = "TEALDEER_CACHE_DIR";
pub static TLDR_PAGES_DIR: &str = "tldr-pages";
static TLDR_OLD_PAGES_DIR: &str = "tldr-master";
pub static TLDR_OLD_PAGES_DIR: &str = "tldr-master";
#[derive(Debug)]
pub struct Cache {
url: String,
platform: PlatformType,
#[derive(Clone)]
pub struct CacheConfig<'a> {
pub pages_directory: &'a Path,
pub custom_pages_directory: Option<&'a Path>,
pub platforms: &'a [PlatformType],
pub search_languages: &'a [Language<'a>],
pub download_languages: &'a [Language<'a>],
}
/// The directory backing this cache is checked to be populated at construction.
pub struct Cache<'a> {
config: CacheConfig<'a>,
}
#[derive(Debug)]
@ -35,6 +42,228 @@ pub struct PageLookupResult {
pub patch_path: Option<PathBuf>,
}
impl<'a> Cache<'a> {
/// Try opening a cache at the location given by `config.pages_directory`. If no directory
/// exists at this location, `Ok(None)` is returned.
pub fn open(config: CacheConfig<'a>) -> Result<Option<Self>> {
match config.pages_directory.metadata() {
Ok(md) => {
ensure!(
md.is_dir(),
"Cache directory `{}` exists, but is not a directory.",
config.pages_directory.display(),
);
Ok(Some(Cache { config }))
}
Err(err) if err.kind() == ErrorKind::NotFound => Ok(None),
Err(err) => Err(anyhow!(err).context(format!(
"Error getting metdata of cache directory {}",
config.pages_directory.display()
))),
}
}
/// Open an existing cache at `config.pages_directory` or create one if no cache resides at
/// this location. In case of success, the return value is a tuple with the `Cache` and a
/// boolean indicating whether the cache was newly created.
pub fn open_or_create(config: CacheConfig<'a>) -> Result<(Self, bool)> {
if let Some(cache) = Self::open(config.clone())? {
return Ok((cache, false));
}
fs::create_dir_all(config.pages_directory).with_context(|| {
format!(
"Cache directory `{}` cannot be created",
config.pages_directory.display(),
)
})?;
eprintln!(
"Successfully created cache directory `{}`.",
config.pages_directory.display(),
);
Ok((Cache { config }, true))
}
pub fn age(&self) -> Result<Duration> {
let mtime = self.config.pages_directory.metadata()?.modified()?;
SystemTime::now()
.duration_since(mtime)
.context("Error comparing cache mtime with current time")
}
pub fn find_page(&self, command: &str) -> Option<PageLookupResult> {
let page_filename = format!("{command}.md");
let patch_filename = format!("{command}.patch.md");
let custom_filename = format!("{command}.page.md");
if let Some(custom_pages_dir) = self.config.custom_pages_directory {
let custom_page = custom_pages_dir.join(custom_filename);
if custom_page.is_file() {
return Some(PageLookupResult::with_page(custom_page));
}
}
let patch_path = self
.config
.custom_pages_directory
.map(|dir| dir.join(&patch_filename))
.filter(|path| path.is_file());
for &platform in self.config.platforms {
for language in self.config.search_languages {
let mut search_path = self.config.pages_directory.to_path_buf();
search_path.push(language.directory_name());
search_path.push(platform.directory_name());
search_path.push(&page_filename);
if search_path.is_file() {
return Some(
PageLookupResult::with_page(search_path).with_optional_patch(patch_path),
);
}
}
}
None
}
pub fn list_pages(&self) -> Result<impl IntoIterator<Item = String>> {
let mut pages = Vec::new();
let mut append_all = |directory: &Path, suffix: &str| -> Result<()> {
let Ok(file_iter) = fs::read_dir(directory) else {
return Ok(());
};
for entry in file_iter {
let entry = entry?;
if entry.file_type()?.is_file() {
let mut page_path = entry
.file_name()
.into_string()
.map_err(|_| anyhow!("Found invalid filename: {:?}", entry.path()))?;
if page_path.ends_with(suffix) {
page_path.truncate(page_path.len() - suffix.len());
pages.push(page_path);
} else {
debug!(
"Skipping page entry not ending in \".md\": {:?}",
entry.path(),
);
}
}
}
Ok(())
};
let mut search_path = self.config.pages_directory.to_path_buf();
for language in self.config.search_languages {
search_path.push(language.directory_name());
for platform in self.config.platforms {
search_path.push(platform.directory_name());
append_all(&search_path, ".md")?;
search_path.pop();
}
search_path.pop();
}
if let Some(custom_pages_dir) = self.config.custom_pages_directory {
append_all(custom_pages_dir, ".page.md")?;
}
pages.sort_unstable();
pages.dedup();
Ok(pages)
}
pub fn old_custom_pages_exist(&self) -> Result<bool> {
let Some(directory) = self.config.custom_pages_directory else {
return Ok(false);
};
let Ok(file_iter) = fs::read_dir(directory) else {
return Ok(false);
};
for entry in file_iter {
if let Some(extension) = entry?.path().extension() {
if extension == "page" || extension == "patch" {
return Ok(true);
}
}
}
Ok(false)
}
pub fn clear(self) -> Result<()> {
fs::remove_dir_all(self.config.pages_directory).with_context(|| {
format!(
"Could not remove pages directory at {}",
self.config.pages_directory.display(),
)
})
}
/// Download archives for the languages in `self.config().download_languages` and replace the
/// pages directory with the newly downloaded pages. As not all languages might have pages
/// available (for example, `en_US` instead of `en`), an iterator yielding all languages which
/// were successfully downloaded is returned.
pub fn update(
&mut self,
archive_url: &str,
tls_backend: TlsBackend,
) -> Result<impl IntoIterator<Item = Language<'_>>> {
let client = Self::build_client(tls_backend);
// Download everything before deleting anything
let mut archives = self
.config
.download_languages
.iter()
.map(|&lang| {
Ok((
lang,
Self::download(
&client,
&format!("{archive_url}/tldr-{}.zip", lang.directory_name()),
)?
.map(|bytes| ZipArchive::new(Cursor::new(bytes)))
.transpose()?,
))
})
.collect::<Result<Vec<_>>>()?;
// Clear cache directory
// Note: This is not the best solution. Ideally we would download the
// archive to a temporary directory and then swap the two directories.
// But renaming a directory doesn't work across filesystems and Rust
// does not yet offer a recursive directory copying function. So for
// now, we'll use this approach.
fs::remove_dir_all(self.config.pages_directory)?;
fs::create_dir(self.config.pages_directory)?;
for (lang, archive) in &mut archives {
if let Some(archive) = archive {
info!("Extracting archive for {lang:?}");
archive.extract(self.config.pages_directory.join(lang.directory_name()))?;
} else {
info!("No archive found for {lang:?}");
}
}
Ok(archives
.into_iter()
.filter_map(|(lang, archive)| archive.is_some().then_some(lang)))
}
pub fn config(&self) -> &CacheConfig<'a> {
&self.config
}
}
impl PageLookupResult {
pub fn with_page(page_path: PathBuf) -> Self {
Self {
@ -48,21 +277,21 @@ impl PageLookupResult {
self
}
/// Create a buffered reader that sequentially reads from the page and the
/// Create a reader that sequentially reads from the page and the
/// patch, as if they were concatenated.
///
/// This will return an error if either the page file or the patch file
/// cannot be opened.
pub fn reader(&self) -> Result<BufReader<Box<dyn Read>>, String> {
pub fn reader(&self) -> Result<Box<dyn Read>> {
// Open page file
let page_file = File::open(&self.page_path)
.map_err(|msg| format!("Could not open page file at {:?}: {}", self.page_path, msg))?;
.with_context(|| format!("Could not open page file at {}", self.page_path.display()))?;
// Open patch file
let patch_file_opt = match &self.patch_path {
Some(path) => Some(
File::open(path)
.map_err(|msg| format!("Could not open patch file at {:?}: {}", path, msg))?,
.with_context(|| format!("Could not open patch file at {}", path.display()))?,
),
None => None,
};
@ -73,314 +302,76 @@ impl PageLookupResult {
// the page and patch files and that will read them sequentially,
// because it avoids the boxing below. However, the performance impact
// would first need to be shown to be significant using a benchmark.
Ok(BufReader::new(if let Some(patch_file) = patch_file_opt {
Ok(if let Some(patch_file) = patch_file_opt {
Box::new(page_file.chain(&b"\n"[..]).chain(patch_file)) as Box<dyn Read>
} else {
Box::new(page_file) as Box<dyn Read>
}))
})
}
}
pub enum CacheFreshness {
/// The cache is still fresh (less than MAX_CACHE_AGE old)
Fresh,
/// The cache is stale and should be updated
Stale(Duration),
/// The cache is missing
Missing,
impl Language<'_> {
fn directory_name(&self) -> String {
format!("pages.{}", self.0)
}
}
impl Cache {
pub fn new<S>(url: S, platform: PlatformType) -> Self
where
S: Into<String>,
{
Self {
url: url.into(),
platform,
}
}
/// Return the path to the cache directory.
pub fn get_cache_dir() -> Result<(PathBuf, PathSource), TealdeerError> {
// Allow overriding the cache directory by setting the env variable.
if let Ok(value) = env::var(CACHE_DIR_ENV_VAR) {
let path = PathBuf::from(value);
let (path_exists, path_is_dir) = path
.metadata()
.map_or((false, false), |md| (true, md.is_dir()));
if path_exists && !path_is_dir {
return Err(CacheError(format!(
"Path specified by ${} is not a directory.",
CACHE_DIR_ENV_VAR
)));
}
if !path_exists {
// Try to create the complete directory path.
fs::create_dir_all(&path).map_err(|_| {
CacheError(format!(
"Directory path specified by ${} cannot be created.",
CACHE_DIR_ENV_VAR
))
})?;
eprintln!(
"Successfully created cache directory path `{}`.",
path.to_str().unwrap()
);
}
return Ok((path, PathSource::EnvVar));
};
// Otherwise, fall back to user cache directory.
match get_app_root(AppDataType::UserCache, &crate::APP_INFO) {
Ok(dirs) => Ok((dirs, PathSource::OsConvention)),
Err(_) => Err(CacheError(
"Could not determine user cache directory.".into(),
)),
}
}
/// Download the archive
fn download(&self) -> Result<Vec<u8>, TealdeerError> {
let mut builder = Client::builder();
if let Ok(ref host) = env::var("HTTP_PROXY") {
if let Ok(proxy) = Proxy::http(host) {
builder = builder.proxy(proxy);
}
}
if let Ok(ref host) = env::var("HTTPS_PROXY") {
if let Ok(proxy) = Proxy::https(host) {
builder = builder.proxy(proxy);
}
}
let client = builder.build().unwrap_or_else(|_| Client::new());
let mut resp = client.get(&self.url).send()?;
let mut buf: Vec<u8> = vec![];
let bytes_downloaded = resp.copy_to(&mut buf)?;
debug!("{} bytes downloaded", bytes_downloaded);
Ok(buf)
}
/// Decompress and open the archive
fn decompress<R: Read + Seek>(reader: R) -> ZipArchive<R> {
ZipArchive::new(reader).unwrap()
}
/// Update the pages cache.
pub fn update(&self) -> Result<(), TealdeerError> {
// First, download the compressed data
let bytes: Vec<u8> = self.download()?;
// Decompress the response body into an `Archive`
let mut archive = Self::decompress(Cursor::new(bytes));
// Determine paths
let (cache_dir, _) = Self::get_cache_dir()?;
let pages_dir = cache_dir.join(TLDR_PAGES_DIR);
// Make sure that cache directory exists
debug!("Ensure cache directory {:?} exists", &cache_dir);
fs::create_dir_all(&cache_dir)
.map_err(|e| UpdateError(format!("Could not create cache directory: {}", e)))?;
// Clear cache directory
// Note: This is not the best solution. Ideally we would download the
// archive to a temporary directory and then swap the two directories.
// But renaming a directory doesn't work across filesystems and Rust
// does not yet offer a recursive directory copying function. So for
// now, we'll use this approach.
Self::clear()?;
// Extract archive
archive
.extract(&pages_dir)
.map_err(|e| UpdateError(format!("Could not unpack compressed data: {}", e)))?;
Ok(())
}
/// Return the duration since the cache directory was last modified.
pub fn last_update() -> Option<Duration> {
if let Ok((cache_dir, _)) = Self::get_cache_dir() {
if let Ok(metadata) = fs::metadata(cache_dir.join(TLDR_PAGES_DIR)) {
if let Ok(mtime) = metadata.modified() {
let now = SystemTime::now();
return now.duration_since(mtime).ok();
};
};
};
None
}
/// Return the freshness of the cache (fresh, stale or missing).
pub fn freshness() -> CacheFreshness {
match Cache::last_update() {
Some(ago) if ago > crate::config::MAX_CACHE_AGE => CacheFreshness::Stale(ago),
Some(_) => CacheFreshness::Fresh,
None => CacheFreshness::Missing,
}
}
/// Return the platform directory.
fn get_platform_dir(&self) -> &'static str {
match self.platform {
impl PlatformType {
fn directory_name(self) -> &'static str {
match self {
PlatformType::Linux => "linux",
PlatformType::OsX => "osx",
PlatformType::SunOs => "sunos",
PlatformType::Windows => "windows",
PlatformType::Android => "android",
PlatformType::FreeBsd => "freebsd",
PlatformType::NetBsd => "netbsd",
PlatformType::OpenBsd => "openbsd",
PlatformType::Common => "common",
}
}
}
/// Check for pages for a given platform in one of the given languages.
fn find_page_for_platform(
page_name: &str,
cache_dir: &Path,
platform: &str,
language_dirs: &[String],
) -> Option<PathBuf> {
language_dirs
.iter()
.map(|lang_dir| cache_dir.join(lang_dir).join(platform).join(page_name))
.find(|path| path.exists() && path.is_file())
}
/// Look up custom patch (<name>.patch). If it exists, store it in a variable.
fn find_patch(patch_name: &str, custom_pages_dir: Option<&Path>) -> Option<PathBuf> {
custom_pages_dir
.map(|custom_dir| custom_dir.join(patch_name))
.filter(|path| path.exists() && path.is_file())
}
/// Search for a page and return the path to it.
pub fn find_page(
&self,
name: &str,
languages: &[String],
custom_pages_dir: Option<&Path>,
) -> Option<PageLookupResult> {
let page_filename = format!("{}.md", name);
let patch_filename = format!("{}.patch", name);
let custom_filename = format!("{}.page", name);
// Get cache dir
let cache_dir = match Self::get_cache_dir() {
Ok((cache_dir, _)) => cache_dir.join(TLDR_PAGES_DIR),
Err(e) => {
log::error!("Could not get cache directory: {}", e);
return None;
}
impl Cache<'_> {
fn build_client(tls_backend: TlsBackend) -> Agent {
let tls_builder = match tls_backend {
#[cfg(feature = "native-tls")]
TlsBackend::NativeTls => TlsConfig::builder()
.provider(TlsProvider::NativeTls)
.root_certs(RootCerts::PlatformVerifier),
#[cfg(feature = "rustls-with-webpki-roots")]
TlsBackend::RustlsWithWebpkiRoots => TlsConfig::builder()
.provider(TlsProvider::Rustls)
.root_certs(RootCerts::WebPki),
#[cfg(feature = "rustls-with-native-roots")]
TlsBackend::RustlsWithNativeRoots => TlsConfig::builder()
.provider(TlsProvider::Rustls)
.root_certs(RootCerts::PlatformVerifier),
};
let config = Agent::config_builder()
.http_status_as_error(false) // because we want to handle them
.tls_config(tls_builder.build())
.build();
let lang_dirs: Vec<String> = languages
.iter()
.map(|lang| {
if lang == "en" {
String::from("pages")
} else {
format!("pages.{}", lang)
}
})
.collect();
config.into()
}
// Look up custom page (<name>.page). If it exists, return it directly
if let Some(config_dir) = custom_pages_dir {
let custom_page = config_dir.join(custom_filename);
if custom_page.exists() && custom_page.is_file() {
return Some(PageLookupResult::with_page(custom_page));
/// Download the archive from the specified URL.
fn download(client: &Agent, archive_url: &str) -> Result<Option<Vec<u8>>> {
info!("Downloading archive from {archive_url}");
let response = client.get(archive_url).call();
match response {
Ok(response) if response.status().is_success() => {
let mut buf: Vec<u8> = Vec::new();
response.into_body().into_reader().read_to_end(&mut buf)?;
debug!("{} bytes downloaded", buf.len());
Ok(Some(buf))
}
Ok(response) if response.status() == StatusCode::NOT_FOUND => Ok(None),
_ => {
bail!("Could not download tldr pages from {archive_url}: {response:?}")
}
}
let patch_path = Self::find_patch(&patch_filename, custom_pages_dir);
// Try to find a platform specific path next, append custom patch to it.
let platform_dir = self.get_platform_dir();
if let Some(page) =
Self::find_page_for_platform(&page_filename, &cache_dir, platform_dir, &lang_dirs)
{
return Some(PageLookupResult::with_page(page).with_optional_patch(patch_path));
}
// Did not find platform specific results, fall back to "common"
Self::find_page_for_platform(&page_filename, &cache_dir, "common", &lang_dirs)
.map(|page| PageLookupResult::with_page(page).with_optional_patch(patch_path))
}
/// Return the available pages.
pub fn list_pages(&self) -> Result<Vec<String>, TealdeerError> {
// Determine platforms directory and platform
let (cache_dir, _) = Self::get_cache_dir()?;
let platforms_dir = cache_dir.join(TLDR_PAGES_DIR).join("pages");
let platform_dir = self.get_platform_dir();
// Closure that allows the WalkDir instance to traverse platform
// specific and common page directories, but not others.
let should_walk = |entry: &DirEntry| -> bool {
let file_type = entry.file_type();
let file_name = match entry.file_name().to_str() {
Some(name) => name,
None => return false,
};
if file_type.is_dir() {
return file_name == "common" || file_name == platform_dir;
} else if file_type.is_file() {
return true;
}
false
};
// Recursively walk through common and (if applicable) platform specific directory
let mut pages = WalkDir::new(platforms_dir)
.min_depth(1) // Skip root directory
.into_iter()
.filter_entry(|e| should_walk(e)) // Filter out pages for other architectures
.filter_map(Result::ok) // Convert results to options, filter out errors
.filter_map(|e| {
let path = e.path();
let extension = &path.extension().and_then(OsStr::to_str).unwrap_or("");
if e.file_type().is_file() && extension == &"md" {
path.file_stem()
.and_then(|stem| stem.to_str().map(Into::into))
} else {
None
}
})
.collect::<Vec<String>>();
pages.sort();
pages.dedup();
Ok(pages)
}
/// Delete the cache directory.
pub fn clear() -> Result<(), TealdeerError> {
let (path, _) = Self::get_cache_dir()?;
if path.exists() && path.is_dir() {
// Delete old tldr-pages cache location as well if present
// TODO: To be removed in the future
for pages_dir_name in [TLDR_PAGES_DIR, TLDR_OLD_PAGES_DIR] {
let pages_dir = path.join(pages_dir_name);
if pages_dir.exists() {
fs::remove_dir_all(&pages_dir).map_err(|e| {
CacheError(format!(
"Could not remove cache directory ({}): {}",
pages_dir.display(),
e
))
})?;
}
}
} else if path.exists() {
return Err(CacheError(format!(
"Cache path ({}) is not a directory.",
path.display()
)));
} else {
return Err(CacheError(format!(
"Cache path ({}) does not exist.",
path.display()
)));
};
Ok(())
}
}
@ -398,8 +389,8 @@ mod tests {
fn test_reader_with_patch() {
// Write test files
let dir = tempfile::tempdir().unwrap();
let page_path = dir.path().join("test.page");
let patch_path = dir.path().join("test.patch");
let page_path = dir.path().join("test.page.md");
let patch_path = dir.path().join("test.patch.md");
{
let mut f1 = File::create(&page_path).unwrap();
f1.write_all(b"Hello\n").unwrap();
@ -422,7 +413,7 @@ mod tests {
fn test_reader_without_patch() {
// Write test file
let dir = tempfile::tempdir().unwrap();
let page_path = dir.path().join("test.page");
let page_path = dir.path().join("test.page.md");
{
let mut f = File::create(&page_path).unwrap();
f.write_all(b"Hello\n").unwrap();

112
src/cli.rs Normal file
View file

@ -0,0 +1,112 @@
//! Definition of the CLI arguments and options.
use std::path::PathBuf;
use clap::{builder::ArgAction, ArgGroup, Parser};
use crate::types::{ColorOptions, PlatformType};
// Note: flag names are specified explicitly in clap attributes
// to improve readability and allow contributors to grep names like "clear-cache"
#[derive(Parser, Debug)]
#[command(
about = "A fast TLDR client",
version,
disable_version_flag = true,
author,
help_template = "{before-help}{name} {version}: {about-with-newline}{author-with-newline}
{usage-heading} {usage}
{all-args}{after-help}",
after_help = "To view the user documentation, please visit https://tealdeer-rs.github.io/tealdeer/.
To view usage examples, run tldr tldr or tldr tealdeer.",
arg_required_else_help = true,
help_expected = true,
group = ArgGroup::new("command_or_file").args(&["command", "render"]),
)]
pub(crate) struct Cli {
/// The command to show (e.g. `tar` or `git log`)
#[arg(num_args(1..))]
pub command: Vec<String>,
/// List all commands in the cache
#[arg(short = 'l', long = "list")]
pub list: bool,
/// Edit custom page with `EDITOR`
#[arg(long, requires = "command")]
pub edit_page: bool,
/// Edit custom patch with `EDITOR`
#[arg(long, requires = "command", conflicts_with = "edit_page")]
pub edit_patch: bool,
/// Render a specific markdown file
#[arg(
short = 'f',
long = "render",
value_name = "FILE",
conflicts_with = "command"
)]
pub render: Option<PathBuf>,
/// Override the operating system, can be specified multiple times in order of preference
#[arg(
short = 'p',
long = "platform",
value_name = "PLATFORM",
action = ArgAction::Append,
)]
pub platforms: Option<Vec<PlatformType>>,
/// Override the language
#[arg(short = 'L', long = "language")]
pub language: Option<String>,
/// Update the local cache
#[arg(short = 'u', long = "update")]
pub update: bool,
/// If auto update is configured, disable it for this run
#[arg(long = "no-auto-update", requires = "command_or_file")]
pub no_auto_update: bool,
/// Clear the local cache
#[arg(short = 'c', long = "clear-cache")]
pub clear_cache: bool,
/// Override config file location
#[arg(long = "config-path", value_name = "FILE")]
pub config_path: Option<PathBuf>,
/// Use a pager to page output
#[arg(long = "pager", requires = "command_or_file")]
pub pager: bool,
/// Display the raw markdown instead of rendering it
#[arg(short = 'r', long = "raw", requires = "command_or_file")]
pub raw: bool,
/// Suppress informational messages
#[arg(short = 'q', long = "quiet")]
pub quiet: bool,
/// Show file and directory paths used by tealdeer
#[arg(long = "show-paths")]
pub show_paths: bool,
/// Create a basic config
#[arg(long = "seed-config")]
pub seed_config: bool,
/// Control whether to use color
#[arg(long = "color", value_name = "WHEN")]
pub color: Option<ColorOptions>,
/// Print the version
// Note: We override the version flag because clap uses `-V` by default,
// while TLDR specification requires `-v` to be used.
#[arg(short = 'v', long = "version", action = ArgAction::Version)]
pub version: (),
}

File diff suppressed because it is too large Load diff

View file

@ -1,40 +0,0 @@
use std::fmt;
use reqwest::Error as ReqwestError;
#[derive(Debug)]
#[allow(clippy::enum_variant_names)]
pub enum TealdeerError {
CacheError(String),
ConfigError(String),
UpdateError(String),
WriteError(String),
}
impl TealdeerError {
pub fn message(&self) -> &str {
match self {
Self::CacheError(msg)
| Self::ConfigError(msg)
| Self::UpdateError(msg)
| Self::WriteError(msg) => msg,
}
}
}
impl From<ReqwestError> for TealdeerError {
fn from(err: ReqwestError) -> Self {
Self::UpdateError(format!("HTTP error: {}", err.to_string()))
}
}
impl fmt::Display for TealdeerError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::CacheError(e) => write!(f, "CacheError: {}", e),
Self::ConfigError(e) => write!(f, "ConfigError: {}", e),
Self::UpdateError(e) => write!(f, "UpdateError: {}", e),
Self::WriteError(e) => write!(f, "WriteError: {}", e),
}
}
}

View file

@ -1,14 +1,14 @@
use std::mem;
/// An extension trait to clear duplicates from a collection.
pub(crate) trait Dedup<T: PartialEq + Clone> {
pub(crate) trait Dedup<T: PartialEq> {
fn clear_duplicates(&mut self);
}
/// Clear duplicates from a collection, keep the first one seen.
///
/// For small vectors, this will be faster than a `HashSet`.
impl<T: PartialEq + Clone> Dedup<T> for Vec<T> {
impl<T: PartialEq> Dedup<T> for Vec<T> {
fn clear_duplicates(&mut self) {
let orig = mem::replace(self, Vec::with_capacity(self.len()));
for item in orig {

View file

@ -1,26 +1,62 @@
//! Functions related to formatting and printing lines from a `Tokenizer`.
use crate::{extensions::FindFrom, types::LineType};
use log::debug;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
use crate::{config::Indent, extensions::FindFrom, types::LineType};
#[derive(Debug, Clone, Copy, Eq)]
/// Represents a snippet from a page of a specific highlighting class.
pub enum PageSnippet<'a> {
CommandName(&'a str),
Variable(&'a str),
NormalCode(&'a str),
Description(&'a str),
Text(&'a str),
pub enum PageSnippet<T> {
CommandName(T),
Variable(T),
NormalCode(T),
Description(T),
Text(T),
Title(T),
Linebreak,
}
impl<'a> PageSnippet<'a> {
#[cfg_attr(not(test), allow(dead_code))]
impl<T> PageSnippet<T> {
pub fn map<F, U>(self, f: F) -> PageSnippet<U>
where
F: FnOnce(T) -> U,
{
match self {
PageSnippet::CommandName(s) => PageSnippet::CommandName(f(s)),
PageSnippet::Variable(s) => PageSnippet::Variable(f(s)),
PageSnippet::NormalCode(s) => PageSnippet::NormalCode(f(s)),
PageSnippet::Description(s) => PageSnippet::Description(f(s)),
PageSnippet::Text(s) => PageSnippet::Text(f(s)),
PageSnippet::Title(s) => PageSnippet::Title(f(s)),
PageSnippet::Linebreak => PageSnippet::Linebreak,
}
}
}
impl<T: PartialEq<U>, U> PartialEq<PageSnippet<U>> for PageSnippet<T> {
fn eq(&self, other: &PageSnippet<U>) -> bool {
match (self, other) {
(PageSnippet::CommandName(s), PageSnippet::CommandName(t))
| (PageSnippet::Variable(s), PageSnippet::Variable(t))
| (PageSnippet::NormalCode(s), PageSnippet::NormalCode(t))
| (PageSnippet::Description(s), PageSnippet::Description(t))
| (PageSnippet::Text(s), PageSnippet::Text(t))
| (PageSnippet::Title(s), PageSnippet::Title(t)) => s == t,
(PageSnippet::Linebreak, PageSnippet::Linebreak) => true,
_ => false,
}
}
}
impl PageSnippet<&str> {
pub fn is_empty(&self) -> bool {
use PageSnippet::*;
match self {
CommandName(s) | Variable(s) | NormalCode(s) | Description(s) | Text(s) => s.is_empty(),
CommandName(s) | Variable(s) | NormalCode(s) | Description(s) | Text(s) | Title(s) => {
s.is_empty()
}
Linebreak => false,
}
}
@ -31,11 +67,15 @@ pub fn highlight_lines<L, F, E>(
lines: L,
process_snippet: &mut F,
keep_empty_lines: bool,
show_title: bool,
indent: Indent,
) -> Result<(), E>
where
L: Iterator<Item = LineType>,
F: for<'snip> FnMut(PageSnippet<'snip>) -> Result<(), E>,
F: for<'snip> FnMut(PageSnippet<&'snip str>) -> Result<(), E>,
{
let base_indent = " ".repeat(indent.base);
let command_indent = " ".repeat(indent.command);
let mut command = String::new();
for line in lines {
match line {
@ -45,51 +85,122 @@ where
}
}
LineType::Title(title) => {
debug!("Ignoring title");
if show_title {
process_snippet(PageSnippet::Linebreak)?;
process_snippet(PageSnippet::Title(&base_indent))?;
process_snippet(PageSnippet::Title(&title))?;
process_snippet(PageSnippet::Linebreak)?;
} else {
debug!("Ignoring title");
}
// This is safe as long as the parsed title is only the command,
// and the iterator yields values in order of appearance.
command = title;
debug!("Detected command name: {}", &command);
debug!("Detected command name: {command}");
}
LineType::Description(text) => {
process_snippet(PageSnippet::Description(&base_indent))?;
process_snippet(PageSnippet::Description(&text))?;
process_snippet(PageSnippet::Linebreak)?;
}
LineType::ExampleText(text) => {
process_snippet(PageSnippet::Text(&base_indent))?;
process_snippet(PageSnippet::Text(&text))?;
process_snippet(PageSnippet::Linebreak)?;
}
LineType::Description(text) => process_snippet(PageSnippet::Description(&text))?,
LineType::ExampleText(text) => process_snippet(PageSnippet::Text(&text))?,
LineType::ExampleCode(text) => {
process_snippet(PageSnippet::NormalCode(" "))?;
process_snippet(PageSnippet::NormalCode(&command_indent))?;
highlight_code(&command, &text, process_snippet)?;
process_snippet(PageSnippet::Linebreak)?;
}
LineType::Other(text) => debug!("Unknown line type: {:?}", text),
LineType::Other(text) => debug!("Unknown line type: {text:?}"),
}
}
process_snippet(PageSnippet::Linebreak)?;
Ok(())
}
/// Highlight code examples including user variables in {{ curly braces }}.
fn highlight_code<'a, E>(
command: &'a str,
text: &'a str,
process_snippet: &mut impl FnMut(PageSnippet<'a>) -> Result<(), E>,
/// Highlight code examples.
/// - parse placeholders (`{{ curly braces }}`)
/// - replace escaped placeholder markers (`\{\{` and `\}\}`)
fn highlight_code<E>(
command: &str,
mut text: &str,
process_snippet: &mut impl FnMut(PageSnippet<&str>) -> Result<(), E>,
) -> Result<(), E> {
let variable_splits = text
.split("}}")
.map(|s| s.split_once("{{").unwrap_or((s, "")));
for (code_segment, variable) in variable_splits {
highlight_code_segment(command, code_segment, process_snippet)?;
process_snippet(PageSnippet::Variable(variable))?;
// We replace escaped placeholder markers at the end so that our replacing does not interfere
// with finding the actual markers.
// NOTE: This is not optimal, as it allocates one String for each `replace`
let replace_escaped = |s: &str| s.replace(r"\{\{", "{{").replace(r"\}\}", "}}");
loop {
// Find placeholder markers and split into code and placeholder accordingly
let Some(start_marker) = find_marker(text, "{{", r"\{\{") else {
break;
};
let Some(mut end_marker) = find_marker(&text[start_marker + 2..], "}}", r"\}\}") else {
break;
};
end_marker += start_marker + 2;
// Greedily extend matched range
while end_marker + 2 < text.len() && text.as_bytes()[end_marker + 2] == b'}' {
end_marker += 1;
}
let placeholder_content = &text[start_marker + 2..end_marker];
if start_marker > 0 {
highlight_code_segment(
command,
&replace_escaped(&text[..start_marker]),
process_snippet,
)?;
}
process_snippet(PageSnippet::Variable(&replace_escaped(placeholder_content)))?;
text = &text[end_marker + 2..];
}
if !text.is_empty() {
highlight_code_segment(command, &replace_escaped(text), process_snippet)?;
}
Ok(())
}
/// Yields `NormalCode` and `CommandName` in alternating order according to the occurences of
/// Find a "{{" (or "}}") substring that does not overlap with a preceding "\{\{" (or "\}\}").
fn find_marker(s: &str, marker: &str, forbidden_prefix: &str) -> Option<usize> {
let mut search_start = 0;
loop {
let marker_index = s.find_from(marker, search_start)?;
let overlaps_with_prefix = (forbidden_prefix.len() <= marker_index + 1) && {
let prefix_start = marker_index + 1 - forbidden_prefix.len();
// NOTE: The indices might not be valid character offsets, so we should do this
// comparison on raw bytes. If prefix_start is indeed not a character offset than the
// comparison is guaranteed to return false because forbidden_prefix[0] definitely _is_
// the start of a (single byte, ASCII) character.
&s.as_bytes()[prefix_start..=marker_index] == forbidden_prefix.as_bytes()
};
if !overlaps_with_prefix {
return Some(marker_index);
}
// The next valid marker cannot include the first character of the current match
search_start = marker_index + 1;
}
}
/// Yields `NormalCode` and `CommandName` in alternating order according to the occurrences of
/// `command_name` in `segment`. Variables are not detected here, see `highlight_code`
/// instead.
fn highlight_code_segment<'a, E>(
command_name: &'a str,
mut segment: &'a str,
process_snippet: &mut impl FnMut(PageSnippet<'a>) -> Result<(), E>,
process_snippet: &mut impl FnMut(PageSnippet<&'a str>) -> Result<(), E>,
) -> Result<(), E> {
if !command_name.is_empty() {
let mut search_start = 0;
@ -113,26 +224,23 @@ fn highlight_code_segment<'a, E>(
}
/// Checks whether the characters right before and after the substring (given by half-open index interval) are whitespace (if they exist).
fn is_freestanding_substring(surrouding: &str, substring: (usize, usize)) -> bool {
fn is_freestanding_substring(surrounding: &str, substring: (usize, usize)) -> bool {
let (start, end) = substring;
// "okay" meaning <exists and is whitespace> or <doesn't exist>
let char_before_is_okay = surrouding[..start]
let char_before_is_okay = surrounding[..start]
.chars()
.last()
.filter(|prev_char| !prev_char.is_whitespace())
.is_none();
let char_after_is_okay = surrouding[end..]
.is_none_or(char::is_whitespace);
let char_after_is_okay = surrounding[end..]
.chars()
.next()
.filter(|next_char| !next_char.is_whitespace())
.is_none();
.is_none_or(char::is_whitespace);
char_before_is_okay && char_after_is_okay
}
#[cfg(test)]
mod tests {
use super::*;
use PageSnippet::*;
#[test]
fn test_is_freestanding_substring() {
@ -159,80 +267,193 @@ mod tests {
));
}
fn run<'a>(cmd: &'a str, segment: &'a str) -> Vec<PageSnippet<'a>> {
fn run<'a>(cmd: &'a str, segment: &'a str) -> Vec<PageSnippet<String>> {
let mut yielded = Vec::new();
let mut process_snippet = |snip: PageSnippet<'a>| {
let mut process_snippet = |snip: PageSnippet<&str>| {
if !snip.is_empty() {
yielded.push(snip);
yielded.push(snip.map(str::to_string));
}
Ok::<(), ()>(())
};
highlight_code_segment(cmd, segment, &mut process_snippet)
.expect("highlight code segment failed");
highlight_code(cmd, segment, &mut process_snippet).expect("highlight code segment failed");
yielded
}
#[test]
fn test_highlight_code_segment() {
assert!(run("make", "").is_empty());
assert_eq!(
&run("make", "make all CC=clang -q"),
&[CommandName("make"), NormalCode(" all CC=clang -q")]
);
assert_eq!(
&run("make", " make money --always-make"),
&[
NormalCode(" "),
CommandName("make"),
NormalCode(" money --always-make")
]
);
assert_eq!(
&run("git commit", "git commit -m 'git commit'"),
&[CommandName("git commit"), NormalCode(" -m 'git commit'"),]
);
mod highlight_code_segment {
use super::*;
use PageSnippet::*;
#[test]
fn test_highlight_code_segment() {
assert!(run("make", "").is_empty());
assert_eq!(
&run("make", "make all CC=clang -q"),
&[CommandName("make"), NormalCode(" all CC=clang -q")]
);
assert_eq!(
&run("make", " make money --always-make"),
&[
NormalCode(" "),
CommandName("make"),
NormalCode(" money --always-make")
]
);
assert_eq!(
&run("git commit", "git commit -m 'git commit'"),
&[CommandName("git commit"), NormalCode(" -m 'git commit'"),]
);
}
#[test]
fn test_i18n() {
assert_eq!(
&run("mäke", "mäke höhlenrätselbücher"),
&[CommandName("mäke"), NormalCode(" höhlenrätselbücher")]
);
assert_eq!(
&run(
"Müll",
"1000 Gründe warum Müll heute größer ist als Müll früher, ärgerlich"
),
&[
NormalCode("1000 Gründe warum "),
CommandName("Müll"),
NormalCode(" heute größer ist als "),
CommandName("Müll"),
NormalCode(" früher, ärgerlich")
]
);
assert_eq!(
&run(
"übergang",
"die Zustandsübergangsfunktion übergang Änderungen",
),
&[
NormalCode("die Zustandsübergangsfunktion "),
CommandName("übergang"),
NormalCode(" Änderungen")
],
);
}
#[test]
fn test_empty_command() {
let segment = "some code";
let snippets = [NormalCode(segment)];
assert_eq!(run("", segment), snippets);
assert_eq!(run(" ", segment), snippets);
assert_eq!(run(" \t ", segment), snippets);
}
}
#[test]
fn test_i18n() {
assert_eq!(
&run("mäke", "mäke höhlenrätselbücher"),
&[CommandName("mäke"), NormalCode(" höhlenrätselbücher")]
);
assert_eq!(
&run(
"Müll",
"1000 Gründe warum Müll heute größer ist als Müll früher, ärgerlich"
),
&[
NormalCode("1000 Gründe warum "),
CommandName("Müll"),
NormalCode(" heute größer ist als "),
CommandName("Müll"),
NormalCode(" früher, ärgerlich")
]
);
assert_eq!(
&run(
"übergang",
"die Zustandsübergangsfunktion übergang Änderungen",
),
&[
NormalCode("die Zustandsübergangsfunktion "),
CommandName("übergang"),
NormalCode(" Änderungen")
],
);
}
mod placeholders {
use super::*;
use PageSnippet::*;
#[test]
fn test_empty_command() {
let segment = "some code";
let snippets = [NormalCode(segment)];
#[test]
fn variable_vs_escaped() {
assert_eq!(
run("ping", "ping {{example.com}}"),
[
CommandName("ping"),
NormalCode(" "),
Variable("example.com"),
],
);
assert_eq!(
run(
"docker inspect",
r"docker inspect --format '\{\{range.NetworkSettings.Networks\}\}\{\{.IPAddress\}\}\{\{end\}\}' {{container}}"
),
[
CommandName("docker inspect"),
NormalCode(
" --format '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "
),
Variable("container"),
],
);
assert_eq!(
run("mount", r"mount \\{{computer_name}}\{{share_name}} Z:"),
[
CommandName("mount"),
NormalCode(r" \\"),
Variable("computer_name"),
NormalCode(r"\"),
Variable("share_name"),
NormalCode(" Z:"),
],
);
assert_eq!(run("", segment), snippets);
assert_eq!(run(" ", segment), snippets);
assert_eq!(run(" \t ", segment), snippets);
assert_eq!(run("", r"\{"), [NormalCode(r"\{")]);
assert_eq!(run("", r"\{{a"), [NormalCode(r"\{{a")]);
assert_eq!(run("", r"\{{a}}"), [NormalCode(r"\"), Variable("a")]);
// Placeholder has begin marker, but no end marker
assert_eq!(run("", r"{{\}\}}"), [NormalCode("{{}}}")]);
}
#[test]
fn outer_precedence() {
assert_eq!(
run("git stash", "git stash show --patch {{stash@{0}}}"),
[
CommandName("git stash"),
NormalCode(" show --patch "),
Variable("stash@{0}"),
],
);
// The following is not listed in the specification, but this is the highlighting I would expect.
assert_eq!(
run("rg", "rg {{}}}"),
[CommandName("rg"), NormalCode(" "), Variable("}")]
);
// And these are just to document the current behavior
assert_eq!(run("", "{{{}}}"), [Variable("{}")]);
assert_eq!(run("", "{{{{}}}"), [Variable("{{}")]);
assert_eq!(run("", "{{{}}}}"), [Variable("{}}")]);
}
#[test]
fn escaped_inside_placeholder() {
assert_eq!(
run(
"playerctl",
r#"playerctl metadata {{[-f|--format]}} "{{Now playing: \{\{artist\}\} - \{\{album\}\} - \{\{title\}\}}}""#
),
[
CommandName("playerctl"),
NormalCode(" metadata "),
Variable("[-f|--format]"),
NormalCode(" \""),
Variable("Now playing: {{artist}} - {{album}} - {{title}}"),
NormalCode("\""),
],
);
}
#[test]
fn placeholder_inside_escaped() {
assert_eq!(
run("test", r"test \{\{{{var}} normal\}\}"),
[
CommandName("test"),
NormalCode(" {{"),
Variable("var"),
NormalCode(" normal}}"),
],
);
}
#[test]
/// Regression test for <https://github.com/tealdeer-rs/tealdeer/issues/473>
fn prefix_check_character_boundary() {
assert_eq!("Ä".len(), 2);
assert_eq!(run("", r"Äxx{{x}}"), [NormalCode("Äxx"), Variable("x")],);
}
}
}

View file

@ -1,6 +1,6 @@
//! Code to split a `BufRead` instance into an iterator of `LineType`s.
use std::io::BufRead;
use std::io::{BufRead, Read};
use log::warn;
@ -12,7 +12,7 @@ pub enum TldrFormat {
Undecided,
/// The original format
V1,
/// The new format (see https://github.com/tldr-pages/tldr/pull/958)
/// The new format (see <https://github.com/tldr-pages/tldr/pull/958>)
V2,
}
@ -53,7 +53,7 @@ impl<R: BufRead> Iterator for LineIterator<R> {
match bytes_read {
Ok(0) => None,
Err(e) => {
warn!("Could not read line from reader: {:?}", e);
warn!("Could not read line from reader: {e:?}");
None
}
Ok(_) => {
@ -64,10 +64,11 @@ impl<R: BufRead> Iterator for LineIterator<R> {
self.format = TldrFormat::V1;
} else {
// It's the new format! Drop next line.
// (Hmm, is there a way to do this without an allocation?)
let mut devnull = String::new();
if let Err(e) = self.reader.read_line(&mut devnull) {
warn!("Could not read line from reader: {:?}", e);
if let Err(e) = Read::bytes(&mut self.reader)
.find(|b| matches!(b, Ok(b'\n') | Err(_)))
.transpose()
{
warn!("Could not read line from reader: {e:?}");
return None;
}
self.first_line = false;
@ -95,21 +96,27 @@ mod test {
#[test]
fn test_first_line_old_format() {
let input = "# The Title\n\n";
let input = "# The Title\n> Description\n";
let mut lines = LineIterator::new(input.as_bytes());
let title = lines.next().unwrap();
assert_eq!(title, LineType::Title("The Title".to_string()));
let empty = lines.next().unwrap();
assert_eq!(empty, LineType::Empty);
let description = lines.next().unwrap();
assert_eq!(
description,
LineType::Description("Description".to_string())
);
}
#[test]
fn test_first_line_new_format() {
let input = "The Title\n=========\n\n";
let input = "The Title\n=========\n> Description\n";
let mut lines = LineIterator::new(input.as_bytes());
let title = lines.next().unwrap();
assert_eq!(title, LineType::Title("The Title".to_string()));
let empty = lines.next().unwrap();
assert_eq!(empty, LineType::Empty);
let description = lines.next().unwrap();
assert_eq!(
description,
LineType::Description("Description".to_string())
);
}
}

View file

@ -15,18 +15,36 @@
#![allow(clippy::similar_names)]
#![allow(clippy::struct_excessive_bools)]
#![allow(clippy::too_many_lines)]
#![allow(clippy::unnecessary_debug_formatting)]
#![allow(clippy::while_let_loop)]
use std::{env, path::PathBuf, process};
#[cfg(not(any(
feature = "native-tls",
feature = "rustls-with-webpki-roots",
feature = "rustls-with-native-roots",
)))]
compile_error!(
"at least one of the features \"native-tls\", \"rustls-with-webpki-roots\" or \"rustls-with-native-roots\" must be enabled"
);
use app_dirs::AppInfo;
use atty::Stream;
use clap::{AppSettings, ArgGroup, Parser};
#[cfg(not(target_os = "windows"))]
use pager::Pager;
use std::{
env,
fs::create_dir_all,
io::{self, IsTerminal},
path::Path,
process::{Command, ExitCode},
};
use anyhow::{anyhow, Context, Result};
use cache::{CacheConfig, TLDR_OLD_PAGES_DIR};
use clap::Parser;
use config::{ConfigLoader, Language, StyleConfig, TlsBackend};
use log::debug;
use types::PlatformType;
mod cache;
mod cli;
mod config;
mod error;
pub mod extensions;
mod formatter;
mod line_iterator;
@ -35,299 +53,92 @@ mod types;
mod utils;
use crate::{
cache::{Cache, CacheFreshness, PageLookupResult, TLDR_PAGES_DIR},
config::{get_config_dir, get_config_path, make_default_config, Config},
error::TealdeerError::ConfigError,
extensions::Dedup,
cache::{Cache, PageLookupResult, TLDR_PAGES_DIR},
cli::Cli,
config::{
get_config_dir, make_default_config, supported_tls_backends_string, Config, PathWithSource,
},
output::print_page,
types::{ColorOptions, PlatformType},
types::ColorOptions,
utils::{print_error, print_warning},
};
const NAME: &str = "tealdeer";
const APP_INFO: AppInfo = AppInfo {
name: NAME,
author: NAME,
};
const ARCHIVE_URL: &str = "https://tldr.sh/assets/tldr.zip";
// Note: flag names are specified explicitly in clap attributes
// to improve readability and allow contributors to grep names like "clear-cache"
#[derive(Parser, Debug)]
#[clap(about = "A fast TLDR client", author, version)]
#[clap(setting = AppSettings::ArgRequiredElseHelp)]
#[clap(setting = AppSettings::DeriveDisplayOrder)]
#[clap(setting = AppSettings::DisableColoredHelp)]
#[clap(
after_help = "To view the user documentation, please visit https://dbrgn.github.io/tealdeer/."
)]
#[clap(group = ArgGroup::new("command_or_file").args(&["command", "render"]))]
struct Args {
/// The command to show (e.g. `tar` or `git log`)
#[clap(min_values = 1)]
command: Vec<String>,
/// List all commands in the cache
#[clap(short = 'l', long = "list")]
list: bool,
/// Render a specific markdown file
#[clap(
short = 'f',
long = "render",
value_name = "FILE",
conflicts_with = "command"
)]
render: Option<PathBuf>,
/// Override the operating system
#[clap(
short = 'p',
long = "platform",
possible_values = ["linux", "macos", "windows", "sunos", "osx"],
)]
platform: Option<PlatformType>,
/// Deprecated alias of `platform`
#[clap(
short = 'o',
long = "os",
possible_values = ["linux", "macos", "windows", "sunos", "osx"],
hide = true
)]
os: Option<PlatformType>,
/// Override the language
#[clap(short = 'L', long = "language")]
language: Option<String>,
/// Update the local cache
#[clap(short = 'u', long = "update")]
update: bool,
/// Clear the local cache
#[clap(short = 'c', long = "clear-cache")]
clear_cache: bool,
/// Use a pager to page output
#[clap(long = "pager", requires = "command_or_file")]
pager: bool,
/// Display the raw markdown instead of rendering it
#[clap(short = 'r', long = "--raw", requires = "command_or_file")]
raw: bool,
/// Deprecated alias of `raw`
#[clap(
long = "markdown",
short = 'm',
requires = "command_or_file",
hide = true
)]
markdown: bool,
/// Suppress informational messages
#[clap(short = 'q', long = "quiet")]
quiet: bool,
/// Show file and directory paths used by tealdeer
#[clap(long = "show-paths")]
show_paths: bool,
/// Show config file path
#[clap(long = "config-path")]
config_path: bool,
/// Create a basic config
#[clap(long = "seed-config")]
seed_config: bool,
/// Control whether to use color
#[clap(
long = "color",
value_name = "WHEN",
possible_values = ["always", "auto", "never"]
)]
color: Option<ColorOptions>,
/// Print the version
// Note: We override the version flag because clap uses `-V` by default,
// while TLDR specification requires `-v` to be used.
#[clap(short = 'v', long = "version")]
version: bool,
}
/// Set up display pager
#[cfg(not(target_os = "windows"))]
fn configure_pager(_: bool) {
Pager::with_default_pager("less -R").setup();
}
#[cfg(target_os = "windows")]
fn configure_pager(enable_styles: bool) {
print_warning(enable_styles, "--pager flag not available on Windows!");
}
/// The cache should get updated if this was requested by the user, or if auto
/// updates are enabled and the cache age is longer than the auto update interval.
fn should_update_cache(args: &Args, config: &Config) -> bool {
args.update
|| (config.updates.auto_update
&& Cache::last_update().map_or(true, |ago| ago >= config.updates.auto_update_interval))
}
#[derive(PartialEq)]
enum CheckCacheResult {
CacheFound,
CacheMissing,
}
/// Check the cache for freshness. If it's stale or missing, show a warning.
fn check_cache(args: &Args, enable_styles: bool) -> CheckCacheResult {
match Cache::freshness() {
CacheFreshness::Fresh => CheckCacheResult::CacheFound,
CacheFreshness::Stale(_) if args.quiet => CheckCacheResult::CacheFound,
CacheFreshness::Stale(age) => {
print_warning(
enable_styles,
&format!(
"The cache hasn't been updated for {} days.\n\
You should probably run `tldr --update` soon.",
age.as_secs() / 24 / 3600
),
);
CheckCacheResult::CacheFound
}
CacheFreshness::Missing => {
print_warning(
enable_styles,
"Cache not found. Please run `tldr --update`.",
);
CheckCacheResult::CacheMissing
}
}
}
static TEALDEER_PAGE: &str =
include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/pages/tealdeer.md"));
/// Clear the cache
fn clear_cache(quietly: bool, enable_styles: bool) {
Cache::clear().unwrap_or_else(|e| {
print_error(
enable_styles,
&format!("Could not delete cache: {}", e.message()),
);
process::exit(1);
});
fn clear_cache(cache: Cache, quietly: bool) -> Result<()> {
let cache_dir = cache.config().pages_directory.display();
cache.clear().context("Could not clear cache")?;
if !quietly {
eprintln!("Successfully deleted cache.");
eprintln!("Successfully cleared cache at `{cache_dir}`.");
}
Ok(())
}
/// Update the cache
fn update_cache(cache: &Cache, quietly: bool, enable_styles: bool) {
cache.update().unwrap_or_else(|e| {
print_error(
enable_styles,
&format!("Could not update cache: {}", e.message()),
);
process::exit(1);
});
fn update_cache(
cache: &mut Cache,
archive_source: &str,
tls_backend: TlsBackend,
quietly: bool,
) -> Result<()> {
let downloaded_languages = cache
.update(archive_source, tls_backend)
.context("Could not update cache")?;
if !quietly {
eprintln!("Successfully updated cache.");
}
}
/// Show the config path (DEPRECATED)
fn show_config_path(enable_styles: bool) {
match get_config_path() {
Ok((config_file_path, _)) => {
println!("Config path is: {}", config_file_path.to_str().unwrap());
}
Err(ConfigError(msg)) => {
print_error(
enable_styles,
&format!("Could not look up config_path: {}", msg),
);
process::exit(1);
}
Err(_) => {
print_error(enable_styles, "Unknown error");
process::exit(1);
eprint!("Pages for the following languages were downloaded: ");
let language_strings: Vec<_> = downloaded_languages
.into_iter()
.map(|lang| lang.0)
.collect();
if language_strings.is_empty() {
eprintln!("(none)");
} else {
eprintln!("{}", language_strings.join(", "));
}
}
Ok(())
}
/// Show file paths
fn show_paths(config: &Config) {
let config_dir = get_config_dir().map_or_else(
|e| format!("[Error: {}]", e),
|(mut path, source)| {
path.push(""); // Trailing path separator
match path.to_str() {
Some(path) => format!("{} ({})", path, source),
None => "[Invalid]".to_string(),
}
},
);
let config_path = get_config_path().map_or_else(
|e| format!("[Error: {}]", e),
|(path, _)| path.to_str().unwrap_or("[Invalid]").to_string(),
);
let cache_dir = Cache::get_cache_dir().map_or_else(
|e| format!("[Error: {}]", e),
|(mut path, source)| {
path.push(""); // Trailing path separator
match path.to_str() {
Some(path) => format!("{} ({})", path, source),
None => "[Invalid]".to_string(),
}
},
);
let pages_dir = Cache::get_cache_dir().map_or_else(
|e| format!("[Error: {}]", e),
|(mut path, _)| {
path.push(TLDR_PAGES_DIR);
path.push(""); // Trailing path separator
path.into_os_string()
.into_string()
.unwrap_or_else(|_| "[Invalid]".to_string())
},
);
let custom_pages_dir = config.directories.custom_pages_dir.as_deref().map_or_else(
|| "[None]".to_string(),
|path| {
path.to_str()
.map_or_else(|| "[Invalid]".to_string(), ToString::to_string)
},
);
println!("Config dir: {}", config_dir);
println!("Config path: {}", config_path);
println!("Cache dir: {}", cache_dir);
println!("Pages dir: {}", pages_dir);
println!("Custom pages dir: {}", custom_pages_dir);
let config_dir = {
let (mut path, source) = get_config_dir();
path.push(""); // Trailing path separator
match path.to_str() {
Some(path) => format!("{path} ({source})"),
None => "[Invalid]".to_string(),
}
};
let config_path = config.file_path.to_string();
let cache_dir = config.directories.cache_dir.to_string();
let pages_dir = {
let mut path = config.directories.cache_dir.path.clone();
path.push(TLDR_PAGES_DIR);
path.push(""); // Trailing path separator
path.display().to_string()
};
let custom_pages_dir = match config.directories.custom_pages_dir {
Some(ref path_with_source) => path_with_source.to_string(),
None => "[None]".to_string(),
};
println!("Config dir: {config_dir}");
println!("Config path: {config_path}");
println!("Cache dir: {cache_dir}");
println!("Pages dir: {pages_dir}");
println!("Custom pages dir: {custom_pages_dir}");
}
/// Create seed config file and exit
fn create_config_and_exit(enable_styles: bool) {
match make_default_config() {
Ok(config_file_path) => {
eprintln!(
"Successfully created seed config file here: {}",
config_file_path.to_str().unwrap()
);
process::exit(0);
}
Err(ConfigError(msg)) => {
print_error(
enable_styles,
&format!("Could not create seed config: {}", msg),
);
process::exit(1);
}
Err(_) => {
print_error(enable_styles, "Unknown error");
process::exit(1);
}
}
fn create_config(path: Option<&Path>) -> Result<()> {
let config_file_path = make_default_config(path).context("Could not create seed config")?;
eprintln!(
"Successfully created seed config file here: {}",
config_file_path.to_str().unwrap()
);
Ok(())
}
#[cfg(feature = "logging")]
@ -338,109 +149,96 @@ fn init_log() {
#[cfg(not(feature = "logging"))]
fn init_log() {}
fn get_languages(env_lang: Option<&str>, env_language: Option<&str>) -> Vec<String> {
// Language list according to
// https://github.com/tldr-pages/tldr/blob/main/CLIENT-SPECIFICATION.md#language
fn spawn_editor(custom_pages_dir: &Path, file_name: &str) -> Result<()> {
create_dir_all(custom_pages_dir).context("Failed to create custom pages directory")?;
if env_lang.is_none() {
return vec!["en".to_string()];
let custom_page_path = custom_pages_dir.join(file_name);
let Some(custom_page_path) = custom_page_path.to_str() else {
return Err(anyhow!("`custom_page_path.to_str()` failed"));
};
let Ok(editor) = env::var("EDITOR") else {
return Err(anyhow!(
"To edit a custom page, please set the `EDITOR` environment variable."
));
};
println!("Editing {custom_page_path:?}");
let status = Command::new(&editor).arg(custom_page_path).status()?;
if !status.success() {
return Err(anyhow!("{editor} exit with code {:?}", status.code()));
}
let env_lang = env_lang.unwrap();
// Create an iterator that contains $LANGUAGE (':' separated list) followed by $LANG (single language)
let locales = env_language.unwrap_or("").split(':').chain([env_lang]);
let mut lang_list = Vec::new();
for locale in locales {
// Language plus country code (e.g. `en_US`)
if locale.len() >= 5 && locale.chars().nth(2) == Some('_') {
lang_list.push(&locale[..5]);
}
// Language code only (e.g. `en`)
if locale.len() >= 2 && locale != "POSIX" {
lang_list.push(&locale[..2]);
}
}
lang_list.push("en");
lang_list.clear_duplicates();
lang_list.into_iter().map(str::to_string).collect()
Ok(())
}
fn get_languages_from_env() -> Vec<String> {
get_languages(
std::env::var("LANG").ok().as_deref(),
std::env::var("LANGUAGE").ok().as_deref(),
)
}
fn main() {
fn main() -> ExitCode {
// Initialize logger
init_log();
// Parse arguments
let mut args = Args::parse();
let args = Cli::parse();
// Determine the usage of styles
#[cfg(target_os = "windows")]
let ansi_support = ansi_term::enable_ansi_support().is_ok();
#[cfg(not(target_os = "windows"))]
let ansi_support = true;
let enable_styles = match args.color.unwrap_or_default() {
// Attempt to use styling if instructed
ColorOptions::Always => true,
ColorOptions::Always => {
yansi::enable(); // disable yansi's automatic detection for ANSI support on Windows
true
}
// Enable styling if:
// * There is `ansi_support`
// * NO_COLOR env var isn't set: https://no-color.org/
// * The output stream is stdout (not being piped)
ColorOptions::Auto => {
ansi_support && env::var_os("NO_COLOR").is_none() && atty::is(Stream::Stdout)
}
ColorOptions::Auto => env::var_os("NO_COLOR").is_none() && io::stdout().is_terminal(),
// Disable styling
ColorOptions::Never => false,
};
// Handle renamed arguments
if args.markdown {
args.raw = true;
print_warning(
enable_styles,
"The -m / --markdown flag is deprecated, use -r / --raw instead",
);
}
if args.os.is_some() {
print_warning(
enable_styles,
"The -o / --os flag is deprecated, use -p / --platform instead",
);
}
args.platform = args.platform.or(args.os);
// Show config file and path, pass through
if args.config_path {
print_warning(
enable_styles,
"The --config-path flag is deprecated, use --show-paths instead",
);
show_config_path(enable_styles);
}
try_main(args, enable_styles).unwrap_or_else(|error| {
print_error(enable_styles, &error);
ExitCode::FAILURE
})
}
fn try_main(args: Cli, enable_styles: bool) -> Result<ExitCode> {
// Look up config file, if none is found fall back to default config.
let config = match Config::load(enable_styles) {
Ok(config) => config,
Err(ConfigError(msg)) => {
print_error(enable_styles, &format!("Could not load config: {}", msg));
process::exit(1);
debug!("Loading config");
let config_loader = match &args.config_path {
Some(path) if !args.seed_config => {
ConfigLoader::read(path.clone()).context("Could not read config from given path")?
}
Err(e) => {
print_error(enable_styles, &format!("Could not load config: {}", e));
process::exit(1);
_ => {
ConfigLoader::read_default_path().context("Could not read config from default path")?
}
};
let mut config = config_loader.load()?;
// Set up pager
if args.pager || config.display.use_pager {
configure_pager(enable_styles);
// Override styles if needed
if !enable_styles {
config.style = StyleConfig::default();
}
let custom_pages_dir = config
.directories
.custom_pages_dir
.as_ref()
.map(PathWithSource::path);
// Note: According to the TLDR client spec, page names must be transparently
// lowercased before lookup:
// https://github.com/tldr-pages/tldr/blob/main/CLIENT-SPECIFICATION.md#page-names
let command = args.command.join("-").to_lowercase();
if args.edit_patch || args.edit_page {
let file_name = if args.edit_patch {
format!("{command}.patch.md")
} else {
format!("{command}.page.md")
};
custom_pages_dir
.context("To edit custom pages/patches, please specify a custom pages directory.")
.and_then(|custom_pages_dir| spawn_editor(custom_pages_dir, &file_name))?;
return Ok(ExitCode::SUCCESS);
}
// Show various paths
@ -450,148 +248,197 @@ fn main() {
// Create a basic config and exit
if args.seed_config {
create_config_and_exit(enable_styles);
create_config(args.config_path.as_deref())?;
return Ok(ExitCode::SUCCESS);
}
// Specify target OS
let platform: PlatformType = args.platform.unwrap_or_else(PlatformType::current);
// If a local file was passed in, render it and exit
if let Some(file) = args.render {
let path = PageLookupResult::with_page(file);
if let Err(msg) = print_page(&path, args.raw, &config) {
print_error(enable_styles, &msg);
process::exit(1);
} else {
process::exit(0);
};
let reader = PageLookupResult::with_page(file).reader()?;
print_page(reader, args.raw, enable_styles, args.pager, &config)?;
return Ok(ExitCode::SUCCESS);
}
// Initialize cache
let cache = Cache::new(ARCHIVE_URL, platform);
// Clear cache, pass through
if args.clear_cache {
clear_cache(args.quiet, enable_styles);
// The tealdeer page is embedded in the binary, no cache needed
if command == "tealdeer" {
print_page(
TEALDEER_PAGE.as_bytes(),
args.raw,
enable_styles,
args.pager,
&config,
)?;
return Ok(ExitCode::SUCCESS);
}
// Cache update, pass through
let cache_updated = if should_update_cache(&args, &config) {
update_cache(&cache, args.quiet, enable_styles);
true
} else {
false
if let Some(platforms) = args.platforms {
config.search.platforms = platforms;
if !config.search.platforms.contains(&PlatformType::Common) {
config.search.platforms.push(PlatformType::Common);
}
}
let (search_languages, download_languages): (&[_], &[_]) = match args.language.as_deref() {
Some(lang) => (&[Language(lang)], &[Language(lang)]),
None => (&config.search.languages, &config.updates.download_languages),
};
// Check cache presence and freshness
if !cache_updated
&& (args.list || !args.command.is_empty())
&& check_cache(&args, enable_styles) == CheckCacheResult::CacheMissing
{
process::exit(1);
let cache_config = CacheConfig {
pages_directory: &config.directories.cache_dir.path().join(TLDR_PAGES_DIR),
custom_pages_directory: config
.directories
.custom_pages_dir
.as_ref()
.map(PathWithSource::path),
platforms: &config.search.platforms,
search_languages,
download_languages,
};
// TODO: remove in tealdeer 1.9
let old_config = CacheConfig {
pages_directory: &config.directories.cache_dir.path().join(TLDR_OLD_PAGES_DIR),
..cache_config
};
if let Ok(Some(old_cache)) = Cache::open(old_config) {
old_cache.clear()?;
eprintln!("Cleared pages from old cache location.");
}
// List cached commands and exit
if args.list {
// Get list of pages
let pages = cache.list_pages().unwrap_or_else(|e| {
if args.clear_cache {
if let Some(cache) = Cache::open(cache_config)? {
clear_cache(cache, args.quiet)?;
}
return Ok(ExitCode::SUCCESS);
}
let cache = if args.update || config.updates.auto_update && !args.no_auto_update {
let (mut cache, was_created) = Cache::open_or_create(cache_config)?;
if was_created || args.update || cache.age()? >= config.updates.auto_update_interval {
let result = update_cache(
&mut cache,
config.updates.archive_source,
config.updates.tls_backend,
args.quiet,
);
if let Err(e) = result {
print_error(enable_styles, &e);
eprintln!();
eprintln!("Note: Update errors are often caused by unexpected or missing TLS certificates.");
eprintln!(
"You are currently using the following TLS backend: {}",
config.updates.tls_backend,
);
eprintln!(
"Try changing the updates.tls_backend setting in the config file, for example:"
);
eprintln!();
eprintln!(" [updates]");
eprintln!(" tls_backend = \"rustls-with-native-roots\"");
eprintln!();
eprintln!(
"This build of tealdeer has support for the following options: {}",
supported_tls_backends_string(),
);
return Ok(ExitCode::FAILURE);
}
}
cache
} else if args.list || !command.is_empty() {
// Cache is needed for these commands to work
let Some(cache) = Cache::open(cache_config)? else {
print_error(
enable_styles,
&format!("Could not get list of pages: {}", e.message()),
&anyhow::anyhow!(
"Page cache not found. Please run `tldr --update` to download the cache."
),
);
process::exit(1);
});
println!("\nNote: You can optionally enable automatic cache updates by adding the");
println!("following config to your config file:\n");
println!(" [updates]");
println!(" auto_update = true\n");
println!("The path to your config file can be looked up with `tldr --show-paths`.");
println!("To create an initial config file, use `tldr --seed-config`.\n");
println!("You can find more tips and tricks in our docs:\n");
println!(" https://tealdeer-rs.github.io/tealdeer/config_updates.html");
// Print pages
println!("{}", pages.join("\n"));
process::exit(0);
return Ok(ExitCode::FAILURE);
};
if let Some(max_cache_age) = config.updates.warn_cache_age {
let age = cache.age()?;
if age > max_cache_age && !args.quiet {
print_warning(
enable_styles,
&format!(
"The cache hasn't been updated for {} days.\n\
You should probably run `tldr --update` soon.",
age.as_secs() / 24 / 3600
),
);
}
}
cache
} else {
// There is nothing left to do
return Ok(ExitCode::SUCCESS);
};
if args.list {
for page in cache.list_pages()? {
println!("{page}");
}
return Ok(ExitCode::SUCCESS);
}
// Show command from cache
if !args.command.is_empty() {
// Note: According to the TLDR client spec, page names must be transparently
// lowercased before lookup:
// https://github.com/tldr-pages/tldr/blob/main/CLIENT-SPECIFICATION.md#page-names
let command = args.command.join("-").to_lowercase();
if !command.is_empty() {
// TODO: Remove this check 1 year after version 1.7.0 was released
if cache.old_custom_pages_exist()? {
print_warning(
enable_styles,
&format!(
"Custom pages using the old naming convention were found in {}.\n\
Please rename them to follow the new convention:\n\
- `<name>.page` `<name>.page.md`\n\
- `<name>.patch` `<name>.patch.md`",
cache
.config()
.custom_pages_directory
.expect("Old custom pages can only exist in custom pages directory")
.display(),
),
);
}
// Collect languages
let languages = args
.language
.map_or_else(get_languages_from_env, |lang| vec![lang]);
// Search for command in cache
if let Some(lookup_result) = cache.find_page(
&command,
&languages,
config.directories.custom_pages_dir.as_deref(),
) {
if let Err(msg) = print_page(&lookup_result, args.raw, &config) {
print_error(enable_styles, &msg);
process::exit(1);
}
process::exit(0);
} else {
let Some(result) = cache.find_page(&command) else {
if !args.quiet {
print_warning(
enable_styles,
&format!(
"Page `{}` not found in cache.\n\
"Page `{command}` not found in cache.\n\
Try updating with `tldr --update`, or submit a pull request to:\n\
https://github.com/tldr-pages/tldr",
&command
https://github.com/tldr-pages/tldr"
),
);
}
process::exit(1);
}
}
}
#[cfg(test)]
mod test {
use crate::get_languages;
mod language {
use super::*;
#[test]
fn missing_lang_env() {
let lang_list = get_languages(None, Some("de:fr"));
assert_eq!(lang_list, ["en"]);
let lang_list = get_languages(None, None);
assert_eq!(lang_list, ["en"]);
}
#[test]
fn missing_language_env() {
let lang_list = get_languages(Some("de"), None);
assert_eq!(lang_list, ["de", "en"]);
}
#[test]
fn preference_order() {
let lang_list = get_languages(Some("de"), Some("fr:cn"));
assert_eq!(lang_list, ["fr", "cn", "de", "en"]);
}
#[test]
fn country_code_expansion() {
let lang_list = get_languages(Some("pt_BR"), None);
assert_eq!(lang_list, ["pt_BR", "pt", "en"]);
}
#[test]
fn ignore_posix_and_c() {
let lang_list = get_languages(Some("POSIX"), None);
assert_eq!(lang_list, ["en"]);
let lang_list = get_languages(Some("C"), None);
assert_eq!(lang_list, ["en"]);
}
#[test]
fn no_duplicates() {
let lang_list = get_languages(Some("de"), Some("fr:de:cn:de"));
assert_eq!(lang_list, ["fr", "de", "cn", "en"]);
}
return Ok(ExitCode::FAILURE);
};
print_page(
result.reader()?,
args.raw,
enable_styles,
args.pager,
&config,
)?;
}
Ok(ExitCode::SUCCESS)
}

View file

@ -1,23 +1,46 @@
//! Functions for printing pages to the terminal
use std::io::{self, BufRead, Write};
use std::io::{self, BufRead, BufReader, Read, Write};
use anyhow::{Context, Result};
use yansi::Paint;
use crate::{
cache::PageLookupResult,
config::{Config, StyleConfig},
error::TealdeerError::WriteError,
formatter::{highlight_lines, PageSnippet},
line_iterator::LineIterator,
};
/// Set up display pager
///
/// SAFETY: this function may be called multiple times
#[cfg(not(target_os = "windows"))]
fn configure_pager(_: bool) {
use std::sync::Once;
static INIT: Once = Once::new();
INIT.call_once(|| pager::Pager::with_default_pager("less -R").setup());
}
#[cfg(target_os = "windows")]
fn configure_pager(enable_styles: bool) {
use crate::utils::print_warning;
print_warning(enable_styles, "--pager flag not available on Windows!");
}
/// Print page by path
pub fn print_page(
lookup_result: &PageLookupResult,
reader: impl Read,
enable_markdown: bool,
enable_styles: bool,
use_pager: bool,
config: &Config,
) -> Result<(), String> {
// Create reader from file(s)
let reader = lookup_result.reader()?;
) -> Result<()> {
let reader = BufReader::new(reader);
// Configure pager if applicable
if use_pager || config.display.use_pager {
configure_pager(enable_styles);
}
// Lock stdout only once, this improves performance considerably
let stdout = io::stdout();
@ -26,17 +49,16 @@ pub fn print_page(
if enable_markdown {
// Print the raw markdown of the file.
for line in reader.lines() {
writeln!(handle, "{}", line.unwrap())
.map_err(|_| "Could not write to stdout".to_string())?;
let line = line.context("Error while reading from a page")?;
writeln!(handle, "{line}").context("Could not write to stdout")?;
}
} else {
// Closure that processes a page snippet and writes it to stdout
let mut process_snippet = |snip: PageSnippet<'_>| {
let mut process_snippet = |snip: PageSnippet<&str>| {
if snip.is_empty() {
Ok(())
} else {
print_snippet(&mut handle, snip, &config.style)
.map_err(|e| WriteError(e.to_string()))
print_snippet(&mut handle, snip, &config.style).context("Failed to print snippet")
}
};
@ -45,31 +67,31 @@ pub fn print_page(
LineIterator::new(reader),
&mut process_snippet,
!config.display.compact,
config.display.show_title,
config.display.indent,
)
.map_err(|e| format!("Could not write to stdout: {}", e.message()))?;
};
.context("Could not write to stdout")?;
}
// We're done outputting data, flush stdout now!
handle
.flush()
.map_err(|_| "Could not flush stdout".to_string())?;
handle.flush().context("Could not flush stdout")?;
Ok(())
}
fn print_snippet(
writer: &mut impl Write,
snip: PageSnippet<'_>,
snip: PageSnippet<&str>,
style: &StyleConfig,
) -> Result<(), io::Error> {
) -> io::Result<()> {
use PageSnippet::*;
match snip {
CommandName(s) => write!(writer, "{}", style.command_name.paint(s)),
Variable(s) => write!(writer, "{}", style.example_variable.paint(s)),
NormalCode(s) => write!(writer, "{}", style.example_code.paint(s)),
Description(s) => writeln!(writer, " {}", style.description.paint(s)),
Text(s) => writeln!(writer, " {}", style.example_text.paint(s)),
CommandName(s) | Title(s) => write!(writer, "{}", s.paint(style.command_name)),
Variable(s) => write!(writer, "{}", s.paint(style.example_variable)),
NormalCode(s) => write!(writer, "{}", s.paint(style.example_code)),
Description(s) => write!(writer, "{}", s.paint(style.description)),
Text(s) => write!(writer, "{}", s.paint(style.example_text)),
Linebreak => writeln!(writer),
}
}

View file

@ -10,8 +10,13 @@ use serde_derive::{Deserialize, Serialize};
pub enum PlatformType {
Linux,
OsX,
SunOs,
Windows,
SunOs,
Android,
FreeBsd,
NetBsd,
OpenBsd,
Common,
}
impl fmt::Display for PlatformType {
@ -19,25 +24,43 @@ impl fmt::Display for PlatformType {
match self {
Self::Linux => write!(f, "Linux"),
Self::OsX => write!(f, "macOS / BSD"),
Self::SunOs => write!(f, "SunOS"),
Self::Windows => write!(f, "Windows"),
Self::SunOs => write!(f, "SunOS"),
Self::Android => write!(f, "Android"),
Self::FreeBsd => write!(f, "FreeBSD"),
Self::NetBsd => write!(f, "NetBSD"),
Self::OpenBsd => write!(f, "OpenBSD"),
Self::Common => write!(f, "Common"),
}
}
}
impl str::FromStr for PlatformType {
type Err = String;
impl clap::ValueEnum for PlatformType {
fn value_variants<'a>() -> &'a [Self] {
&[
Self::Linux,
Self::OsX,
Self::SunOs,
Self::Windows,
Self::Android,
Self::FreeBsd,
Self::NetBsd,
Self::OpenBsd,
Self::Common,
]
}
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"linux" => Ok(Self::Linux),
"osx" | "macos" => Ok(Self::OsX),
"sunos" => Ok(Self::SunOs),
"windows" => Ok(Self::Windows),
other => Err(format!(
"Unknown OS: {}. Possible values: linux, macos, osx, sunos, windows",
other
)),
fn to_possible_value<'a>(&self) -> Option<clap::builder::PossibleValue> {
match self {
Self::Linux => Some(clap::builder::PossibleValue::new("linux")),
Self::OsX => Some(clap::builder::PossibleValue::new("macos").alias("osx")),
Self::Windows => Some(clap::builder::PossibleValue::new("windows")),
Self::SunOs => Some(clap::builder::PossibleValue::new("sunos")),
Self::Android => Some(clap::builder::PossibleValue::new("android")),
Self::FreeBsd => Some(clap::builder::PossibleValue::new("freebsd")),
Self::NetBsd => Some(clap::builder::PossibleValue::new("netbsd")),
Self::OpenBsd => Some(clap::builder::PossibleValue::new("openbsd")),
Self::Common => Some(clap::builder::PossibleValue::new("common")),
}
}
}
@ -48,13 +71,7 @@ impl PlatformType {
Self::Linux
}
#[cfg(any(
target_os = "macos",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
target_os = "dragonfly"
))]
#[cfg(any(target_os = "macos", target_os = "dragonfly"))]
pub fn current() -> Self {
Self::OsX
}
@ -64,6 +81,26 @@ impl PlatformType {
Self::Windows
}
#[cfg(target_os = "android")]
pub fn current() -> Self {
Self::Android
}
#[cfg(target_os = "freebsd")]
pub fn current() -> Self {
Self::FreeBsd
}
#[cfg(target_os = "netbsd")]
pub fn current() -> Self {
Self::NetBsd
}
#[cfg(target_os = "openbsd")]
pub fn current() -> Self {
Self::OpenBsd
}
#[cfg(not(any(
target_os = "linux",
target_os = "macos",
@ -71,43 +108,24 @@ impl PlatformType {
target_os = "netbsd",
target_os = "openbsd",
target_os = "dragonfly",
target_os = "windows"
target_os = "windows",
target_os = "android",
)))]
pub fn current() -> Self {
Self::Other
}
}
#[derive(Debug, Eq, PartialEq, Copy, Clone, Deserialize)]
#[derive(Debug, Eq, PartialEq, Copy, Clone, Deserialize, clap::ValueEnum)]
#[serde(rename_all = "lowercase")]
#[derive(Default)]
pub enum ColorOptions {
Always,
#[default]
Auto,
Never,
}
impl str::FromStr for ColorOptions {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"always" => Ok(Self::Always),
"auto" => Ok(Self::Auto),
"never" => Ok(Self::Never),
other => Err(format!(
"Unknown color option: {}. Possible values: always, auto, never",
other
)),
}
}
}
impl Default for ColorOptions {
fn default() -> Self {
Self::Auto
}
}
#[derive(Debug, Eq, PartialEq)]
pub enum LineType {
Empty,
@ -175,16 +193,16 @@ impl LineType {
}
/// The reason why a certain path (e.g. config path or cache dir) was chosen.
#[derive(Debug, PartialEq)]
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum PathSource {
/// OS convention (e.g. XDG on Linux)
OsConvention,
/// Env variable (TEALDEER_*)
EnvVar,
#[allow(dead_code)] // Waiting for Pull Request #141
/// Config file variable
ConfigVar,
/// Config file
ConfigFile,
/// CLI argument override
Cli,
}
impl fmt::Display for PathSource {
@ -195,7 +213,8 @@ impl fmt::Display for PathSource {
match self {
Self::OsConvention => "OS convention",
Self::EnvVar => "env variable",
Self::ConfigVar => "config file variable",
Self::ConfigFile => "config file",
Self::Cli => "command line argument",
}
)
}

View file

@ -1,4 +1,4 @@
use ansi_term::{Color, Style};
use yansi::{Color, Paint};
/// Print a warning to stderr. If `enable_styles` is true, then a yellow
/// message will be printed.
@ -6,17 +6,16 @@ pub fn print_warning(enable_styles: bool, message: &str) {
print_msg(enable_styles, message, "Warning: ", Color::Yellow);
}
/// Print an error to stderr. If `enable_styles` is true, then a red message
/// will be printed.
pub fn print_error(enable_styles: bool, message: &str) {
print_msg(enable_styles, message, "Error: ", Color::Red);
/// Print an anyhow error to stderr. If `enable_styles` is true, then a red
/// message will be printed.
pub fn print_error(enable_styles: bool, error: &anyhow::Error) {
print_msg(enable_styles, &format!("{error:?}"), "Error: ", Color::Red);
}
fn print_msg(enable_styles: bool, message: &str, prefix: &'static str, color: Color) {
if enable_styles {
let style = Style::new().fg(color);
eprintln!("{}{}", style.paint(prefix), style.paint(message));
eprintln!("{}{}", prefix.paint(color), message.paint(color));
} else {
eprintln!("{}", message);
eprintln!("{message}");
}
}

View file

@ -0,0 +1,36 @@
# git checkout
> Checkout a branch or paths to the working tree.
> More information: <https://git-scm.com/docs/git-checkout>.
- Create and switch to a new branch:
`git checkout -b {{branch_name}}`
- Create and switch to a new branch based on a specific reference (branch, remote/branch, tag are examples of valid references):
`git checkout -b {{branch_name}} {{reference}}`
- Switch to an existing local branch:
`git checkout {{branch_name}}`
- Switch to the previously checked out branch:
`git checkout -`
- Switch to an existing remote branch:
`git checkout --track {{remote_name}}/{{branch_name}}`
- Discard all unstaged changes in the current directory (see `git reset` for more undo-like commands):
`git checkout .`
- Discard unstaged changes to a given file:
`git checkout {{path/to/file}}`
- Replace a file in the current directory with the version of it committed in a given branch:
`git checkout {{branch_name}} -- {{path/to/file}}`

37
tests/cache/pages.ja/common/apt.md vendored Normal file
View file

@ -0,0 +1,37 @@
# apt
> Debian系ディストリビューションで使われるパッケージ管理システムです。
> Ubuntuのバージョンが16.04か、それ以降で対話モードを使う場合`apt-get`の代わりとして使用します。
> 詳しくはこちら: <https://manned.org/apt.8>
- 利用可能なパーケージとバージョンのリストの更新(他の`apt`コマンドの前での実行を推奨):
`sudo apt update`
- 指定されたパッケージの検索:
`apt search {{パッケージ}}`
- パッケージの情報を出力:
`apt show {{パッケージ}}`
- パッケージのインストール、または利用可能な最新バージョンに更新:
`sudo apt install {{パッケージ}}`
- パッケージの削除(`sudo apt remove --purge`の場合設定ファイルも削除):
`sudo apt remove {{パッケージ}}`
- インストールされている全てのパッケージを最新のバージョンにアップグレード:
`sudo apt upgrade`
- インストールできるすべてのパッケージを表示:
`apt list`
- インストールされた全てのパッケージを表示(依存関係も表示):
`apt list --installed`

View file

@ -1,32 +0,0 @@
Изменить права доступа файлу или папке.
Больше информации: <https://www.gnu.org/software/coreutils/chmod>.
Дать [u]пользователю, который владеет файлом, права на его [x]исполнение:
 chmod u+x файл
Дать права [u]пользователю права [r]чтения и [w]записи в файл/папку:
 chmod u+rw файл_или_папка
Убрать права на [x]исполнение у [g]группы:
 chmod g-x файл
Дать [a]всем пользователям права на [r]чтение и [x]исполенеие:
 chmod a+rx файл
Дать [o]другим (не из группы владельцев файлом) такие же права как и у [g]группы:
 chmod o=g файл
Убрать все права у [o]других:
 chmod o= файл
Изменить права рекурсивно, дав [g]группе и [o]другим возможность [w]записи в папку:
 chmod -R g+w,o+w папка

View file

@ -1,32 +0,0 @@
# chmod
> Изменить права доступа файлу или папке.
> Больше информации: <https://www.gnu.org/software/coreutils/chmod>.
- Дать [u]пользователю, который владеет файлом, права на его [x]исполнение:
`chmod u+x {{файл}}`
- Дать права [u]пользователю права [r]чтения и [w]записи в файл/папку:
`chmod u+rw {{файл_или_папка}}`
- Убрать права на [x]исполнение у [g]группы:
`chmod g-x {{файл}}`
- Дать [a]всем пользователям права на [r]чтение и [x]исполенеие:
`chmod a+rx {{файл}}`
- Дать [o]другим (не из группы владельцев файлом) такие же права как и у [g]группы:
`chmod o=g {{файл}}`
- Убрать все права у [o]других:
`chmod o= {{файл}}`
- Изменить права рекурсивно, дав [g]группе и [o]другим возможность [w]записи в папку:
`chmod -R g+w,o+w {{папка}}`

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,37 @@
Debian系ディストリビューションで使われるパッケージ管理システムです。
Ubuntuのバージョンが16.04か、それ以降で対話モードを使う場合`apt-get`の代わりとして使用します。
詳しくはこちら: <https://manned.org/apt.8>
 利用可能なパーケージとバージョンのリストの更新他の`apt`コマンドの前での実行を推奨):
 sudo apt update
 指定されたパッケージの検索:
 apt search パッケージ
 パッケージの情報を出力:
 apt show パッケージ
 パッケージのインストール、または利用可能な最新バージョンに更新:
 sudo apt install パッケージ
 パッケージの削除`sudo apt remove --purge`の場合設定ファイルも削除):
 sudo apt remove パッケージ
 インストールされている全てのパッケージを最新のバージョンにアップグレード:
 sudo apt upgrade
 インストールできるすべてのパッケージを表示:
 apt list
 インストールされた全てのパッケージを表示依存関係も表示:
 apt list --installed

View file

@ -0,0 +1,32 @@
An SVG (Scalable Vector Graphics) editing program.
Use -z to not open the GUI and only process files in the console.
Open an SVG file in the Inkscape GUI:
inkscape filename.svg
Export an SVG file into a bitmap with the default format (PNG) and the default resolution (90 DPI):
inkscape filename.svg -e filename.png
Export an SVG file into a bitmap of 600x400 pixels (aspect ratio distortion may occur):
inkscape filename.svg -e filename.png -w 600 -h 400
Export a single object, given its ID, into a bitmap:
inkscape filename.svg -i id -e object.png
Export an SVG document to PDF, converting all texts to paths:
inkscape filename.svg | inkscape | inkscape --export-pdf=inkscape.pdf | inkscape | inkscape --export-text-to-path
Duplicate the object with id="path123", rotate the duplicate 90 degrees, save the file, and quit Inkscape:
inkscape filename.svg --select=path123 --verb=EditDuplicate --verb=ObjectRotate90 --verb=FileSave --verb=FileQuit
Some invalid command just to test the correct highlighting of the command name:
inkscape --use-inkscape=v3.0 file

View file

@ -2,31 +2,31 @@
An SVG (Scalable Vector Graphics) editing program.
Use -z to not open the GUI and only process files in the console.
Open an SVG file in the Inkscape GUI:
 Open an SVG file in the Inkscape GUI:
 inkscape filename.svg
Export an SVG file into a bitmap with the default format (PNG) and the default resolution (90 DPI):
 Export an SVG file into a bitmap with the default format (PNG) and the default resolution (90 DPI):
 inkscape filename.svg -e filename.png
Export an SVG file into a bitmap of 600x400 pixels (aspect ratio distortion may occur):
 Export an SVG file into a bitmap of 600x400 pixels (aspect ratio distortion may occur):
 inkscape filename.svg -e filename.png -w 600 -h 400
Export a single object, given its ID, into a bitmap:
 Export a single object, given its ID, into a bitmap:
 inkscape filename.svg -i id -e object.png
Export an SVG document to PDF, converting all texts to paths:
 Export an SVG document to PDF, converting all texts to paths:
 inkscape filename.svg | inkscape | inkscape --export-pdf=inkscape.pdf | inkscape | inkscape --export-text-to-path
Duplicate the object with id="path123", rotate the duplicate 90 degrees, save the file, and quit Inkscape:
 Duplicate the object with id="path123", rotate the duplicate 90 degrees, save the file, and quit Inkscape:
 inkscape filename.svg --select=path123 --verb=EditDuplicate --verb=ObjectRotate90 --verb=FileSave --verb=FileQuit
Some invalid command just to test the correct highlighting of the command name:
 Some invalid command just to test the correct highlighting of the command name:
 inkscape --use-inkscape=v3.0 file

View file

@ -2,31 +2,31 @@
An SVG (Scalable Vector Graphics) editing program.
Use -z to not open the GUI and only process files in the console.
Open an SVG file in the Inkscape GUI:
 Open an SVG file in the Inkscape GUI:
inkscape filename.svg
Export an SVG file into a bitmap with the default format (PNG) and the default resolution (90 DPI):
 Export an SVG file into a bitmap with the default format (PNG) and the default resolution (90 DPI):
inkscape filename.svg -e filename.png
Export an SVG file into a bitmap of 600x400 pixels (aspect ratio distortion may occur):
 Export an SVG file into a bitmap of 600x400 pixels (aspect ratio distortion may occur):
inkscape filename.svg -e filename.png -w 600 -h 400
Export a single object, given its ID, into a bitmap:
 Export a single object, given its ID, into a bitmap:
inkscape filename.svg -i id -e object.png
Export an SVG document to PDF, converting all texts to paths:
 Export an SVG document to PDF, converting all texts to paths:
inkscape filename.svg | inkscape | inkscape --export-pdf=inkscape.pdf | inkscape | inkscape --export-text-to-path
Duplicate the object with id="path123", rotate the duplicate 90 degrees, save the file, and quit Inkscape:
 Duplicate the object with id="path123", rotate the duplicate 90 degrees, save the file, and quit Inkscape:
inkscape filename.svg --select=path123 --verb=EditDuplicate --verb=ObjectRotate90 --verb=FileSave --verb=FileQuit
Some invalid command just to test the correct highlighting of the command name:
 Some invalid command just to test the correct highlighting of the command name:
inkscape --use-inkscape=v3.0 file

View file

@ -0,0 +1,34 @@
inkscape
An SVG (Scalable Vector Graphics) editing program.
Use -z to not open the GUI and only process files in the console.
Open an SVG file in the Inkscape GUI:
inkscape filename.svg
Export an SVG file into a bitmap with the default format (PNG) and the default resolution (90 DPI):
inkscape filename.svg -e filename.png
Export an SVG file into a bitmap of 600x400 pixels (aspect ratio distortion may occur):
inkscape filename.svg -e filename.png -w 600 -h 400
Export a single object, given its ID, into a bitmap:
inkscape filename.svg -i id -e object.png
Export an SVG document to PDF, converting all texts to paths:
inkscape filename.svg | inkscape | inkscape --export-pdf=inkscape.pdf | inkscape | inkscape --export-text-to-path
Duplicate the object with id="path123", rotate the duplicate 90 degrees, save the file, and quit Inkscape:
inkscape filename.svg --select=path123 --verb=EditDuplicate --verb=ObjectRotate90 --verb=FileSave --verb=FileQuit
Some invalid command just to test the correct highlighting of the command name:
inkscape --use-inkscape=v3.0 file

View file

@ -0,0 +1,34 @@
 inkscape
An SVG (Scalable Vector Graphics) editing program.
Use -z to not open the GUI and only process files in the console.
 Open an SVG file in the Inkscape GUI:
 inkscape filename.svg
 Export an SVG file into a bitmap with the default format (PNG) and the default resolution (90 DPI):
 inkscape filename.svg -e filename.png
 Export an SVG file into a bitmap of 600x400 pixels (aspect ratio distortion may occur):
 inkscape filename.svg -e filename.png -w 600 -h 400
 Export a single object, given its ID, into a bitmap:
 inkscape filename.svg -i id -e object.png
 Export an SVG document to PDF, converting all texts to paths:
 inkscape filename.svg | inkscape | inkscape --export-pdf=inkscape.pdf | inkscape | inkscape --export-text-to-path
 Duplicate the object with id="path123", rotate the duplicate 90 degrees, save the file, and quit Inkscape:
 inkscape filename.svg --select=path123 --verb=EditDuplicate --verb=ObjectRotate90 --verb=FileSave --verb=FileQuit
 Some invalid command just to test the correct highlighting of the command name:
 inkscape --use-inkscape=v3.0 file

View file

@ -19,11 +19,3 @@ underline = false
underline = true
bold = false
italic = true
[display]
use_pager = false
compact = false
[updates]
auto_update = false
auto_update_interval_hours = 720