1 个不稳定版本
0.0.1 | 2023年7月20日 |
---|
#147 in #捕获
7KB
ctsh!
在编译时运行命令(可选地)捕获它们的输出。
use ctsh::ctsh;
let result = ctsh!("echo" "Hello" "World" as str);
assert_eq!(result.trim(), "Hello World");
lib.rs
:
ctsh!
在编译时运行命令(可选地)捕获它们的输出。
use ctsh::ctsh;
let result = ctsh!("echo" "Hello" "World" as str);
assert_eq!(result.trim(), "Hello World");
命令可以一起通过管道连接。
let result = ctsh!("echo" "Hello" "World" | "tr" "-d" "l" as str);
assert_eq!(result.trim(), "Heo Word");
可以使用分号执行多个命令。如果它们的输出用于表达式,它们会生成所有输出的元组。
let result = ctsh!{
"echo" "1" as str;
"echo" "foo" as str;
};
assert_eq!(result.0.trim(), "1");
assert_eq!(result.1.trim(), "foo");
为命令提供了多种处理方式。
let result = ctsh!{
"echo" "moo"; // execute command and ignore its output
"echo" "oink" as str; // capture output as string literal (`&'static str`)
"echo" "meow" as bytes; // capture output as byte literal (`&'static [u8; _]`)
"echo" "()" as expr; // capture output as Rust expression
};
assert_eq!(result, ("oink\n", b"meow\n", ()));
ctsh!{
"echo" r#"
#[derive(Debug)]
struct Foo;
let result = format!("{:?}", Foo);
"# as stmts; // capture output as Rust statements (cannot be mixed with expression capturing)
}
assert_eq!(result, "Foo");
每个 ctsh!
都在 CARGO_MANIFEST_DIR
开始执行命令。
let result = ctsh!("pwd" as str);
assert_eq!(result.trim(), env!("CARGO_MANIFEST_DIR"));
使用 cd
来更改目录。注意:cd
使用规范化的路径,并解析了所有符号链接。
let result = ctsh!{
cd "/";
"pwd" as str;
};
assert_eq!(result.trim(), "/");
可以使用特殊形式 cd temp
来创建并进入一个在之后会被清理的临时目录。
ctsh!{
cd temp;
"touch" "garbage"; // does not leave any `garbage` files on your computer
}
ctsh!
如果命令失败,将导致编译时错误。
ctsh!("false")
ctsh!("false" | "true")
使用 ?
标记可能会失败的每个命令来忽略错误。
ctsh!("false" ? | "true")
ctsh!("false" | "true" ?)
依赖项
~2–11MB
~127K SLoC