1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
// src/output/writer.rs
use crate::config::{Config, OutputDestination};
use anyhow::{anyhow, Result};
use std::fs::File;
use std::io::{self, BufWriter, Write};
use std::sync::{Arc, Mutex};
/// Represents the setup output writer, potentially including a buffer for clipboard.
pub struct OutputWriterSetup {
pub writer: Box<dyn Write + Send>,
/// Holds the buffer only if the destination is Clipboard.
pub clipboard_buffer: Option<Arc<Mutex<Vec<u8>>>>,
}
/// Sets up the output writer based on the configuration.
/// Returns a struct containing the boxed Write trait object and an optional buffer handle.
pub fn setup_output_writer(config: &Config) -> Result<OutputWriterSetup> {
let mut clipboard_buffer = None;
let writer: Box<dyn Write + Send> = match &config.output_destination {
OutputDestination::Stdout => Box::new(io::stdout()),
OutputDestination::File(path) => {
let file =
File::create(path).map_err(|e| crate::errors::io_error_with_path(e, path))?;
Box::new(BufWriter::new(file)) // Use BufWriter for file I/O
}
OutputDestination::Clipboard => {
// For clipboard, write to an in-memory buffer first.
let buffer = Arc::new(Mutex::new(Vec::<u8>::new()));
clipboard_buffer = Some(buffer.clone()); // Store handle to the buffer
Box::new(ArcMutexVecWriter(buffer)) // Wrap Arc<Mutex<Vec<u8>>>
}
};
Ok(OutputWriterSetup {
writer,
clipboard_buffer,
})
}
/// Finalizes output, specifically handling the clipboard case.
/// If the destination was Clipboard, this function copies the buffer content.
pub fn finalize_output(
mut writer: Box<dyn Write + Send>, // Take ownership to ensure drop/flush
clipboard_buffer: Option<Arc<Mutex<Vec<u8>>>>,
config: &Config,
) -> Result<()> {
// Ensure final flush before potential clipboard op or drop
writer.flush()?;
if config.output_destination == OutputDestination::Clipboard {
if let Some(buffer_arc) = clipboard_buffer {
let buffer = buffer_arc
.lock()
.map_err(|e| anyhow!("Failed to lock clipboard buffer mutex: {}", e))?;
let content = String::from_utf8(buffer.clone())?; // Clone buffer data
copy_to_clipboard(&content)?;
// Avoid printing to stderr in library code, let the caller handle feedback
// eprintln!("Output copied to clipboard."); // Provide feedback
} else {
// This indicates an internal logic error in setup/finalize pairing
return Err(anyhow!(
"Clipboard destination specified, but no buffer found during finalization."
));
}
}
// For Stdout or File, flushing happened above, and drop handles closing.
Ok(())
}
#[cfg(feature = "clipboard")]
fn copy_to_clipboard(content: &str) -> Result<()> {
use crate::errors::AppError; // Import AppError only when needed
use arboard::Clipboard;
let mut clipboard = Clipboard::new().map_err(|e| AppError::ClipboardError(e.to_string()))?;
clipboard
.set_text(content)
.map_err(|e| AppError::ClipboardError(e.to_string()))?;
Ok(())
}
#[cfg(not(feature = "clipboard"))]
fn copy_to_clipboard(_content: &str) -> Result<()> {
// This should ideally be caught earlier by clap's `requires` or config validation
Err(anyhow!(
"Clipboard feature is not enabled, cannot use --paste."
))
}
// --- Wrapper struct for Arc<Mutex<Vec<u8>>> to implement Write ---
// This is necessary because we cannot implement a foreign trait (Write)
// directly on a foreign type (Arc<Mutex<Vec<u8>>>).
#[derive(Debug, Clone)]
struct ArcMutexVecWriter(Arc<Mutex<Vec<u8>>>);
impl Write for ArcMutexVecWriter {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
// Attempt to lock the mutex. If poisoned, return an error.
let mut buffer = self
.0 // Access the inner Arc<Mutex<Vec<u8>>>
.lock()
.map_err(|e| io::Error::new(io::ErrorKind::Other, format!("Mutex poisoned: {}", e)))?;
// Write data to the underlying Vec<u8>
buffer.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
// Attempt to lock the mutex. If poisoned, return an error.
let mut buffer = self
.0 // Access the inner Arc<Mutex<Vec<u8>>>
.lock()
.map_err(|e| io::Error::new(io::ErrorKind::Other, format!("Mutex poisoned: {}", e)))?;
// Flush the underlying Vec<u8> (no-op, but required by trait)
buffer.flush()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::output::tests::create_mock_config; // Use shared helper
// Removed unused Read, Seek, SeekFrom
use tempfile::NamedTempFile;
#[test]
fn test_write_impl_for_arc_mutex_vec() -> io::Result<()> {
let buffer_arc: Arc<Mutex<Vec<u8>>> = Arc::new(Mutex::new(Vec::new()));
let mut writer = ArcMutexVecWriter(buffer_arc.clone()); // Use wrapper as writer
write!(writer, "Hello")?;
writer.write_all(b", ")?;
write!(writer, "World!")?;
writer.flush()?; // Should be a no-op for Vec but test it doesn't fail
// Lock the original Arc to check the contents
let buffer = buffer_arc.lock().unwrap();
assert_eq!(*buffer, b"Hello, World!");
Ok(())
}
#[test]
fn test_setup_output_writer_stdout() {
// Simple check: Does it return *something* without panicking for stdout?
// Testing the actual type is brittle.
let config = create_mock_config(false, false, false, false); // Destination is stdout
let setup_result = setup_output_writer(&config);
assert!(setup_result.is_ok());
let setup = setup_result.unwrap();
assert!(setup.clipboard_buffer.is_none());
// Cannot easily assert the type of writer is stdout without downcasting, which is complex.
}
#[test]
fn test_setup_output_writer_file() -> Result<()> {
let temp_file = NamedTempFile::new()?;
let path = temp_file.path().to_path_buf();
let mut config = create_mock_config(false, false, false, false);
config.output_destination = OutputDestination::File(path.clone());
let setup_result = setup_output_writer(&config);
assert!(setup_result.is_ok());
let mut setup = setup_result.unwrap();
assert!(setup.clipboard_buffer.is_none());
// Test writing to the file via the writer
write!(setup.writer, "Test content")?;
setup.writer.flush()?; // Important for BufWriter
// Drop the writer to close the file before reading
drop(setup.writer);
// Re-open and read the file to verify content
let content = std::fs::read_to_string(&path)?;
assert_eq!(content, "Test content");
Ok(())
}
#[test]
fn test_setup_output_writer_clipboard() {
// Test clipboard destination setup
let mut config = create_mock_config(false, false, false, false);
config.output_destination = OutputDestination::Clipboard;
let setup_result = setup_output_writer(&config);
assert!(setup_result.is_ok());
let setup = setup_result.unwrap();
assert!(setup.clipboard_buffer.is_some()); // Should have a buffer
// Check if the writer is the buffer itself by trying to write to it
let mut writer = setup.writer;
write!(writer, "Clipboard test").unwrap();
writer.flush().unwrap();
// Check the buffer content directly
let buffer_arc = setup.clipboard_buffer.unwrap();
let buffer = buffer_arc.lock().unwrap();
assert_eq!(*buffer, b"Clipboard test");
}
#[test]
fn test_finalize_output_stdout() -> Result<()> {
// Finalize should be a no-op for stdout
let config = create_mock_config(false, false, false, false); // stdout
let writer = Box::new(io::sink()); // Use sink to avoid printing during test
let buffer = None;
finalize_output(writer, buffer, &config)?; // Should just succeed
Ok(())
}
#[test]
fn test_finalize_output_file() -> Result<()> {
// Finalize should be a no-op for file (drop handles closing)
let temp_file = NamedTempFile::new()?;
let path = temp_file.path().to_path_buf();
let file = File::create(&path)?;
let writer = Box::new(BufWriter::new(file));
let mut config = create_mock_config(false, false, false, false);
config.output_destination = OutputDestination::File(path);
let buffer = None;
finalize_output(writer, buffer, &config)?; // Should just succeed
Ok(())
}
// Note: Testing finalize_output for Clipboard requires mocking `copy_to_clipboard`
// or enabling the "clipboard" feature and potentially running in a specific environment.
// The current test only checks if it attempts to access the buffer.
#[test]
fn test_finalize_output_clipboard_buffer_access() {
let mut config = create_mock_config(false, false, false, false);
config.output_destination = OutputDestination::Clipboard;
let buffer_arc: Arc<Mutex<Vec<u8>>> = Arc::new(Mutex::new(b"clipboard data".to_vec()));
let writer = Box::new(ArcMutexVecWriter(buffer_arc.clone())); // Writer is the buffer wrapper
let clipboard_buffer = Some(buffer_arc.clone());
// This will call copy_to_clipboard internally, which might fail if feature not enabled,
// or succeed (or fail depending on env) if enabled. We just check if it runs without panic.
let result = finalize_output(writer, clipboard_buffer, &config);
// If clipboard feature IS enabled, this might fail if clipboard context unavailable.
// If clipboard feature IS NOT enabled, this *should* fail with the specific anyhow error.
#[cfg(not(feature = "clipboard"))]
{
assert!(result.is_err());
assert!(result
.unwrap_err()
.to_string()
.contains("Clipboard feature is not enabled"));
}
#[cfg(feature = "clipboard")]
{
use crate::errors::AppError; // Need AppError for matching
// In a test environment without a clipboard service, arboard might return an error.
// We accept Ok or a specific ClipboardError here.
if let Err(e) = result {
assert!(e
.downcast_ref::<AppError>()
.map_or(false, |ae| matches!(ae, AppError::ClipboardError(_))));
}
}
}
#[test]
fn test_finalize_output_clipboard_missing_buffer() {
// Test the internal error case where buffer is somehow None
let mut config = create_mock_config(false, false, false, false);
config.output_destination = OutputDestination::Clipboard;
let writer = Box::new(io::sink()); // Not a buffer
let clipboard_buffer = None; // Missing buffer
let result = finalize_output(writer, clipboard_buffer, &config);
assert!(result.is_err());
assert!(result
.unwrap_err()
.to_string()
.contains("no buffer found during finalization"));
}
}