Skip to content

Commit d1e1551

Browse files
committed
feat(plugin-tee): working version
1 parent 8b5e608 commit d1e1551

File tree

1 file changed

+52
-5
lines changed

1 file changed

+52
-5
lines changed

crates/plugin-tee/src/lib.rs

Lines changed: 52 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
#[allow(warnings)]
22
mod bindings;
33

4+
use std::io::Write;
5+
46
use crate::bindings::exports::repl::api::plugin::Guest;
7+
use crate::bindings::repl::api::host_state_plugin;
58
use crate::bindings::repl::api::transport;
69

710
struct Component;
@@ -31,11 +34,55 @@ DESCRIPTION
3134
}
3235

3336
fn run(payload: String) -> Result<transport::PluginResponse, ()> {
34-
Ok(transport::PluginResponse {
35-
status: transport::ReplStatus::Success,
36-
stdout: Some(format!("{}", payload)),
37-
stderr: None,
38-
})
37+
match run_inner(payload) {
38+
Ok(content) => Ok(transport::PluginResponse {
39+
status: transport::ReplStatus::Success,
40+
stdout: Some(format!("{}", content)),
41+
stderr: None,
42+
}),
43+
Err(e) => {
44+
// e.kind() - verify if the error is a permission error
45+
return Ok(transport::PluginResponse {
46+
status: transport::ReplStatus::Error,
47+
stdout: None,
48+
stderr: Some(format!("{}", e)),
49+
});
50+
}
51+
}
52+
}
53+
}
54+
55+
fn run_inner(payload: String) -> Result<String, String> {
56+
let is_append = payload.starts_with("-a") || payload.starts_with("--append");
57+
let filepath = if is_append {
58+
let Some((_, filepath)) = payload.split_once(" ") else {
59+
return Err("Invalid arguments. Usage: tee <file> or tee -a <file>".to_string());
60+
};
61+
filepath.to_string()
62+
} else {
63+
payload
64+
};
65+
66+
let content = host_state_plugin::get_repl_var("0").unwrap_or("".to_string());
67+
let content_as_bytes = content.as_bytes();
68+
69+
if !is_append {
70+
let mut file = std::fs::File::create(&filepath)
71+
.map_err(|e| format!("Failed to create file '{}': {}", filepath, e))?;
72+
file.write_all(content_as_bytes)
73+
.map_err(|e| format!("Failed to write to file '{}': {}", filepath, e))?;
74+
return Ok(content);
75+
} else {
76+
let mut file = std::fs::File::options()
77+
.append(true)
78+
.open(&filepath)
79+
.map_err(|e| format!("Failed to open file in append mode '{}': {}", filepath, e))?;
80+
// Add a newline before the content in append mode
81+
file.write_all(b"\n")
82+
.map_err(|e| format!("Failed to write newline to file '{}': {}", filepath, e))?;
83+
file.write_all(content_as_bytes)
84+
.map_err(|e| format!("Failed to write to file '{}': {}", filepath, e))?;
85+
return Ok(content);
3986
}
4087
}
4188

0 commit comments

Comments
 (0)