|
1 | 1 | #[allow(warnings)] |
2 | 2 | mod bindings; |
3 | 3 |
|
| 4 | +use std::io::Write; |
| 5 | + |
4 | 6 | use crate::bindings::exports::repl::api::plugin::Guest; |
| 7 | +use crate::bindings::repl::api::host_state_plugin; |
5 | 8 | use crate::bindings::repl::api::transport; |
6 | 9 |
|
7 | 10 | struct Component; |
@@ -31,11 +34,55 @@ DESCRIPTION |
31 | 34 | } |
32 | 35 |
|
33 | 36 | 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); |
39 | 86 | } |
40 | 87 | } |
41 | 88 |
|
|
0 commit comments