Merge branch 'main' into callback
This commit is contained in:
commit
f5214e476c
1 changed files with 38 additions and 11 deletions
49
src/lib.rs
49
src/lib.rs
|
@ -22,6 +22,36 @@ fn to_c_char(text: &str) -> *mut c_char {
|
||||||
return CString::new(text).unwrap().into_raw();
|
return CString::new(text).unwrap().into_raw();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
enum Output {
|
||||||
|
Stdout(String),
|
||||||
|
Stderr(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
struct OutputCapture {
|
||||||
|
stdout: BufferRedirect,
|
||||||
|
stderr: BufferRedirect,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OutputCapture {
|
||||||
|
pub fn capture() -> std::io::Result<Self> {
|
||||||
|
Ok(Self {
|
||||||
|
stdout: BufferRedirect::stdout()?,
|
||||||
|
stderr: BufferRedirect::stderr()?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_output(mut self) -> std::io::Result<Output> {
|
||||||
|
let mut buf = String::new();
|
||||||
|
|
||||||
|
if self.stderr.read_to_string(&mut buf)? > 0 {
|
||||||
|
Ok(Output::Stderr(buf))
|
||||||
|
} else {
|
||||||
|
self.stdout.read_to_string(&mut buf)?;
|
||||||
|
Ok(Output::Stdout(buf))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct MenuError {
|
pub struct MenuError {
|
||||||
message: String,
|
message: String,
|
||||||
|
@ -154,19 +184,15 @@ impl Menu {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn run(&self) -> Result<String, MenuError> {
|
pub fn run(&self) -> Result<String, MenuError> {
|
||||||
|
let output = OutputCapture::capture().unwrap();
|
||||||
|
|
||||||
unsafe {
|
unsafe {
|
||||||
let mut stdout = BufferRedirect::stdout().unwrap();
|
match (bindings::menu_run(self.ctx), output.get_output()) {
|
||||||
match bindings::menu_run(self.ctx) {
|
(0, Ok(Output::Stdout(value))) => Ok(value.trim_end().to_string()),
|
||||||
0 => {
|
(n, Ok(Output::Stdout(value) | Output::Stderr(value))) => {
|
||||||
let mut buf = String::new();
|
Err(MenuError::new(n, value))
|
||||||
stdout.read_to_string(&mut buf).unwrap();
|
|
||||||
Ok(buf.trim_end().to_string())
|
|
||||||
}
|
|
||||||
n => {
|
|
||||||
let mut buf = String::new();
|
|
||||||
stdout.read_to_string(&mut buf).unwrap();
|
|
||||||
Err(MenuError::new(n, buf))
|
|
||||||
}
|
}
|
||||||
|
(n, Err(e)) => Err(MenuError::new(n, e.to_string())),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -197,6 +223,7 @@ mod tests {
|
||||||
.add_items(&items);
|
.add_items(&items);
|
||||||
|
|
||||||
let result = menu.run().expect("couldn't get result");
|
let result = menu.run().expect("couldn't get result");
|
||||||
|
println!("{:?}", result.as_bytes());
|
||||||
assert!(items.contains(&result.as_str()));
|
assert!(items.contains(&result.as_str()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Reference in a new issue