| 1 |
# `os_display` |
| 2 |
|
| 3 |
[](https://crates.io/crates/os_display) |
| 4 |
[](https://docs.rs/os_display/) |
| 5 |
[](https://blog.rust-lang.org/2022/12/15/Rust-1.66.0.html) |
| 6 |
[](https://github.com/blyxxyz/os_display/actions) |
| 7 |
|
| 8 |
This crate quotes strings so that they can be copy/pasted in the terminal. |
| 9 |
|
| 10 |
``` |
| 11 |
use os_display::Quotable; |
| 12 |
|
| 13 |
"filename".quote() → 'filename' |
| 14 |
"foo'bar".quote() → "foo'bar" |
| 15 |
"foo\u{1B}".quote() → $'foo\x1B' |
| 16 |
"ihavenospaces".maybe_quote() → ihavenospaces |
| 17 |
"i do have spaces".maybe_quote() → 'i do have spaces' |
| 18 |
``` |
| 19 |
|
| 20 |
This deals with a number of problems: |
| 21 |
|
| 22 |
- Strings can have control codes that mess up the message or the whole terminal. |
| 23 |
|
| 24 |
- Whitespace and special characters must be quoted or escaped to be used in a shell command. |
| 25 |
|
| 26 |
- `OsString`s and `Path`s can contain invalid Unicode (which even [`Path::display`](https://doc.rust-lang.org/std/path/struct.Path.html#method.display) doesn't preserve). This crate handles them as appropriate for the platform. |
| 27 |
|
| 28 |
Values are rendered so that they can always be pasted back into a shell without information loss. |
| 29 |
|
| 30 |
On Unix (and other platforms) values are quoted using bash/ksh syntax, while on Windows PowerShell syntax is used. |
| 31 |
|
| 32 |
## When should I use this? |
| 33 |
|
| 34 |
This crate is especially useful for command line programs that deal with arbitrary filenames or other "dirty" text. `ls` for example is the very tool you use to find odd filenames, so it's nice if it displays them well. This is why it's used in [`uutils`](https://github.com/uutils/coreutils). |
| 35 |
|
| 36 |
Another use case is printing commands for the user to run. [`xh`](https://github.com/ducaale/xh) has a mode that prints `curl` commands, using this crate to make them pretty and copy/pastable on both Unix and Windows. |
| 37 |
|
| 38 |
Any program that prints text that the user might want to paste into a terminal can get some use out of this. |
| 39 |
|
| 40 |
Most programs get along fine without it. You likely don't strictly need it, but you may find it a nice improvement. |
| 41 |
|
| 42 |
## Usage |
| 43 |
Import the [`Quotable`](https://docs.rs/os_display/latest/os_display/trait.Quotable.html) trait: |
| 44 |
|
| 45 |
```rust |
| 46 |
use os_display::Quotable; |
| 47 |
``` |
| 48 |
|
| 49 |
This adds two methods to the common string types (including `OsStr`): `.quote()` and `.maybe_quote()`. They return `Quoted`, a wrapper with a custom `Display` implementation. |
| 50 |
|
| 51 |
`.quote()` always puts quotes around the text: |
| 52 |
|
| 53 |
```rust |
| 54 |
// Found file 'filename' |
| 55 |
println!("Found file {}", "filename".quote()); |
| 56 |
|
| 57 |
// Found file "foo'bar" |
| 58 |
println!("Found file {}", "foo'bar".quote()); |
| 59 |
|
| 60 |
// Unix: Found file $'foo\nbar' |
| 61 |
// Windows: Found file "foo`nbar" |
| 62 |
println!("Found file {}", "foo\nbar".quote()); |
| 63 |
``` |
| 64 |
|
| 65 |
`.maybe_quote()` only adds them if necessary because of whitespace or special characters: |
| 66 |
|
| 67 |
```rust |
| 68 |
// filename: Not found |
| 69 |
println!("{}: Not found", "filename".maybe_quote()); |
| 70 |
|
| 71 |
// 'foo bar': Not found |
| 72 |
println!("{}: Not found", "foo bar".maybe_quote()); |
| 73 |
|
| 74 |
// '*?$': Not found |
| 75 |
println!("{}: Not found", "*?$".maybe_quote()); |
| 76 |
``` |
| 77 |
|
| 78 |
`.quote()` is best used inside longer sentences while `.maybe_quote()` can be used for text that's already separated some other way, like by a colon. This is the convention of many GNU programs. |
| 79 |
|
| 80 |
## Limitations |
| 81 |
- Unicode may be quoted but only control characters are escaped. The printed text can still look weird, and a few (buggy) terminals drop certain characters. |
| 82 |
- This library should **not** be used to interpolate text into shell scripts. It's designed for readability, not absolute safety. Consider using the [`shell-escape`](https://crates.io/crates/shell-escape) crate instead (or ideally, passing in the values in some other way). |
| 83 |
- The output is not compatible with every single shell. |
| 84 |
- [Old versions of PowerShell treat quotes differently in arguments to external commands](https://stackoverflow.com/questions/6714165). This library defaults to the modern behavior. The `Quoted::external()` method toggles legacy quoting. |
| 85 |
- I'm not a Unicode expert. The first release of this crate had multiple oversights and there may be more. |
| 86 |
|
| 87 |
## Invalid unicode |
| 88 |
On Unix: |
| 89 |
|
| 90 |
```rust |
| 91 |
use std::ffi::OsStr; |
| 92 |
use std::os::unix::ffi::OsStrExt; |
| 93 |
|
| 94 |
// \xFF makes this invalid UTF-8, so to_str() would fail |
| 95 |
let bad_string = OsStr::from_bytes(&[b'x', 0xFF, b'y']); |
| 96 |
assert_eq!(bad_string.quote().to_string(), r#"$'x\xFFy'"#); |
| 97 |
``` |
| 98 |
|
| 99 |
On Windows: |
| 100 |
|
| 101 |
```rust |
| 102 |
use std::ffi::OsString; |
| 103 |
use std::os::windows::ffi::OsStringExt; |
| 104 |
|
| 105 |
// 0xD800 is an unpaired surrogate, making this invalid UTF-16 |
| 106 |
let bad_string = OsString::from_wide(&[b'a' as u16, 0xD800, b'b' as u16]); |
| 107 |
assert_eq!(bad_string.quote().to_string(), r#""a`u{D800}b""#); |
| 108 |
``` |
| 109 |
|
| 110 |
## Zero-width unicode |
| 111 |
Some codepoints are zero-width. They can make a string invisible, or they can make it hard to select. GNU tools struggle with this: |
| 112 |
|
| 113 |
```console |
| 114 |
$ wc $'\u200b' |
| 115 |
wc: : No such file or directory |
| 116 |
``` |
| 117 |
|
| 118 |
`os_display` adds quotes in such cases: |
| 119 |
|
| 120 |
```rust |
| 121 |
assert_eq!("\u{200B}".maybe_quote().to_string(), "'\u{200B}'"); |
| 122 |
``` |
| 123 |
|
| 124 |
It still misleadingly looks like `''` when printed, but it's possible to copy and paste it and get the right result. |
| 125 |
|
| 126 |
## Bidirectional unicode |
| 127 |
A carefully-crafted string can move part of itself to the end of the line: |
| 128 |
```console |
| 129 |
$ wc $'filename\u202E\u2066 [This does not belong!]\u2069\u2066' |
| 130 |
wc: 'filename': No such file or directory [This does not belong!] |
| 131 |
``` |
| 132 |
This is known as a [*Trojan Source*](https://trojansource.codes/) attack. It uses control codes for bidirectional text. |
| 133 |
|
| 134 |
`os_display` escapes those control codes if they're not properly terminated. |
| 135 |
|
| 136 |
## Feature flags |
| 137 |
By default you can only use the current platform's quoting style. That's appropriate most of the time. |
| 138 |
|
| 139 |
### `windows`/`unix` |
| 140 |
The `windows` and `unix` optional features can be enabled to add constructors to `Quoted`. |
| 141 |
|
| 142 |
`Quoted::unix("some string")` will quote with bash/ksh syntax no matter the platform, and `Quoted::windows("etc")` uses PowerShell syntax. |
| 143 |
|
| 144 |
`Quoted::unix_raw` and `Quoted::windows_raw` take `&[u8]` (for malformed UTF-8) and `&[u16]` (for malformed UTF-16), respectively. |
| 145 |
|
| 146 |
### `native` |
| 147 |
The `native` feature (enabled by default) is required for the `Quotable` trait and the `Quoted::native(&str)` and `Quoted::native_raw(&OsStr)` constructors. If it's not enabled then the quoting style has to be chosen explicitly. |
| 148 |
|
| 149 |
### `alloc`/`std` |
| 150 |
This crate is `no_std`-compatible if the `alloc` and/or `std` features are disabled. |
| 151 |
|
| 152 |
The `std` feature is required to quote `OsStr`s. The `alloc` feature is required for `Quoted::windows_raw`. |
| 153 |
|
| 154 |
## Alternative constructors |
| 155 |
`Quoted` has constructors for specific styles as well as `Quoted::native()` and `Quoted::native_raw()`. These can be used as an alternative to the `Quotable` trait if you prefer boring functions. |
| 156 |
|
| 157 |
By default quotes are always added. To get behavior like `.maybe_quote()` use the `.force()` method: |
| 158 |
```rust |
| 159 |
println!("{}", Quoted::native(x).force(false)); |
| 160 |
``` |
| 161 |
|
| 162 |
## Testing |
| 163 |
The Unix implementation has been [fuzzed](https://github.com/rust-fuzz/cargo-fuzz) against bash, zsh, mksh, ksh93 and busybox to ensure all output is interpreted back as the original string. It has been fuzzed to a more limited extent against fish, dash, tcsh, posh, and yash (which don't support all of the required syntax). |
| 164 |
|
| 165 |
The PowerShell implementation has been fuzzed against PowerShell Core 7.1.4 running on Linux. |
| 166 |
|
| 167 |
Both implementations have been fuzzed to test their protection against Trojan Source attacks. |
| 168 |
|
| 169 |
## Acknowledgments |
| 170 |
This library is modeled after the quoting done by [Gnulib](https://www.gnu.org/software/gnulib/) as seen in the GNU coreutils. The behavior is not identical, however: |
| 171 |
- GNU uses octal escapes, like `\377` instead of `\xFF`. |
| 172 |
- GNU eagerly switches quoting style midway through, like `''$'\n''xyz'` instead of `$'\nxyz'`. `os_display` avoids this unless necessary. |
| 173 |
- GNU escapes unassigned codepoints instead of leaving their handling up to the terminal. |
| 174 |
- GNU doesn't handle zero-width codepoints specially. |
| 175 |
|
| 176 |
The first version of this code was written for the [uutils project](https://github.com/uutils/coreutils). The feedback and the opportunity to use it in a large codebase were helpful. |