Strip out control codes from the logged messages (#10081)

* Strip out control codes from the logged messages

* Also strip away C1 control codes

* Add extra comments

* Clear the buffer after flushing; rename `write` to `flush`

* Move control code stripping into its own function

* Also strip out control codes from panic messages

* Also strip out Unicode left-to-right/right-to-left control codes
This commit is contained in:
Koute
2021-11-01 17:46:32 +09:00
committed by GitHub
parent 21c8d18c23
commit 8c2ea19085
5 changed files with 142 additions and 20 deletions
@@ -25,6 +25,7 @@
//! temporarily be disabled by using an [`AbortGuard`].
use backtrace::Backtrace;
use regex::Regex;
use std::{
cell::Cell,
io::{self, Write},
@@ -125,6 +126,24 @@ impl Drop for AbortGuard {
}
}
// NOTE: When making any changes here make sure to also change this function in `sc-tracing`.
fn strip_control_codes(input: &str) -> std::borrow::Cow<str> {
lazy_static::lazy_static! {
static ref RE: Regex = Regex::new(r#"(?x)
\x1b\[[^m]+m| # VT100 escape codes
[
\x00-\x09\x0B-\x1F # ASCII control codes / Unicode C0 control codes, except \n
\x7F # ASCII delete
\u{80}-\u{9F} # Unicode C1 control codes
\u{202A}-\u{202E} # Unicode left-to-right / right-to-left control characters
\u{2066}-\u{2069} # Same as above
]
"#).expect("regex parsing doesn't fail; qed");
}
RE.replace_all(input, "")
}
/// Function being called when a panic happens.
fn panic_hook(info: &PanicInfo, report_url: &str, version: &str) {
let location = info.location();
@@ -139,6 +158,8 @@ fn panic_hook(info: &PanicInfo, report_url: &str, version: &str) {
},
};
let msg = strip_control_codes(&msg);
let thread = thread::current();
let name = thread.name().unwrap_or("<unnamed>");
@@ -181,4 +202,44 @@ mod tests {
let _guard = AbortGuard::force_abort();
std::panic::catch_unwind(|| panic!()).ok();
}
fn run_test_in_another_process(
test_name: &str,
test_body: impl FnOnce(),
) -> Option<std::process::Output> {
if std::env::var("RUN_FORKED_TEST").is_ok() {
test_body();
None
} else {
let output = std::process::Command::new(std::env::current_exe().unwrap())
.arg(test_name)
.env("RUN_FORKED_TEST", "1")
.output()
.unwrap();
assert!(output.status.success());
Some(output)
}
}
#[test]
fn control_characters_are_always_stripped_out_from_the_panic_messages() {
const RAW_LINE: &str = "$$START$$\x1B[1;32mIn\u{202a}\u{202e}\u{2066}\u{2069}ner\n\r\x7ftext!\u{80}\u{9f}\x1B[0m$$END$$";
const SANITIZED_LINE: &str = "$$START$$Inner\ntext!$$END$$";
let output = run_test_in_another_process(
"control_characters_are_always_stripped_out_from_the_panic_messages",
|| {
set("test", "1.2.3");
let _guard = AbortGuard::force_unwind();
let _ = std::panic::catch_unwind(|| panic!("{}", RAW_LINE));
},
);
if let Some(output) = output {
let stderr = String::from_utf8(output.stderr).unwrap();
assert!(!stderr.contains(RAW_LINE));
assert!(stderr.contains(SANITIZED_LINE));
}
}
}