|
14 | 14 | use crate::error::UResult; |
15 | 15 | use crate::locale::translate; |
16 | 16 |
|
| 17 | +use clap::builder::{IntoResettable, Resettable, StyledStr}; |
17 | 18 | use clap::error::{ContextKind, ErrorKind}; |
18 | 19 | use clap::{Arg, ArgAction, ArgMatches, Command, Error}; |
19 | 20 |
|
@@ -556,6 +557,49 @@ impl CommandHelpLocalization for Command { |
556 | 557 | } |
557 | 558 | } |
558 | 559 |
|
| 560 | +pub trait ArgHelpLocalization { |
| 561 | + /// Add translation of "default" keyword for options with defaults. |
| 562 | + /// Also support options without defaults with the same output as normal .help() |
| 563 | + fn help_localized(self, description: impl IntoResettable<StyledStr>) -> Self; |
| 564 | +} |
| 565 | + |
| 566 | +impl ArgHelpLocalization for Arg { |
| 567 | + fn help_localized(self, description: impl IntoResettable<StyledStr>) -> Self { |
| 568 | + use std::fmt::Write; |
| 569 | + |
| 570 | + let mut template = clap::builder::StyledStr::new(); |
| 571 | + let mut has_description = false; |
| 572 | + |
| 573 | + // Manually extract the Option from Resettable because ".into_option()" is private |
| 574 | + if let Resettable::Value(description_str) = description.into_resettable() { |
| 575 | + write!(template, "{}", description_str).unwrap(); |
| 576 | + has_description = true; |
| 577 | + } |
| 578 | + |
| 579 | + let defaults: Vec<String> = self |
| 580 | + .get_default_values() |
| 581 | + .iter() |
| 582 | + .filter_map(|v| v.to_str().map(String::from)) |
| 583 | + .map(|s| format!("\"{}\"", s)) |
| 584 | + .collect(); |
| 585 | + if !defaults.is_empty() { |
| 586 | + if has_description { |
| 587 | + // Space between description and [Default: ...] |
| 588 | + write!(template, " ").unwrap(); |
| 589 | + } |
| 590 | + |
| 591 | + let default_label = translate!("common-default"); |
| 592 | + let defaults_str = defaults.join(" "); |
| 593 | + write!(template, "[{default_label}: {defaults_str}]").unwrap(); |
| 594 | + |
| 595 | + // Only hide default value if replaced otherwise clap throw an error |
| 596 | + self.hide_default_value(true).help(template) |
| 597 | + } else { |
| 598 | + self.help(template) |
| 599 | + } |
| 600 | + } |
| 601 | +} |
| 602 | + |
559 | 603 | /* spell-checker: disable */ |
560 | 604 | #[cfg(test)] |
561 | 605 | mod tests { |
|
0 commit comments