cargo-plugin-utils 0.0.10

Shared utilities for cargo plugins (logger, subprocess handling, common functions)
Documentation
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
//! Logger for handling output with cargo-style progress and status messages.

use std::io::Write;

use anyhow::Context;
use carlog::Status;
use console;
use indicatif::{
    ProgressBar,
    ProgressDrawTarget,
    ProgressStyle,
};
use portable_pty::{
    CommandBuilder,
    PtySize,
    native_pty_system,
};

/// Logger for handling output with cargo-style progress and status messages.
///
/// All progress and status messages go to stderr (matching cargo's behavior).
/// This allows command output (badges, changelog, etc.) to be piped cleanly
/// through stdout while progress messages appear on the console.
pub struct Logger {
    progress_bar: Option<ProgressBar>,
    line_count: usize,
}

impl Logger {
    /// Create a new logger.
    pub fn new() -> Self {
        Self {
            progress_bar: None,
            line_count: 0,
        }
    }

    /// Show a progress bar (ephemeral, disappears on finish).
    ///
    /// Use this for operations with known progress.
    /// Always uses stderr (matching cargo's behavior).
    #[allow(dead_code)] // Will be used for long-running operations
    pub fn progress(&mut self, message: &str) {
        let pb = ProgressBar::new_spinner();
        pb.set_draw_target(ProgressDrawTarget::stderr());
        pb.set_style(
            ProgressStyle::default_spinner()
                .template("{spinner:.green} {msg}")
                .unwrap(),
        );
        pb.set_message(message.to_string());
        pb.enable_steady_tick(std::time::Duration::from_millis(100));

        self.progress_bar = Some(pb);
    }

    /// Update the progress bar message.
    #[allow(dead_code)] // Will be used for long-running operations
    pub fn set_progress_message(&self, message: &str) {
        if let Some(pb) = &self.progress_bar {
            pb.set_message(message.to_string());
        }
    }

    /// Print a status message in cargo's style: "   Building crate-name".
    ///
    /// Uses cyan color for the action word (ephemeral operations).
    /// This creates an ephemeral message that will be cleared on finish().
    /// Always goes to stderr (matching cargo's behavior).
    pub fn status(&mut self, action: &str, target: &str) {
        // Clear previous status (replaces it with new one)
        if let Some(pb) = self.progress_bar.take() {
            pb.finish_and_clear();
        }

        // Format status message with cyan color (like cargo's "Building")
        use console::style;
        let formatted_message = format!("{:>12} {}", style(action).cyan().bold(), target);

        // Create a progress bar that shows the message ephemerally
        let pb = ProgressBar::new_spinner();
        pb.set_draw_target(ProgressDrawTarget::stderr());
        pb.set_style(ProgressStyle::default_spinner().template("{msg}").unwrap());
        pb.set_message(formatted_message);

        self.progress_bar = Some(pb);
        self.line_count = 1;
    }

    /// Print a permanent status message in cargo's style: "   Compiling
    /// crate-name".
    ///
    /// Uses green color for the action word (permanent operations).
    /// This message will NOT be cleared - use for operations that spawn
    /// subprocesses. Always goes to stderr (matching cargo's behavior).
    #[allow(dead_code)] // Will be used for subprocess-heavy operations
    pub fn status_permanent(&self, action: &str, target: &str) {
        let status = Status::new()
            .bold()
            .justify()
            .color(carlog::CargoColor::Green)
            .status(action);

        let formatted_target = format!(" {}", target);

        // Print permanent message to stderr (suspend if progress bar active)
        if let Some(pb) = &self.progress_bar {
            pb.suspend(|| {
                let _ = status.print_stderr(&formatted_target);
            });
        } else {
            let _ = status.print_stderr(&formatted_target);
        }
    }

    /// Print a permanent message (will be kept in output).
    ///
    /// Always goes to stderr (matching cargo's behavior).
    #[allow(dead_code)] // May be used by other commands
    pub fn print_message(&self, msg: &str) {
        if let Some(pb) = &self.progress_bar {
            pb.suspend(|| {
                eprintln!("{}", msg);
            });
        } else {
            eprintln!("{}", msg);
        }
    }

    /// Print an info message (cyan colored).
    ///
    /// Info messages are permanent (not cleared).
    /// Always goes to stderr (matching cargo's behavior).
    #[allow(dead_code)] // May be used by other commands
    pub fn info(&self, action: &str, target: &str) {
        let status = Status::new()
            .bold()
            .justify()
            .color(carlog::CargoColor::Cyan)
            .status(action);

        let formatted_target = format!(" {}", target);

        // Suspend progress bar to print permanent message to stderr
        if let Some(pb) = &self.progress_bar {
            pb.suspend(|| {
                let _ = status.print_stderr(&formatted_target);
            });
        } else {
            let _ = status.print_stderr(&formatted_target);
        }
    }

    /// Print a warning message (yellow colored).
    ///
    /// Warning messages are permanent (not cleared).
    /// Always goes to stderr (matching cargo's behavior).
    pub fn warning(&self, action: &str, target: &str) {
        let status = Status::new()
            .bold()
            .justify()
            .color(carlog::CargoColor::Yellow)
            .status(action);

        let formatted_target = format!(" {}", target);

        // Suspend progress bar to print permanent message to stderr
        if let Some(pb) = &self.progress_bar {
            pb.suspend(|| {
                let _ = status.print_stderr(&formatted_target);
            });
        } else {
            let _ = status.print_stderr(&formatted_target);
        }
    }

    /// Print an error message (red colored).
    ///
    /// Error messages are permanent (not cleared).
    /// Always goes to stderr (matching cargo's behavior).
    #[allow(dead_code)] // May be used by other commands
    pub fn error(&self, action: &str, target: &str) {
        let status = Status::new()
            .bold()
            .justify()
            .color(carlog::CargoColor::Red)
            .status(action);

        let formatted_target = format!(" {}", target);

        // Suspend progress bar to print permanent message to stderr
        if let Some(pb) = &self.progress_bar {
            pb.suspend(|| {
                let _ = status.print_stderr(&formatted_target);
            });
        } else {
            let _ = status.print_stderr(&formatted_target);
        }
    }

    /// Clear the current status message immediately.
    ///
    /// Useful before subprocess operations that might write to stderr.
    pub fn clear_status(&mut self) {
        if let Some(pb) = self.progress_bar.take() {
            pb.finish_and_clear();
            self.line_count = 0;
        }
    }

    /// Temporarily suspend the status message (for subprocess output).
    ///
    /// Call this before spawning subprocesses that write to stderr to avoid
    /// mixing their output with our status line.
    pub fn suspend<F, R>(&mut self, f: F) -> R
    where
        F: FnOnce() -> R,
    {
        if let Some(pb) = &self.progress_bar {
            pb.suspend(f)
        } else {
            f()
        }
    }

    /// Finish logging and clear ephemeral status messages.
    pub fn finish(&mut self) {
        if let Some(pb) = self.progress_bar.take() {
            // finish_and_clear() will clear the progress bar's line
            pb.finish_and_clear();
            self.line_count = 0;
        }
    }
}

/// Result of running a subprocess with windowed stderr rendering.
#[derive(Debug, Clone)]
pub struct SubprocessOutput {
    /// Captured stdout
    pub stdout: Vec<u8>,
    /// Captured stderr
    pub stderr: Vec<u8>,
    /// Exit code
    pub exit_code: u32,
}

impl SubprocessOutput {
    /// Get stdout as a string, with UTF-8 error handling.
    pub fn stdout_str(&self) -> anyhow::Result<String> {
        String::from_utf8(self.stdout.clone()).context("Failed to parse stdout as UTF-8")
    }

    /// Get stderr as a string, with UTF-8 error handling.
    pub fn stderr_str(&self) -> anyhow::Result<String> {
        String::from_utf8(self.stderr.clone()).context("Failed to parse stderr as UTF-8")
    }

    /// Check if the process exited successfully.
    pub fn success(&self) -> bool {
        self.exit_code == 0
    }

    /// Get the exit code.
    pub fn exit_code(&self) -> u32 {
        self.exit_code
    }
}

/// Run a subprocess with piped stdout/stderr, capturing stdout fully while
/// rendering stderr lines live in a ring buffer.
///
/// # Arguments
///
/// * `logger` - Logger instance to manage progress bar suspension/clearing
/// * `cmd_builder` - Closure that builds a `portable_pty::CommandBuilder`
/// * `stderr_lines` - Number of stderr lines to show in the scrolling region
///   (default: 5)
///
/// # Behavior
///
/// - Uses PTY mode so subprocesses see a TTY (preserves ANSI colors)
/// - Sets up a scrolling region at the bottom of the terminal
/// - Suspends/clears any active progress bar before running
/// - Captures stdout fully
/// - Renders stderr lines live in the scrolling region
/// - On success: clears the scrolling region cleanly
/// - On failure: leaves/replays the final window
///
/// # Returns
///
/// Returns `SubprocessOutput` with captured stdout, stderr, and exit status.
pub async fn run_subprocess<F>(
    logger: &mut Logger,
    cmd_builder: F,
    stderr_lines: Option<usize>,
) -> anyhow::Result<SubprocessOutput>
where
    F: FnOnce() -> CommandBuilder,
{
    let stderr_lines = stderr_lines.unwrap_or(5);

    let term = console::Term::stderr();
    let is_term = term.is_term();

    // Clear any existing Logger output before subprocess to avoid cursor
    // position conflicts. The scrolling region will change cursor position,
    // so Logger's Drop wouldn't be able to clear its lines correctly.
    if is_term {
        // Clear progress bar if present
        if let Some(pb) = logger.progress_bar.take() {
            pb.finish_and_clear();
        }
        // Clear any status lines the Logger has printed
        if logger.line_count > 0 {
            let _ = term.clear_last_lines(logger.line_count);
            logger.line_count = 0;
        }
    }

    // Track how many lines we've drawn for cleanup
    let stderr_lines_u16 = stderr_lines as u16;
    let lines_drawn = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
    let lines_drawn_render = lines_drawn.clone();

    // Build command using portable-pty
    let cmd = cmd_builder();

    // Create PTY
    let pty_system = native_pty_system();
    let pty_size = PtySize {
        rows: stderr_lines_u16,
        cols: 80,
        pixel_width: 0,
        pixel_height: 0,
    };
    let pty = pty_system
        .openpty(pty_size)
        .context("Failed to create PTY")?;

    // Spawn command in PTY
    let mut child = pty
        .slave
        .spawn_command(cmd)
        .context("Failed to spawn command in PTY")?;

    // Get handles for stdout and stderr from PTY
    // We need to keep a reference to the master to close it later
    let mut reader = pty
        .master
        .try_clone_reader()
        .context("Failed to clone PTY reader")?;

    // Keep the master alive until we're done reading
    let master = pty.master;

    // Channel to coordinate rendering (send raw bytes to preserve ANSI codes)
    let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<Vec<u8>>();
    // Keep a clone of tx to close the channel if we timeout
    let tx_clone = tx.clone();

    // Collect output as it arrives (for timeout fallback)
    let collected_output = std::sync::Arc::new(std::sync::Mutex::new(Vec::<u8>::new()));
    let collected_output_clone = collected_output.clone();

    // Task to read from PTY (combines stdout and stderr)
    // PTY reader is blocking, so we use spawn_blocking
    // Allow excessive nesting: inherent to async spawn + spawn_blocking + loop +
    // match pattern
    #[allow(clippy::excessive_nesting)]
    let pty_task = tokio::spawn(async move {
        tokio::task::spawn_blocking(move || {
            let mut full_output = Vec::new();
            let mut buffer = vec![0u8; 4096];

            loop {
                match reader.read(&mut buffer) {
                    Ok(0) => break, // EOF
                    Ok(bytes_read) => {
                        let chunk = &buffer[..bytes_read];
                        full_output.extend_from_slice(chunk);
                        // Also collect in shared buffer for timeout fallback
                        if let Ok(mut collected) = collected_output_clone.lock() {
                            collected.extend_from_slice(chunk);
                        }
                        let _ = tx.send(chunk.to_vec());
                    }
                    Err(err) => {
                        // On error, still capture what we have
                        let error_msg = format!("<pty read error: {}>", err);
                        let error_bytes = error_msg.as_bytes();
                        full_output.extend_from_slice(error_bytes);
                        if let Ok(mut collected) = collected_output_clone.lock() {
                            collected.extend_from_slice(error_bytes);
                        }
                        let _ = tx.send(error_bytes.to_vec());
                        break;
                    }
                }
            }

            // Close the channel to signal completion
            drop(tx);

            Ok::<Vec<u8>, anyhow::Error>(full_output)
        })
        .await
        .context("Failed to join blocking PTY read task")?
    });

    // Render output inline (below current cursor position)
    let mut output_buffer = Vec::new();
    let mut output_ring: Vec<Vec<u8>> = Vec::with_capacity(stderr_lines);

    // Process output bytes as they arrive
    // Allow excessive nesting: inherent to async spawn with nested loops and
    // conditionals
    #[allow(clippy::excessive_nesting)]
    let render_task = tokio::spawn(async move {
        let mut current_lines_displayed: usize = 0;

        while let Some(chunk) = rx.recv().await {
            output_buffer.extend_from_slice(&chunk);

            // Split buffer into complete lines (preserving ANSI codes)
            let mut lines: Vec<Vec<u8>> = Vec::new();
            let mut current_line = Vec::new();
            for byte in output_buffer.iter().copied() {
                current_line.push(byte);
                if byte == b'\n' {
                    lines.push(current_line);
                    current_line = Vec::new();
                }
            }
            output_buffer = current_line;

            // Update ring buffer with new complete lines
            for line in lines {
                output_ring.push(line);
                if output_ring.len() > stderr_lines {
                    output_ring.remove(0);
                }
            }

            // Render ring buffer inline (below current position)
            if is_term && !output_ring.is_empty() {
                let mut stderr_handle = std::io::stderr();

                // Move cursor up to clear previous output (if any)
                if current_lines_displayed > 0 {
                    // Move up and clear each line
                    write!(stderr_handle, "\x1b[{}A", current_lines_displayed).ok();
                    for _ in 0..current_lines_displayed {
                        write!(stderr_handle, "\x1b[2K\x1b[1B").ok(); // Clear line, move down
                    }
                    // Move back up to start position
                    write!(stderr_handle, "\x1b[{}A", current_lines_displayed).ok();
                }

                // Write all lines in the ring buffer (preserving ANSI codes)
                for line_bytes in &output_ring {
                    let _ = stderr_handle.write_all(line_bytes);
                }
                let _ = stderr_handle.flush();

                current_lines_displayed = output_ring.len();
                lines_drawn_render
                    .store(current_lines_displayed, std::sync::atomic::Ordering::SeqCst);
            }
        }

        // Handle any remaining partial line
        if !output_buffer.is_empty() {
            output_ring.push(output_buffer);
            if output_ring.len() > stderr_lines {
                output_ring.remove(0);
            }
            if is_term {
                let mut stderr_handle = std::io::stderr();

                // Move cursor up to clear previous output (if any)
                if current_lines_displayed > 0 {
                    write!(stderr_handle, "\x1b[{}A", current_lines_displayed).ok();
                    for _ in 0..current_lines_displayed {
                        write!(stderr_handle, "\x1b[2K\x1b[1B").ok();
                    }
                    write!(stderr_handle, "\x1b[{}A", current_lines_displayed).ok();
                }

                // Render final ring buffer state
                for line_bytes in &output_ring {
                    let _ = stderr_handle.write_all(line_bytes);
                }
                let _ = stderr_handle.flush();

                lines_drawn_render.store(output_ring.len(), std::sync::atomic::Ordering::SeqCst);
            }
        }

        (output_ring, is_term)
    });

    // Wait for process to complete (blocking call, so wrap in spawn_blocking)
    let status = tokio::task::spawn_blocking(move || child.wait())
        .await
        .context("Failed to join process wait task")?
        .context("Failed to wait for subprocess")?;

    // Close the PTY master to signal EOF to the reader
    // This ensures the reader sees EOF even if the process has already exited
    // On Windows, we need to drop the master earlier to help the blocking read
    // return
    drop(master);

    // On Windows, give a small delay to allow the reader to see EOF
    #[cfg(windows)]
    tokio::time::sleep(std::time::Duration::from_millis(100)).await;

    // Wait for PTY reading to complete (with timeout to prevent hanging)
    // If timeout occurs but process has exited, use collected output as fallback
    // On Windows, use a very short timeout since blocking reads may never return
    let timeout_duration = if cfg!(windows) {
        std::time::Duration::from_millis(500)
    } else {
        std::time::Duration::from_secs(10)
    };
    let pty_output = match tokio::time::timeout(timeout_duration, pty_task).await {
        Ok(result) => {
            // Task completed, get the result
            result.context("Failed to join PTY task")??
        }
        Err(_) => {
            // Timeout occurred - this commonly happens on Windows where blocking
            // reads in spawn_blocking cannot be cancelled. Since the process has
            // already exited, we use the output we collected as it arrived through
            // the channel. The blocking task will continue running in the background
            // but won't affect the test outcome.
            // Close the channel to allow render_task to complete
            drop(tx_clone);
            collected_output.lock().unwrap().clone()
        }
    };
    // Wait for render task with timeout to prevent hanging
    // Use very short timeout on Windows where operations may hang
    let render_timeout = if cfg!(windows) {
        std::time::Duration::from_millis(500)
    } else {
        std::time::Duration::from_secs(5)
    };
    let (_final_output_ring, was_term) =
        match tokio::time::timeout(render_timeout, render_task).await {
            Ok(result) => result.context("Failed to join render task")?,
            Err(_) => {
                // Render task timed out - this can happen on Windows where
                // blocking operations may not complete. We'll continue without
                // the final render state.
                (Vec::new(), is_term)
            }
        };

    // For now, treat all PTY output as stderr (we can separate later if needed)
    // In PTY mode, stdout and stderr are combined
    let stdout_bytes = Vec::new(); // PTY combines stdout/stderr, so we'll capture all as stderr
    let stderr_bytes = pty_output;

    // Handle final cleanup
    let exit_code = status.exit_code();
    let final_lines_drawn = lines_drawn.load(std::sync::atomic::Ordering::SeqCst);

    if was_term && final_lines_drawn > 0 {
        // Clear the lines we drew by moving up and clearing each line
        let mut stderr_handle = std::io::stderr();
        write!(stderr_handle, "\x1b[{}A", final_lines_drawn).ok();
        for _ in 0..final_lines_drawn {
            write!(stderr_handle, "\x1b[2K\x1b[1B").ok(); // Clear line, move down
        }
        // Move back up to where we started
        write!(stderr_handle, "\x1b[{}A", final_lines_drawn).ok();
        let _ = stderr_handle.flush();
    }

    Ok(SubprocessOutput {
        stdout: stdout_bytes,
        stderr: stderr_bytes,
        exit_code,
    })
}

impl Default for Logger {
    fn default() -> Self {
        Self::new()
    }
}

impl Drop for Logger {
    fn drop(&mut self) {
        // Clear the progress bar
        if let Some(pb) = self.progress_bar.take() {
            pb.finish_and_clear();
        }

        // Clear the reserved lines (including our status + subprocess output)
        if self.line_count > 0 {
            use console::Term;
            let term = Term::stderr();
            if term.is_term() {
                let _ = term.clear_last_lines(self.line_count);
            }
            self.line_count = 0;
        }
    }
}

#[cfg(test)]
mod tests {
    #[cfg(not(windows))]
    use portable_pty::CommandBuilder;

    use super::*;

    #[tokio::test]
    async fn test_logger_new() {
        let logger = Logger::new();
        assert!(logger.progress_bar.is_none());
        assert_eq!(logger.line_count, 0);
    }

    #[tokio::test]
    async fn test_logger_status() {
        let mut logger = Logger::new();
        logger.status("Building", "test-crate");
        assert!(logger.progress_bar.is_some());
        assert_eq!(logger.line_count, 1);
    }

    #[tokio::test]
    async fn test_logger_clear_status() {
        let mut logger = Logger::new();
        logger.status("Building", "test-crate");
        assert!(logger.progress_bar.is_some());
        logger.clear_status();
        assert!(logger.progress_bar.is_none());
        assert_eq!(logger.line_count, 0);
    }

    #[tokio::test]
    async fn test_logger_finish() {
        let mut logger = Logger::new();
        logger.status("Building", "test-crate");
        logger.finish();
        assert!(logger.progress_bar.is_none());
        assert_eq!(logger.line_count, 0);
    }

    #[tokio::test]
    async fn test_subprocess_output_success() {
        let output = SubprocessOutput {
            stdout: b"stdout content".to_vec(),
            stderr: b"stderr content".to_vec(),
            exit_code: 0,
        };
        assert!(output.success());
        assert_eq!(output.exit_code(), 0);
        assert_eq!(output.stdout_str().unwrap(), "stdout content");
        assert_eq!(output.stderr_str().unwrap(), "stderr content");
    }

    #[tokio::test]
    async fn test_subprocess_output_failure() {
        let output = SubprocessOutput {
            stdout: b"".to_vec(),
            stderr: b"error message".to_vec(),
            exit_code: 1,
        };
        assert!(!output.success());
        assert_eq!(output.exit_code(), 1);
        assert_eq!(output.stderr_str().unwrap(), "error message");
    }

    #[tokio::test]
    #[cfg(not(windows))]
    async fn test_run_subprocess_simple_success() {
        let mut logger = Logger::new();
        let output = run_subprocess(
            &mut logger,
            || {
                let mut cmd = CommandBuilder::new("echo");
                cmd.arg("hello world");
                cmd
            },
            Some(3),
        )
        .await
        .unwrap();

        assert!(output.success());
        assert_eq!(output.exit_code(), 0);
        // PTY combines stdout/stderr, so output should be in stderr
        let stderr = output.stderr_str().unwrap();
        assert!(stderr.contains("hello world") || stderr.is_empty());
    }

    #[tokio::test]
    #[cfg(not(windows))]
    async fn test_run_subprocess_simple_failure() {
        let mut logger = Logger::new();
        let output = run_subprocess(&mut logger, || CommandBuilder::new("false"), Some(3))
            .await
            .unwrap();

        assert!(!output.success());
        assert_ne!(output.exit_code(), 0);
    }

    #[tokio::test]
    #[cfg(not(windows))]
    async fn test_run_subprocess_multiline_output() {
        let mut logger = Logger::new();
        let output = run_subprocess(
            &mut logger,
            || {
                let mut cmd = CommandBuilder::new("sh");
                cmd.arg("-c");
                cmd.arg("echo 'line 1'; echo 'line 2'; echo 'line 3'; echo 'line 4'; echo 'line 5'; echo 'line 6'");
                cmd
            },
            Some(3), // Only show 3 lines in ring buffer
        )
        .await
        .unwrap();

        assert!(output.success());
        // Should capture all output even though only 3 lines shown
        let stderr = output.stderr_str().unwrap();
        assert!(stderr.contains("line 1"));
        assert!(stderr.contains("line 6"));
    }

    #[tokio::test]
    #[cfg(not(windows))]
    async fn test_run_subprocess_with_progress_bar() {
        let mut logger = Logger::new();
        logger.status("Preparing", "test");
        assert!(logger.progress_bar.is_some());

        let output = run_subprocess(
            &mut logger,
            || {
                let mut cmd = CommandBuilder::new("echo");
                cmd.arg("test output");
                cmd
            },
            None,
        )
        .await
        .unwrap();

        assert!(output.success());
        // Progress bar should be cleared before subprocess
        // (we can't easily test this without mocking, but the function should
        // complete)
    }

    #[tokio::test]
    #[cfg(not(windows))]
    async fn test_run_subprocess_exit_code_preservation() {
        let mut logger = Logger::new();
        let output = run_subprocess(
            &mut logger,
            || {
                let mut cmd = CommandBuilder::new("sh");
                cmd.arg("-c");
                cmd.arg("exit 42");
                cmd
            },
            None,
        )
        .await
        .unwrap();

        assert!(!output.success());
        assert_eq!(output.exit_code(), 42);
    }

    #[tokio::test]
    #[cfg(not(windows))]
    async fn test_run_subprocess_ansi_colors_preserved() {
        let mut logger = Logger::new();
        let output = run_subprocess(
            &mut logger,
            || {
                let mut cmd = CommandBuilder::new("sh");
                cmd.arg("-c");
                cmd.arg("echo -e '\\033[31mred\\033[0m'");
                cmd
            },
            None,
        )
        .await
        .unwrap();

        assert!(output.success());
        let stderr = output.stderr_str().unwrap();
        // ANSI codes should be preserved in PTY mode
        assert!(stderr.contains("\x1b[31m") || stderr.contains("red"));
    }

    #[tokio::test]
    #[cfg(not(windows))]
    async fn test_run_subprocess_default_stderr_lines() {
        let mut logger = Logger::new();
        let output = run_subprocess(
            &mut logger,
            || {
                let mut cmd = CommandBuilder::new("echo");
                cmd.arg("test");
                cmd
            },
            None, // Should default to 5 lines
        )
        .await
        .unwrap();

        assert!(output.success());
    }

    #[tokio::test]
    #[cfg(not(windows))]
    async fn test_run_subprocess_custom_stderr_lines() {
        let mut logger = Logger::new();
        let output = run_subprocess(
            &mut logger,
            || {
                let mut cmd = CommandBuilder::new("echo");
                cmd.arg("test");
                cmd
            },
            Some(10), // Custom 10 lines
        )
        .await
        .unwrap();

        assert!(output.success());
    }

    #[tokio::test]
    #[cfg(not(windows))]
    async fn test_run_subprocess_nonexistent_command() {
        let mut logger = Logger::new();
        let result = run_subprocess(
            &mut logger,
            || CommandBuilder::new("nonexistent-command-xyz-123"),
            None,
        )
        .await;

        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_subprocess_output_utf8_handling() {
        let output = SubprocessOutput {
            stdout: "hello 世界".as_bytes().to_vec(),
            stderr: "error 错误".as_bytes().to_vec(),
            exit_code: 0,
        };

        assert_eq!(output.stdout_str().unwrap(), "hello 世界");
        assert_eq!(output.stderr_str().unwrap(), "error 错误");
    }

    #[tokio::test]
    async fn test_subprocess_output_invalid_utf8() {
        let output = SubprocessOutput {
            stdout: vec![0xFF, 0xFE, 0xFD], // Invalid UTF-8
            stderr: vec![],
            exit_code: 0,
        };

        assert!(output.stdout_str().is_err());
    }

    #[tokio::test]
    async fn test_logger_suspend() {
        let mut logger = Logger::new();
        logger.status("Building", "test");
        let result = logger.suspend(|| 42);
        assert_eq!(result, 42);
    }

    #[tokio::test]
    async fn test_logger_suspend_without_progress() {
        let mut logger = Logger::new();
        let result = logger.suspend(|| 42);
        assert_eq!(result, 42);
    }

    #[tokio::test]
    async fn test_logger_status_permanent() {
        let logger = Logger::new();
        // Should not panic
        logger.status_permanent("Compiling", "test-crate");
    }

    #[tokio::test]
    async fn test_logger_warning() {
        let logger = Logger::new();
        // Should not panic
        logger.warning("Warning", "test message");
    }

    #[tokio::test]
    async fn test_logger_info() {
        let logger = Logger::new();
        // Should not panic
        logger.info("Info", "test message");
    }

    #[tokio::test]
    async fn test_logger_error() {
        let logger = Logger::new();
        // Should not panic
        logger.error("Error", "test message");
    }

    #[tokio::test]
    async fn test_logger_print_message() {
        let logger = Logger::new();
        // Should not panic
        logger.print_message("test message");
    }

    #[tokio::test]
    async fn test_logger_progress() {
        let mut logger = Logger::new();
        logger.progress("Processing...");
        assert!(logger.progress_bar.is_some());
    }

    #[tokio::test]
    async fn test_logger_set_progress_message() {
        let mut logger = Logger::new();
        logger.progress("Initial");
        logger.set_progress_message("Updated");
        assert!(logger.progress_bar.is_some());
    }
}