作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我目前正在研究 Rust port证券tool .根据 Rust 的指南,我想将核心库隔离到它自己的箱子中,这样我们就可以创建与核心库交互的各种工具(CLI、API、流等),而无需将它们耦合在一起。
核心库公开了两个公共(public)枚举,其中之一是 PermutationMode
(截断):
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum PermutationMode {
All,
Addition,
BitSquatting,
Homoglyph,
}
使用 Clap 创建 CLI 实用程序时,我想像这样将这个库枚举扩展为 CLI 的一部分:
use clap::Clap;
use twistrs::permutate::PermutationMode;
#[derive(Clap, PartialEq, Debug)]
#[clap(name = "twistrs-cli")]
struct Opts {
#[clap(short, long)]
registered_domains: bool,
#[clap(arg_enum)]
permutation_mode: PermutationMode,
}
因此,当调用 CLI 时,我们可以将排列模式从用户无缝传递到 CLI,再到库,而 CLI 无需了解内部模式(如果库添加了更多).
./twist-cli --registered-domains --permutation_mode=all example.com
目前这似乎是不可能的(这是有道理的)。一种尝试是使用类型别名:
#[derive(Clap)]
type ArgPermutationMode = PermutationMode
但是我们不能为类型别名使用派生宏。我还尝试“克隆”枚举并尝试映射到库枚举:
enum ArgPermutationMode {
PermutationMode::All,
}
不编译。
问题 - 是否可以扩展内部库 Enum 以将其用作 Clap 参数?
最佳答案
很遗憾没有。您必须重新定义枚举,以便 arg_enum!
宏可以访问 token 。
如果你在两者之间添加一个转换函数,那么你可以确保上游对库枚举的更改会通过给你一个编译错误来强制你更新你的 CLI:
arg_enum! {
enum ArgPermutationMode {
All,
Addition,
BitSquatting,
Homoglyph,
}
}
impl From<ArgPermutationMode> for PermutationMode {
fn from(other: ArgPermutationMode) -> PermutationMode {
match other {
ArgPermutationMode::All => PermutationMode::All,
ArgPermutationMode::Addition => PermutationMode::Addition,
ArgPermutationMode::BitSquatting => PermutationMode::BitSquatting,
ArgPermutationMode::Homoglyph => PermutationMode::Homoglyph,
}
}
}
impl From<PermutationMode> for ArgPermutationMode {
fn from(other: PermutationMode) -> ArgPermutationMode {
match other {
PermutationMode::All => ArgPermutationMode::All,
PermutationMode::Addition => ArgPermutationMode::Addition,
PermutationMode::BitSquatting => ArgPermutationMode::BitSquatting,
xPermutationMode::Homoglyph => ArgPermutationMode::Homoglyph,
}
}
}
如果您发现自己经常使用宏,则可以使用宏来减少该样板。
鉴于您可以控制另一个 crate,您可以通过尝试其他几种解决方法之一来妥协:
include!
在两个 crate 中使用相同的源。这假设您的 crate 在同一个工作区中。EnumIter
来自 strum_macros
.这将允许您遍历枚举的变体,以便您可以将它们提供给 Clap,而无需在该 crate 中具有 Clap 依赖项。您将拥有一个 strum_macros
依赖项,因此是否真的更好,取决于您。clap_args!
调用,但对其进行功能控制。您的应用程序箱可以启用此功能,但大多数用户不会。关于rust - 如何为 Clap Args 使用内部库枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62491508/
我是一名优秀的程序员,十分优秀!