Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(help): Ensure padding isn't stripped #5084

Merged
merged 2 commits into from Aug 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
15 changes: 15 additions & 0 deletions clap_builder/src/builder/styled_str.rs
@@ -1,3 +1,5 @@
#![cfg_attr(not(feature = "usage"), allow(dead_code))]

/// Terminal-styling container
///
/// Styling may be encoded as [ANSI Escape Code](https://en.wikipedia.org/wiki/ANSI_escape_code)
Expand Down Expand Up @@ -47,6 +49,19 @@ impl StyledStr {
self.0 = self.0.trim().to_owned()
}

pub(crate) fn trim_start_lines(&mut self) {
if let Some(pos) = self.0.find('\n') {
let (leading, help) = self.0.split_at(pos + 1);
if leading.trim().is_empty() {
self.0 = help.to_owned()
}
}
}

pub(crate) fn trim_end(&mut self) {
self.0 = self.0.trim_end().to_owned()
}

#[cfg(feature = "help")]
pub(crate) fn replace_newline_var(&mut self) {
self.0 = self.0.replace("{n}", "\n");
Expand Down
6 changes: 4 additions & 2 deletions clap_builder/src/output/help.rs
Expand Up @@ -30,8 +30,10 @@ pub(crate) fn write_help(writer: &mut StyledStr, cmd: &Command, usage: &Usage<'_
}
}

// Remove any extra lines caused by book keeping
writer.trim();
// Remove any lines from unused sections
writer.trim_start_lines();
// Remove any whitespace caused by book keeping
writer.trim_end();
// Ensure there is still a trailing newline
writer.push_str("\n");
}
17 changes: 17 additions & 0 deletions tests/builder/help.rs
Expand Up @@ -1333,6 +1333,23 @@ Options:
utils::assert_output(cmd, "ctest --help", ISSUE_777, false);
}

#[test]
fn dont_strip_padding_issue_5083() {
let cmd = Command::new("test")
.help_template("{subcommands}")
.subcommands([
Command::new("one"),
Command::new("two"),
Command::new("three"),
]);
static EXPECTED: &str = " one
two
three
help Print this message or the help of the given subcommand(s)
";
utils::assert_output(cmd, "test --help", EXPECTED, false);
}

static OVERRIDE_HELP_SHORT: &str = "\
Usage: test

Expand Down