Skip to content

Commit

Permalink
Auto merge of #11494 - ehuss:stabilize-diagnostic-width, r=weihanglo
Browse files Browse the repository at this point in the history
Stabilize terminal-width

This stabilized the passing of the `--diagnostic-width` flag to rustc and rustdoc so that they will format diagnostics to fit within the terminal size. Previously they always assume the width is 140. The diagnostics are trimmed with `...` to elide parts of extra-long lines.

In cases where the width isn't known (such as not when used on a tty, or with mintty), then cargo does not pass the flag and the default of 140 is still used.

At this time there is no way for the user to override the width (unlike with the progress bar width). That can be added in the future if there is demand. rust-lang/rust#84673 (comment) contains some thoughts on some different ideas.

Closes rust-lang/rust#84673
  • Loading branch information
bors committed Dec 19, 2022
2 parents 9cb3941 + 1709f0a commit 1d8cdaa
Show file tree
Hide file tree
Showing 5 changed files with 27 additions and 73 deletions.
18 changes: 2 additions & 16 deletions src/cargo/core/compiler/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -899,22 +899,8 @@ fn add_error_format_and_color(cx: &Context<'_, '_>, cmd: &mut ProcessBuilder) {
cmd.arg(json);

let config = cx.bcx.config;
if config.nightly_features_allowed {
match (
config.cli_unstable().terminal_width,
config.shell().err_width().diagnostic_terminal_width(),
) {
// Terminal width explicitly provided - only useful for testing.
(Some(Some(width)), _) => {
cmd.arg(format!("--diagnostic-width={}", width));
}
// Terminal width was not explicitly provided but flag was provided - common case.
(Some(None), Some(width)) => {
cmd.arg(format!("--diagnostic-width={}", width));
}
// User didn't opt-in.
_ => (),
}
if let Some(width) = config.shell().err_width().diagnostic_terminal_width() {
cmd.arg(format!("--diagnostic-width={width}"));
}
}

Expand Down
16 changes: 4 additions & 12 deletions src/cargo/core/features.rs
Original file line number Diff line number Diff line change
Expand Up @@ -686,7 +686,6 @@ unstable_cli_options!(
target_applies_to_host: bool = ("Enable the `target-applies-to-host` key in the .cargo/config.toml file"),
rustdoc_map: bool = ("Allow passing external documentation mappings to rustdoc"),
separate_nightlies: bool = (HIDDEN),
terminal_width: Option<Option<usize>> = ("Provide a terminal width to rustc for error truncation"),
publish_timeout: bool = ("Enable the `publish.timeout` key in .cargo/config.toml file"),
unstable_options: bool = ("Allow the usage of unstable options"),
skip_rustdoc_fingerprint: bool = (HIDDEN),
Expand Down Expand Up @@ -749,6 +748,9 @@ const STABILIZED_TIMINGS: &str = "The -Ztimings option has been stabilized as --

const STABILISED_MULTITARGET: &str = "Multiple `--target` options are now always available.";

const STABILIZED_TERMINAL_WIDTH: &str =
"The -Zterminal-width option is now always enabled for terminal output.";

fn deserialize_build_std<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
where
D: serde::Deserializer<'de>,
Expand Down Expand Up @@ -862,16 +864,6 @@ impl CliUnstable {
Ok(true)
}

fn parse_usize_opt(value: Option<&str>) -> CargoResult<Option<usize>> {
Ok(match value {
Some(value) => match value.parse::<usize>() {
Ok(value) => Some(value),
Err(e) => bail!("expected a number, found: {}", e),
},
None => None,
})
}

let mut stabilized_warn = |key: &str, version: &str, message: &str| {
warnings.push(format!(
"flag `-Z {}` has been stabilized in the {} release, \
Expand Down Expand Up @@ -955,7 +947,7 @@ impl CliUnstable {
"separate-nightlies" => self.separate_nightlies = parse_empty(k, v)?,
"multitarget" => stabilized_warn(k, "1.64", STABILISED_MULTITARGET),
"rustdoc-map" => self.rustdoc_map = parse_empty(k, v)?,
"terminal-width" => self.terminal_width = Some(parse_usize_opt(v)?),
"terminal-width" => stabilized_warn(k, "1.68", STABILIZED_TERMINAL_WIDTH),
"sparse-registry" => self.sparse_registry = parse_empty(k, v)?,
"registry-auth" => self.registry_auth = parse_empty(k, v)?,
"namespaced-features" => stabilized_warn(k, "1.60", STABILISED_NAMESPACED_FEATURES),
Expand Down
7 changes: 5 additions & 2 deletions src/cargo/core/shell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,12 @@ pub enum TtyWidth {
}

impl TtyWidth {
/// Returns the width provided with `-Z terminal-width` to rustc to truncate diagnostics with
/// long lines.
/// Returns the width of the terminal to use for diagnostics (which is
/// relayed to rustc via `--diagnostic-width`).
pub fn diagnostic_terminal_width(&self) -> Option<usize> {
if let Ok(width) = std::env::var("__CARGO_TEST_TTY_WIDTH_DO_NOT_USE_THIS") {
return Some(width.parse().unwrap());
}
match *self {
TtyWidth::NoTty | TtyWidth::Guess(_) => None,
TtyWidth::Known(width) => Some(width),
Expand Down
44 changes: 6 additions & 38 deletions src/doc/src/reference/unstable.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,6 @@ Each new feature described below should explain how to use it.
* [public-dependency](#public-dependency) — Allows dependencies to be classified as either public or private.
* Output behavior
* [out-dir](#out-dir) — Adds a directory where artifacts are copied to.
* [terminal-width](#terminal-width) — Tells rustc the width of the terminal so that long diagnostic messages can be truncated to be more readable.
* [Different binary name](#different-binary-name) — Assign a name to the built binary that is separate from the crate name.
* Compile behavior
* [mtime-on-use](#mtime-on-use) — Updates the last-modified timestamp on every dependency every time it is used, to provide a mechanism to delete unused artifacts.
Expand Down Expand Up @@ -723,43 +722,6 @@ The default value is `"remote"`.

The value may also take a URL for a custom location.

### terminal-width

* Tracking Issue: [#84673](https://github.com/rust-lang/rust/issues/84673)

This feature provides a new flag, `-Z terminal-width`, which is used to pass
a terminal width to `rustc` so that error messages containing long lines
can be intelligently truncated.

For example, passing `-Z terminal-width=20` (an arbitrarily low value) might
produce the following error:

```text
error[E0308]: mismatched types
--> src/main.rs:2:17
|
2 | ..._: () = 42;
| -- ^^ expected `()`, found integer
| |
| expected due to this
error: aborting due to previous error
```

In contrast, without `-Z terminal-width`, the error would look as shown below:

```text
error[E0308]: mismatched types
--> src/main.rs:2:17
|
2 | let _: () = 42;
| -- ^^ expected `()`, found integer
| |
| expected due to this
error: aborting due to previous error
```

### per-package-target
* Tracking Issue: [#9406](https://github.com/rust-lang/cargo/pull/9406)
* Original Pull Request: [#9030](https://github.com/rust-lang/cargo/pull/9030)
Expand Down Expand Up @@ -1447,3 +1409,9 @@ See [workspace.package](workspaces.md#the-package-table),
[workspace.dependencies](workspaces.md#the-dependencies-table),
and [inheriting-a-dependency-from-a-workspace](specifying-dependencies.md#inheriting-a-dependency-from-a-workspace)
for more information.

### terminal-width

The `-Z terminal-width` option has been stabilized in the 1.68 release.
The terminal width is always passed to the compiler when running from a
terminal where Cargo can automatically detect the width.
15 changes: 10 additions & 5 deletions tests/testsuite/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6130,23 +6130,28 @@ fn target_directory_backup_exclusion() {
assert!(!&cachedir_tag.is_file());
}

#[cargo_test(>=1.64, reason = "--diagnostic-width is stabilized in 1.64")]
#[cargo_test]
fn simple_terminal_width() {
let p = project()
.file(
"src/lib.rs",
r#"
fn main() {
pub fn foo() {
let _: () = 42;
}
"#,
)
.build();

p.cargo("build -Zterminal-width=20")
.masquerade_as_nightly_cargo(&["terminal-width"])
p.cargo("build -v")
.env("__CARGO_TEST_TTY_WIDTH_DO_NOT_USE_THIS", "20")
.with_status(101)
.with_stderr_contains("3 | ..._: () = 42;")
.with_stderr_contains("[RUNNING] `rustc [..]--diagnostic-width=20[..]")
.run();

p.cargo("doc -v")
.env("__CARGO_TEST_TTY_WIDTH_DO_NOT_USE_THIS", "20")
.with_stderr_contains("[RUNNING] `rustdoc [..]--diagnostic-width=20[..]")
.run();
}

Expand Down

0 comments on commit 1d8cdaa

Please sign in to comment.