|
14 | 14 | use crate::error::{UResult, USimpleError}; |
15 | 15 | use crate::locale::translate; |
16 | 16 |
|
17 | | -use clap::builder::StyledStr; |
| 17 | +use clap::builder::{IntoResettable, Resettable, StyledStr}; |
18 | 18 | use clap::error::{ContextKind, ErrorKind}; |
19 | 19 | use clap::{Arg, ArgAction, ArgMatches, Command, Error}; |
20 | 20 |
|
@@ -655,6 +655,47 @@ impl CommandHelpLocalization for Command { |
655 | 655 | } |
656 | 656 | } |
657 | 657 |
|
| 658 | +pub trait ArgHelpLocalization { |
| 659 | + /// Add translation of "default" keyword for options with defaults. |
| 660 | + /// Also support options without defaults with the same output as normal .help() |
| 661 | + fn help_with_localized_default(self, description: impl IntoResettable<StyledStr>) -> Self; |
| 662 | +} |
| 663 | + |
| 664 | +impl ArgHelpLocalization for Arg { |
| 665 | + fn help_with_localized_default(self, description: impl IntoResettable<StyledStr>) -> Self { |
| 666 | + use std::fmt::Write; |
| 667 | + |
| 668 | + let mut template = clap::builder::StyledStr::new(); |
| 669 | + let mut has_description = false; |
| 670 | + |
| 671 | + // Manually extract the Option from Resettable because ".into_option()" is private |
| 672 | + if let Resettable::Value(description_str) = description.into_resettable() { |
| 673 | + write!(template, "{description_str}").unwrap(); |
| 674 | + has_description = true; |
| 675 | + } |
| 676 | + |
| 677 | + let defaults: Vec<String> = self |
| 678 | + .get_default_values() |
| 679 | + .iter() |
| 680 | + .filter_map(|v| v.to_str().map(String::from)) |
| 681 | + .map(|s| format!("\"{s}\"")) |
| 682 | + .collect(); |
| 683 | + if defaults.is_empty() { |
| 684 | + self.help(template) |
| 685 | + } else { |
| 686 | + if has_description { |
| 687 | + write!(template, " ").unwrap(); |
| 688 | + } |
| 689 | + |
| 690 | + let default_label = translate!("common-default"); |
| 691 | + let defaults_str = defaults.join(" "); |
| 692 | + write!(template, "[{default_label}: {defaults_str}]").unwrap(); |
| 693 | + // Only hide default value if replaced otherwise clap throw an error |
| 694 | + self.hide_default_value(true).help(template) |
| 695 | + } |
| 696 | + } |
| 697 | +} |
| 698 | + |
658 | 699 | /* spell-checker: disable */ |
659 | 700 | #[cfg(test)] |
660 | 701 | mod tests { |
|
0 commit comments