1use nu_engine::{command_prelude::*, get_eval_block_with_early_return};
2#[cfg(feature = "os")]
3use nu_protocol::process::ChildPipe;
4#[cfg(test)]
5use nu_protocol::shell_error;
6use nu_protocol::{
7 ByteStream, ByteStreamSource, OutDest, PipelineMetadata, Signals,
8 byte_stream::copy_with_signals, engine::Closure, report_shell_error, shell_error::io::IoError,
9};
10use std::{
11 io::{self, Read, Write},
12 sync::{
13 Arc,
14 mpsc::{self, Sender},
15 },
16 thread::{self, JoinHandle},
17};
18
19#[derive(Clone)]
20pub struct Tee;
21
22impl Command for Tee {
23 fn name(&self) -> &str {
24 "tee"
25 }
26
27 fn description(&self) -> &str {
28 "Copy a stream to another command in parallel."
29 }
30
31 fn extra_description(&self) -> &str {
32 "This is useful for doing something else with a stream while still continuing to
33use it in your pipeline."
34 }
35
36 fn signature(&self) -> Signature {
37 Signature::build("tee")
38 .input_output_type(Type::Any, Type::Any)
39 .switch(
40 "stderr",
41 "For external commands: copy the standard error stream instead.",
42 Some('e'),
43 )
44 .required(
45 "closure",
46 SyntaxShape::Closure(None),
47 "The other command to send the stream to.",
48 )
49 .category(Category::Filters)
50 }
51
52 fn examples(&self) -> Vec<Example<'_>> {
53 vec![
54 Example {
55 example: "http get http://example.org/ | tee { save example.html }",
56 description: "Save a webpage to a file while also printing it.",
57 result: None,
58 },
59 Example {
60 example: "nu -c 'print -e error; print ok' | tee --stderr { save error.log } | complete",
61 description: "Save error messages from an external command to a file without redirecting them.",
62 result: None,
63 },
64 Example {
65 example: "1..100 | tee { each { print } } | math sum | wrap sum",
66 description: "Print numbers and their sum.",
67 result: None,
68 },
69 Example {
70 example: "10000 | tee { 1..$in | print } | $in * 5",
71 description: "Do something with a value on another thread, while also passing through the value.",
72 result: Some(Value::test_int(50000)),
73 },
74 ]
75 }
76
77 fn run(
78 &self,
79 engine_state: &EngineState,
80 stack: &mut Stack,
81 call: &Call,
82 input: PipelineData,
83 ) -> Result<PipelineData, ShellError> {
84 let head = call.head;
85 let from_io_error = IoError::factory(head, None);
86 let use_stderr = call.has_flag(engine_state, stack, "stderr")?;
87
88 let closure: Spanned<Closure> = call.req(engine_state, stack, 0)?;
89 let closure_span = closure.span;
90 let closure = closure.item;
91
92 let engine_state_arc = Arc::new(engine_state.clone());
93
94 let mut eval_block = {
95 let closure_engine_state = engine_state_arc.clone();
96 let mut closure_stack = stack
97 .captures_to_stack_preserve_out_dest(closure.captures)
98 .reset_pipes();
99 let eval_block_with_early_return = get_eval_block_with_early_return(engine_state);
100
101 move |input| {
102 let result = eval_block_with_early_return(
103 &closure_engine_state,
104 &mut closure_stack,
105 closure_engine_state.get_block(closure.block_id),
106 input,
107 )
108 .map(|p| p.body);
109 result.and_then(|data| data.drain().map(|_| ()))
111 }
112 };
113
114 let span = input.span().unwrap_or(head);
118 let input = input.into_stream_or_original(engine_state);
119
120 if let PipelineData::ByteStream(stream, metadata) = input {
121 let type_ = stream.type_();
122
123 let info = StreamInfo {
124 span,
125 signals: engine_state.signals().clone(),
126 type_,
127 metadata: metadata.clone(),
128 };
129
130 match stream.into_source() {
131 ByteStreamSource::Read(read) => {
132 if use_stderr {
133 return stderr_misuse(span, head);
134 }
135
136 let tee_thread = spawn_tee(info, eval_block)?;
137 let tee = IoTee::new(read, tee_thread);
138
139 Ok(PipelineData::byte_stream(
140 ByteStream::read(tee, span, engine_state.signals().clone(), type_),
141 metadata,
142 ))
143 }
144 ByteStreamSource::File(file) => {
145 if use_stderr {
146 return stderr_misuse(span, head);
147 }
148
149 let tee_thread = spawn_tee(info, eval_block)?;
150 let tee = IoTee::new(file, tee_thread);
151
152 Ok(PipelineData::byte_stream(
153 ByteStream::read(tee, span, engine_state.signals().clone(), type_),
154 metadata,
155 ))
156 }
157 #[cfg(feature = "os")]
158 ByteStreamSource::Child(mut child) => {
159 let stderr_thread = if use_stderr {
160 let stderr_thread = if let Some(stderr) = child.stderr.take() {
161 let tee_thread = spawn_tee(info.clone(), eval_block)?;
162 let tee = IoTee::new(stderr, tee_thread);
163 match stack.stderr() {
164 OutDest::Pipe | OutDest::PipeSeparate | OutDest::Value => {
165 child.stderr = Some(ChildPipe::Tee(Box::new(tee)));
166 Ok(None)
167 }
168 OutDest::Null => copy_on_thread(tee, io::sink(), &info).map(Some),
169 OutDest::Print | OutDest::Inherit => {
170 copy_on_thread(tee, io::stderr(), &info).map(Some)
171 }
172 OutDest::File(file) => {
173 copy_on_thread(tee, file.clone(), &info).map(Some)
174 }
175 }?
176 } else {
177 None
178 };
179
180 if let Some(stdout) = child.stdout.take() {
181 match stack.stdout() {
182 OutDest::Pipe | OutDest::PipeSeparate | OutDest::Value => {
183 child.stdout = Some(stdout);
184 Ok(())
185 }
186 OutDest::Null => copy_pipe(stdout, io::sink(), &info),
187 OutDest::Print | OutDest::Inherit => {
188 copy_pipe(stdout, io::stdout(), &info)
189 }
190 OutDest::File(file) => copy_pipe(stdout, file.as_ref(), &info),
191 }?;
192 }
193
194 stderr_thread
195 } else {
196 let stderr_thread = if let Some(stderr) = child.stderr.take() {
197 let info = info.clone();
198 match stack.stderr() {
199 OutDest::Pipe | OutDest::PipeSeparate | OutDest::Value => {
200 child.stderr = Some(stderr);
201 Ok(None)
202 }
203 OutDest::Null => {
204 copy_pipe_on_thread(stderr, io::sink(), &info).map(Some)
205 }
206 OutDest::Print | OutDest::Inherit => {
207 copy_pipe_on_thread(stderr, io::stderr(), &info).map(Some)
208 }
209 OutDest::File(file) => {
210 copy_pipe_on_thread(stderr, file.clone(), &info).map(Some)
211 }
212 }?
213 } else {
214 None
215 };
216
217 if let Some(stdout) = child.stdout.take() {
218 let tee_thread = spawn_tee(info.clone(), eval_block)?;
219 let tee = IoTee::new(stdout, tee_thread);
220 match stack.stdout() {
221 OutDest::Pipe | OutDest::PipeSeparate | OutDest::Value => {
222 child.stdout = Some(ChildPipe::Tee(Box::new(tee)));
223 Ok(())
224 }
225 OutDest::Null => copy(tee, io::sink(), &info),
226 OutDest::Print | OutDest::Inherit => copy(tee, io::stdout(), &info),
227 OutDest::File(file) => copy(tee, file.as_ref(), &info),
228 }?;
229 }
230
231 stderr_thread
232 };
233
234 if child.stdout.is_some() || child.stderr.is_some() {
235 Ok(PipelineData::byte_stream(
236 ByteStream::child(*child, span),
237 metadata,
238 ))
239 } else {
240 if let Some(thread) = stderr_thread {
241 thread.join().unwrap_or_else(|_| Err(panic_error()))?;
242 }
243 child.wait()?;
244 Ok(PipelineData::empty())
245 }
246 }
247 }
248 } else {
249 if use_stderr {
250 return stderr_misuse(input.span().unwrap_or(head), head);
251 }
252
253 let metadata = input.metadata();
254 let metadata_clone = metadata.clone();
255
256 if let PipelineData::ListStream(..) = input {
257 let signals = engine_state.signals().clone();
261
262 Ok(tee(input.into_iter(), move |rx| {
263 let input = rx.into_pipeline_data_with_metadata(span, signals, metadata_clone);
264 eval_block(input)
265 })
266 .map_err(&from_io_error)?
267 .map(move |result| result.unwrap_or_else(|err| Value::error(err, closure_span)))
268 .into_pipeline_data_with_metadata(
269 span,
270 engine_state.signals().clone(),
271 metadata,
272 ))
273 } else {
274 let value = input.into_value(span)?;
277 let value_clone = value.clone();
278 tee_once(stack.clone(), engine_state_arc, move || {
279 eval_block(value_clone.into_pipeline_data_with_metadata(metadata_clone))
280 })
281 .map_err(&from_io_error)?;
282 Ok(value.into_pipeline_data_with_metadata(metadata))
283 }
284 }
285 }
286
287 fn pipe_redirection(&self) -> (Option<OutDest>, Option<OutDest>) {
288 (Some(OutDest::PipeSeparate), Some(OutDest::PipeSeparate))
289 }
290}
291
292fn panic_error() -> ShellError {
293 ShellError::NushellFailed {
294 msg: "A panic occurred on a thread spawned by `tee`".into(),
295 }
296}
297
298fn tee<T, I: Iterator<Item = T>>(
303 input: I,
304 with_cloned_stream: impl FnOnce(mpsc::Receiver<T>) -> Result<(), ShellError> + Send + 'static,
305) -> Result<TeeIterator<I>, std::io::Error>
306where
307 T: Clone + Send + 'static,
308{
309 let (tx, rx) = mpsc::channel();
311
312 Ok(TeeIterator {
313 thread: Some(
314 thread::Builder::new()
315 .name("tee".into())
316 .spawn(move || with_cloned_stream(rx))?,
317 ),
318 iter: input.into_iter(),
319 tx: Some(tx),
320 })
321}
322
323struct TeeIterator<I: Iterator> {
324 thread: Option<JoinHandle<Result<(), ShellError>>>,
325 iter: I,
326 tx: Option<Sender<I::Item>>,
327}
328
329impl<I> Iterator for TeeIterator<I>
330where
331 I: Iterator,
332 I::Item: Clone,
333{
334 type Item = Result<I::Item, ShellError>;
335
336 fn next(&mut self) -> Option<Self::Item> {
337 if self.thread.as_ref().is_some_and(|t| t.is_finished()) {
338 let result = self
340 .thread
341 .take()
342 .expect("thread was taken early")
343 .join()
344 .unwrap_or_else(|_| Err(panic_error()));
345 if let Err(err) = result {
346 return Some(Err(err));
348 }
349 }
350
351 if let Some(value) = self.iter.next() {
353 let _ = self.tx.as_ref().map(|tx| tx.send(value.clone()));
355 Some(Ok(value))
356 } else {
357 drop(self.tx.take());
359 self.thread.take().and_then(|t| {
361 t.join()
362 .unwrap_or_else(|_| Err(panic_error()))
363 .err()
364 .map(Err)
365 })
366 }
367 }
368}
369
370impl<I: Iterator> Drop for TeeIterator<I> {
371 fn drop(&mut self) {
372 if let Some(tx) = &mut self.tx {
376 for value in &mut self.iter {
377 if tx.send(value).is_err() {
379 break;
380 }
381 }
382 }
383 }
384}
385
386fn tee_once(
388 stack: Stack,
389 engine_state: Arc<EngineState>,
390 on_thread: impl FnOnce() -> Result<(), ShellError> + Send + 'static,
391) -> Result<JoinHandle<()>, std::io::Error> {
392 thread::Builder::new().name("tee".into()).spawn(move || {
393 if let Err(err) = on_thread() {
394 report_shell_error(Some(&stack), &engine_state, &err);
395 }
396 })
397}
398
399fn stderr_misuse<T>(span: Span, head: Span) -> Result<T, ShellError> {
400 Err(ShellError::UnsupportedInput {
401 msg: "--stderr can only be used on external commands".into(),
402 input: "the input to `tee` is not an external command".into(),
403 msg_span: head,
404 input_span: span,
405 })
406}
407
408struct IoTee<R: Read> {
409 reader: R,
410 sender: Option<Sender<Vec<u8>>>,
411 thread: Option<JoinHandle<Result<(), ShellError>>>,
412}
413
414impl<R: Read> IoTee<R> {
415 fn new(reader: R, tee: TeeThread) -> Self {
416 Self {
417 reader,
418 sender: Some(tee.sender),
419 thread: Some(tee.thread),
420 }
421 }
422}
423
424impl<R: Read> Read for IoTee<R> {
425 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
426 if let Some(thread) = self.thread.take() {
427 if thread.is_finished() {
428 if let Err(err) = thread.join().unwrap_or_else(|_| Err(panic_error())) {
429 return Err(io::Error::other(err));
430 }
431 } else {
432 self.thread = Some(thread)
433 }
434 }
435 let len = self.reader.read(buf)?;
436 if len == 0 {
437 self.sender = None;
438 if let Some(thread) = self.thread.take()
439 && let Err(err) = thread.join().unwrap_or_else(|_| Err(panic_error()))
440 {
441 return Err(io::Error::other(err));
442 }
443 } else if let Some(sender) = self.sender.as_mut()
444 && sender.send(buf[..len].to_vec()).is_err()
445 {
446 self.sender = None;
447 }
448 Ok(len)
449 }
450}
451
452struct TeeThread {
453 sender: Sender<Vec<u8>>,
454 thread: JoinHandle<Result<(), ShellError>>,
455}
456
457fn spawn_tee(
458 info: StreamInfo,
459 mut eval_block: impl FnMut(PipelineData) -> Result<(), ShellError> + Send + 'static,
460) -> Result<TeeThread, ShellError> {
461 let (sender, receiver) = mpsc::channel();
462
463 let thread = thread::Builder::new()
464 .name("tee".into())
465 .spawn(move || {
466 let stream = ByteStream::from_iter(
468 receiver.into_iter(),
469 info.span,
470 Signals::empty(),
471 info.type_,
472 );
473 eval_block(PipelineData::byte_stream(stream, info.metadata))
474 })
475 .map_err(|err| {
476 IoError::new_with_additional_context(err, info.span, None, "Could not spawn tee")
477 })?;
478
479 Ok(TeeThread { sender, thread })
480}
481
482#[derive(Clone)]
483struct StreamInfo {
484 span: Span,
485 signals: Signals,
486 type_: ByteStreamType,
487 metadata: Option<PipelineMetadata>,
488}
489
490fn copy(src: impl Read, dest: impl Write, info: &StreamInfo) -> Result<(), ShellError> {
491 copy_with_signals(src, dest, info.span, &info.signals)?;
492 Ok(())
493}
494
495#[cfg(feature = "os")]
496fn copy_pipe(pipe: ChildPipe, dest: impl Write, info: &StreamInfo) -> Result<(), ShellError> {
497 match pipe {
498 ChildPipe::Pipe(pipe) => copy(pipe, dest, info),
499 ChildPipe::Tee(tee) => copy(tee, dest, info),
500 }
501}
502
503fn copy_on_thread(
504 src: impl Read + Send + 'static,
505 dest: impl Write + Send + 'static,
506 info: &StreamInfo,
507) -> Result<JoinHandle<Result<(), ShellError>>, ShellError> {
508 let span = info.span;
509 let signals = info.signals.clone();
510 thread::Builder::new()
511 .name("stderr copier".into())
512 .spawn(move || {
513 copy_with_signals(src, dest, span, &signals)?;
514 Ok(())
515 })
516 .map_err(|err| {
517 IoError::new_with_additional_context(err, span, None, "Could not spawn stderr copier")
518 .into()
519 })
520}
521
522#[cfg(feature = "os")]
523fn copy_pipe_on_thread(
524 pipe: ChildPipe,
525 dest: impl Write + Send + 'static,
526 info: &StreamInfo,
527) -> Result<JoinHandle<Result<(), ShellError>>, ShellError> {
528 match pipe {
529 ChildPipe::Pipe(pipe) => copy_on_thread(pipe, dest, info),
530 ChildPipe::Tee(tee) => copy_on_thread(tee, dest, info),
531 }
532}
533
534#[test]
535fn tee_copies_values_to_other_thread_and_passes_them_through() {
536 let (tx, rx) = mpsc::channel();
537
538 let expected_values = vec![1, 2, 3, 4];
539
540 let my_result = tee(expected_values.clone().into_iter(), move |rx| {
541 for val in rx {
542 let _ = tx.send(val);
543 }
544 Ok(())
545 })
546 .expect("io error")
547 .collect::<Result<Vec<i32>, ShellError>>()
548 .expect("should not produce error");
549
550 assert_eq!(expected_values, my_result);
551
552 let other_threads_result = rx.into_iter().collect::<Vec<_>>();
553
554 assert_eq!(expected_values, other_threads_result);
555}
556
557#[test]
558fn tee_forwards_errors_back_immediately() {
559 use std::time::Duration;
560 let slow_input = (0..100).inspect(|_| std::thread::sleep(Duration::from_millis(1)));
561 let iter = tee(slow_input, |_| {
562 Err(ShellError::Io(IoError::new_with_additional_context(
563 shell_error::io::ErrorKind::from_std(std::io::ErrorKind::Other),
564 Span::test_data(),
565 None,
566 "test",
567 )))
568 })
569 .expect("io error");
570 for result in iter {
571 if let Ok(val) = result {
572 assert!(val < 99, "the error did not come early enough");
574 } else {
575 return;
577 }
578 }
579 panic!("never received the error");
580}
581
582#[test]
583fn tee_waits_for_the_other_thread() {
584 use std::sync::{
585 Arc,
586 atomic::{AtomicBool, Ordering},
587 };
588 use std::time::Duration;
589 let waited = Arc::new(AtomicBool::new(false));
590 let waited_clone = waited.clone();
591 let iter = tee(0..100, move |_| {
592 std::thread::sleep(Duration::from_millis(10));
593 waited_clone.store(true, Ordering::Relaxed);
594 Err(ShellError::Io(IoError::new_with_additional_context(
595 shell_error::io::ErrorKind::from_std(std::io::ErrorKind::Other),
596 Span::test_data(),
597 None,
598 "test",
599 )))
600 })
601 .expect("io error");
602 let last = iter.last();
603 assert!(waited.load(Ordering::Relaxed), "failed to wait");
604 assert!(
605 last.is_some_and(|res| res.is_err()),
606 "failed to return error from wait"
607 );
608}
609
610#[test]
612fn tee_output_is_ignored_but_other_thread_get_values() {
613 let (tx, rx) = mpsc::channel();
614
615 let input = 0u32..100u32;
616 let expected_values: Vec<_> = input.clone().collect();
617
618 let my_result = tee(input, move |rx| {
619 for val in rx {
620 let _ = tx.send(val);
621 }
622 Ok(())
623 })
624 .expect("io error")
625 .take(2)
627 .collect::<Result<Vec<_>, ShellError>>()
628 .expect("should not produce error");
629
630 assert_eq!(expected_values[0..my_result.len()], my_result);
632
633 let other_threads_result = rx.into_iter().collect::<Vec<_>>();
634
635 assert_eq!(expected_values, other_threads_result);
638}
639
640#[test]
641fn tee_other_thread_ignore_values_but_output_all_others() {
642 let (tx, rx) = mpsc::channel();
643
644 let input = 0u32..100u32;
645 let expected_values: Vec<_> = input.clone().collect();
646
647 let my_result = tee(input, move |rx| {
648 for val in rx {
649 let _ = tx.send(val);
650 }
651 Ok(())
652 })
653 .expect("io error")
654 .collect::<Result<Vec<_>, ShellError>>()
655 .expect("should not produce error");
656
657 assert_eq!(expected_values, my_result);
659
660 let other_threads_result = rx.into_iter().take(2).collect::<Vec<_>>();
662 assert_eq!(expected_values[0..2], other_threads_result);
663}