r-lib / cli

Tools for making beautiful & useful command line interfaces
https://cli.r-lib.org/
Other
654 stars 70 forks source link

Errors formatting error messages with brackets #735

Closed topepo closed 1 month ago

topepo commented 1 month ago

Here's an example from tidymodels/recipes#1380

msg <- "Error in if (df < 0) { : missing blah blah\n"
cli::format_error(msg)
#> Error in glue(str, .envir = .envir, .transformer = transformer, .cli = TRUE, : Expecting '}'

# We patched using
msg <- gsub("(\\{)", "\\1\\1", msg)
msg <- gsub("(\\})", "\\1\\1", msg)
msg
#> [1] "Error in if (df < 0) {{ : missing blah blah\n"
cli::format_error(msg)
#> [1] "Error in if (df < 0) { : missing blah blah"

Created on 2024-10-22 with reprex v2.1.0

Happy to add a PR and tests if you suggest where to add gsub's

gaborcsardi commented 1 month ago

Don't do the gsub()s, the correct way to solve this is:

msg <- "Error in if (df < 0) { : missing blah blah\n"
cli::format_error("{msg}")

The rule of thumb is to always pass a string literal to cli functions, never a variable from the user (that's actually a security issue as well!) or even an error message.