rust-expect 0.1.0

Next-generation Expect-style terminal automation library for Rust
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
//! Error types for rust-expect.
//!
//! This module defines all error types used throughout the library.
//! Errors are designed to be informative, providing context about what went wrong
//! and including relevant data for debugging (e.g., buffer contents on timeout).

use std::process::ExitStatus;
use std::time::Duration;

use thiserror::Error;

/// Maximum length of buffer content to display in error messages.
const MAX_BUFFER_DISPLAY: usize = 500;

/// Context lines to show before/after truncation point.
const CONTEXT_LINES: usize = 3;

/// Format buffer content for display, truncating if necessary.
fn format_buffer_snippet(buffer: &str) -> String {
    if buffer.is_empty() {
        return "(empty buffer)".to_string();
    }

    let buffer_len = buffer.len();

    if buffer_len <= MAX_BUFFER_DISPLAY {
        // Small buffer, show everything with visual markers
        return format!(
            "┌─ buffer ({} bytes) ──────────────────────\n{}\n└────────────────────────────────────────",
            buffer_len,
            buffer.lines().collect::<Vec<_>>().join("\n")
        );
    }

    // Large buffer - show tail with context
    let lines: Vec<&str> = buffer.lines().collect();
    let total_lines = lines.len();

    if total_lines <= CONTEXT_LINES * 2 {
        // Few lines, show all
        return format!(
            "┌─ buffer ({} bytes, {} lines) ─────────────\n{}\n└────────────────────────────────────────",
            buffer_len,
            total_lines,
            lines.join("\n")
        );
    }

    // Show last N lines with truncation indicator
    let tail_lines = &lines[lines.len().saturating_sub(CONTEXT_LINES * 2)..];
    let hidden = total_lines - tail_lines.len();

    format!(
        "┌─ buffer ({} bytes, {} lines) ─────────────\n│ ... ({} lines hidden)\n{}\n└────────────────────────────────────────",
        buffer_len,
        total_lines,
        hidden,
        tail_lines.join("\n")
    )
}

/// Format a timeout error message with enhanced context.
fn format_timeout_error(duration: Duration, pattern: &str, buffer: &str) -> String {
    let buffer_snippet = format_buffer_snippet(buffer);

    format!(
        "timeout after {duration:?} waiting for pattern\n\
         \n\
         Pattern: '{pattern}'\n\
         \n\
         {buffer_snippet}\n\
         \n\
         Tip: The pattern was not found in the output. Check that:\n\
         - The expected text actually appears in the output\n\
         - The pattern is correct (regex special chars may need escaping)\n\
         - The timeout duration is sufficient"
    )
}

/// Format a pattern not found error message.
fn format_pattern_not_found_error(pattern: &str, buffer: &str) -> String {
    let buffer_snippet = format_buffer_snippet(buffer);

    format!(
        "pattern not found before EOF\n\
         \n\
         Pattern: '{pattern}'\n\
         \n\
         {buffer_snippet}\n\
         \n\
         Tip: The process closed before the pattern was found."
    )
}

/// Format a process exited error message.
#[allow(clippy::trivially_copy_pass_by_ref)]
fn format_process_exited_error(exit_status: &ExitStatus, buffer: &str) -> String {
    let buffer_snippet = format_buffer_snippet(buffer);

    format!(
        "process exited unexpectedly with {exit_status:?}\n\
         \n\
         {buffer_snippet}"
    )
}

/// Format an EOF error message.
fn format_eof_error(buffer: &str) -> String {
    let buffer_snippet = format_buffer_snippet(buffer);

    format!(
        "end of file reached unexpectedly\n\
         \n\
         {buffer_snippet}"
    )
}

/// The main error type for rust-expect operations.
#[derive(Debug, Error)]
pub enum ExpectError {
    /// Failed to spawn a process.
    #[error("failed to spawn process: {0}")]
    Spawn(#[from] SpawnError),

    /// An I/O error occurred.
    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),

    /// An I/O error occurred with additional context.
    #[error("{context}: {source}")]
    IoWithContext {
        /// What operation was being performed.
        context: String,
        /// The underlying I/O error.
        #[source]
        source: std::io::Error,
    },

    /// Timeout waiting for pattern match.
    #[error("{}", format_timeout_error(*duration, pattern, buffer))]
    Timeout {
        /// The timeout duration that elapsed.
        duration: Duration,
        /// The pattern that was being searched for.
        pattern: String,
        /// Buffer contents at the time of timeout.
        buffer: String,
    },

    /// Pattern was not found before EOF.
    #[error("{}", format_pattern_not_found_error(pattern, buffer))]
    PatternNotFound {
        /// The pattern that was being searched for.
        pattern: String,
        /// Buffer contents when EOF was reached.
        buffer: String,
    },

    /// Process exited unexpectedly.
    #[error("{}", format_process_exited_error(exit_status, buffer))]
    ProcessExited {
        /// The exit status of the process.
        exit_status: ExitStatus,
        /// Buffer contents when process exited.
        buffer: String,
    },

    /// End of file reached.
    #[error("{}", format_eof_error(buffer))]
    Eof {
        /// Buffer contents when EOF was reached.
        buffer: String,
    },

    /// Invalid pattern specification.
    #[error("invalid pattern: {message}")]
    InvalidPattern {
        /// Description of what's wrong with the pattern.
        message: String,
    },

    /// Invalid regex pattern.
    #[error("invalid regex pattern: {0}")]
    Regex(#[from] regex::Error),

    /// Session is closed.
    #[error("session is closed")]
    SessionClosed,

    /// Session not found.
    #[error("session with id {id} not found")]
    SessionNotFound {
        /// The session ID that was not found.
        id: usize,
    },

    /// No sessions available for operation.
    #[error("no sessions available for operation")]
    NoSessions,

    /// Error in multi-session operation.
    #[error("multi-session error in session {session_id}: {error}")]
    MultiSessionError {
        /// The session that encountered the error.
        session_id: usize,
        /// The underlying error.
        error: Box<Self>,
    },

    /// Session is not in interact mode.
    #[error("session is not in interact mode")]
    NotInteracting,

    /// Buffer overflow.
    #[error("buffer overflow: maximum size of {max_size} bytes exceeded")]
    BufferOverflow {
        /// The maximum buffer size that was exceeded.
        max_size: usize,
    },

    /// Encoding error.
    #[error("encoding error: {message}")]
    Encoding {
        /// Description of the encoding error.
        message: String,
    },

    /// SSH connection error.
    #[cfg(feature = "ssh")]
    #[error("SSH error: {0}")]
    Ssh(#[from] SshError),

    /// Configuration error.
    #[error("configuration error: {message}")]
    Config {
        /// Description of the configuration error.
        message: String,
    },

    /// Signal error (Unix only).
    #[cfg(unix)]
    #[error("signal error: {message}")]
    Signal {
        /// Description of the signal error.
        message: String,
    },
}

/// Errors related to process spawning.
#[derive(Debug, Error)]
pub enum SpawnError {
    /// Command not found.
    #[error("command not found: {command}")]
    CommandNotFound {
        /// The command that was not found.
        command: String,
    },

    /// Permission denied.
    #[error("permission denied: {path}")]
    PermissionDenied {
        /// The path that could not be accessed.
        path: String,
    },

    /// PTY allocation failed.
    #[error("failed to allocate PTY: {reason}")]
    PtyAllocation {
        /// The reason for the failure.
        reason: String,
    },

    /// Failed to set up terminal.
    #[error("failed to set up terminal: {reason}")]
    TerminalSetup {
        /// The reason for the failure.
        reason: String,
    },

    /// Environment variable error.
    #[error("invalid environment variable: {name}")]
    InvalidEnv {
        /// The name of the invalid environment variable.
        name: String,
    },

    /// Working directory error.
    #[error("invalid working directory: {path}")]
    InvalidWorkingDir {
        /// The invalid working directory path.
        path: String,
    },

    /// General I/O error during spawn.
    #[error("I/O error during spawn: {0}")]
    Io(#[from] std::io::Error),

    /// Invalid command or argument.
    #[error("invalid {kind}: {reason}")]
    InvalidArgument {
        /// The kind of invalid input (e.g., "command", "argument").
        kind: String,
        /// The value that was invalid.
        value: String,
        /// The reason it's invalid.
        reason: String,
    },
}

/// Errors related to SSH connections.
#[cfg(feature = "ssh")]
#[derive(Debug, Error)]
pub enum SshError {
    /// Connection failed.
    #[error("failed to connect to {host}:{port}: {reason}")]
    Connection {
        /// The host that could not be connected to.
        host: String,
        /// The port that was used.
        port: u16,
        /// The reason for the failure.
        reason: String,
    },

    /// Authentication failed.
    #[error("authentication failed for user '{user}': {reason}")]
    Authentication {
        /// The user that failed to authenticate.
        user: String,
        /// The reason for the failure.
        reason: String,
    },

    /// Host key verification failed.
    #[error("host key verification failed for {host}: {reason}")]
    HostKeyVerification {
        /// The host whose key verification failed.
        host: String,
        /// The reason for the failure.
        reason: String,
    },

    /// Channel error.
    #[error("SSH channel error: {reason}")]
    Channel {
        /// The reason for the channel error.
        reason: String,
    },

    /// Session error.
    #[error("SSH session error: {reason}")]
    Session {
        /// The reason for the session error.
        reason: String,
    },

    /// Timeout during SSH operation.
    #[error("SSH operation timed out after {duration:?}")]
    Timeout {
        /// The duration that elapsed.
        duration: Duration,
    },
}

/// Result type alias for rust-expect operations.
pub type Result<T> = std::result::Result<T, ExpectError>;

impl ExpectError {
    /// Create a timeout error with the given details.
    pub fn timeout(
        duration: Duration,
        pattern: impl Into<String>,
        buffer: impl Into<String>,
    ) -> Self {
        Self::Timeout {
            duration,
            pattern: pattern.into(),
            buffer: buffer.into(),
        }
    }

    /// Create a pattern not found error.
    pub fn pattern_not_found(pattern: impl Into<String>, buffer: impl Into<String>) -> Self {
        Self::PatternNotFound {
            pattern: pattern.into(),
            buffer: buffer.into(),
        }
    }

    /// Create a process exited error.
    pub fn process_exited(exit_status: ExitStatus, buffer: impl Into<String>) -> Self {
        Self::ProcessExited {
            exit_status,
            buffer: buffer.into(),
        }
    }

    /// Create an EOF error.
    pub fn eof(buffer: impl Into<String>) -> Self {
        Self::Eof {
            buffer: buffer.into(),
        }
    }

    /// Create an invalid pattern error.
    pub fn invalid_pattern(message: impl Into<String>) -> Self {
        Self::InvalidPattern {
            message: message.into(),
        }
    }

    /// Create a buffer overflow error.
    #[must_use]
    pub const fn buffer_overflow(max_size: usize) -> Self {
        Self::BufferOverflow { max_size }
    }

    /// Create an encoding error.
    pub fn encoding(message: impl Into<String>) -> Self {
        Self::Encoding {
            message: message.into(),
        }
    }

    /// Create a configuration error.
    pub fn config(message: impl Into<String>) -> Self {
        Self::Config {
            message: message.into(),
        }
    }

    /// Create an I/O error with context.
    pub fn io_context(context: impl Into<String>, source: std::io::Error) -> Self {
        Self::IoWithContext {
            context: context.into(),
            source,
        }
    }

    /// Wrap an I/O result with context.
    pub fn with_io_context<T>(result: std::io::Result<T>, context: impl Into<String>) -> Result<T> {
        result.map_err(|e| Self::io_context(context, e))
    }

    /// Check if this is a timeout error.
    #[must_use]
    pub const fn is_timeout(&self) -> bool {
        matches!(self, Self::Timeout { .. })
    }

    /// Check if this is an EOF error.
    #[must_use]
    pub const fn is_eof(&self) -> bool {
        matches!(self, Self::Eof { .. } | Self::ProcessExited { .. })
    }

    /// Get the buffer contents if this error contains them.
    #[must_use]
    pub fn buffer(&self) -> Option<&str> {
        match self {
            Self::Timeout { buffer, .. }
            | Self::PatternNotFound { buffer, .. }
            | Self::ProcessExited { buffer, .. }
            | Self::Eof { buffer, .. } => Some(buffer),
            _ => None,
        }
    }
}

impl SpawnError {
    /// Create a command not found error.
    pub fn command_not_found(command: impl Into<String>) -> Self {
        Self::CommandNotFound {
            command: command.into(),
        }
    }

    /// Create a permission denied error.
    pub fn permission_denied(path: impl Into<String>) -> Self {
        Self::PermissionDenied { path: path.into() }
    }

    /// Create a PTY allocation error.
    pub fn pty_allocation(reason: impl Into<String>) -> Self {
        Self::PtyAllocation {
            reason: reason.into(),
        }
    }

    /// Create a terminal setup error.
    pub fn terminal_setup(reason: impl Into<String>) -> Self {
        Self::TerminalSetup {
            reason: reason.into(),
        }
    }

    /// Create an invalid environment variable error.
    pub fn invalid_env(name: impl Into<String>) -> Self {
        Self::InvalidEnv { name: name.into() }
    }

    /// Create an invalid working directory error.
    pub fn invalid_working_dir(path: impl Into<String>) -> Self {
        Self::InvalidWorkingDir { path: path.into() }
    }
}

#[cfg(feature = "ssh")]
impl SshError {
    /// Create a connection error.
    pub fn connection(host: impl Into<String>, port: u16, reason: impl Into<String>) -> Self {
        Self::Connection {
            host: host.into(),
            port,
            reason: reason.into(),
        }
    }

    /// Create an authentication error.
    pub fn authentication(user: impl Into<String>, reason: impl Into<String>) -> Self {
        Self::Authentication {
            user: user.into(),
            reason: reason.into(),
        }
    }

    /// Create a host key verification error.
    pub fn host_key_verification(host: impl Into<String>, reason: impl Into<String>) -> Self {
        Self::HostKeyVerification {
            host: host.into(),
            reason: reason.into(),
        }
    }

    /// Create a channel error.
    pub fn channel(reason: impl Into<String>) -> Self {
        Self::Channel {
            reason: reason.into(),
        }
    }

    /// Create a session error.
    pub fn session(reason: impl Into<String>) -> Self {
        Self::Session {
            reason: reason.into(),
        }
    }

    /// Create a timeout error.
    #[must_use]
    pub const fn timeout(duration: Duration) -> Self {
        Self::Timeout { duration }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn error_display() {
        let err = ExpectError::timeout(
            Duration::from_secs(5),
            "password:",
            "Enter username: admin\n",
        );
        let msg = err.to_string();
        assert!(msg.contains("timeout"));
        assert!(msg.contains("password:"));
        assert!(msg.contains("admin"));
        // Check for enhanced formatting
        assert!(msg.contains("Pattern:"));
        assert!(msg.contains("buffer"));
    }

    #[test]
    fn error_display_with_tips() {
        let err = ExpectError::timeout(Duration::from_secs(5), "password:", "output here\n");
        let msg = err.to_string();
        // Check that tips are included
        assert!(msg.contains("Tip:"));
    }

    #[test]
    fn error_display_empty_buffer() {
        let err = ExpectError::eof("");
        let msg = err.to_string();
        assert!(msg.contains("empty buffer"));
    }

    #[test]
    fn error_display_large_buffer_truncation() {
        // Create a large buffer (> 500 bytes, > 6 lines)
        let large_buffer: String = (0..50).fold(String::new(), |mut acc, i| {
            use std::fmt::Write;
            let _ = writeln!(acc, "Line {i}: Some content here");
            acc
        });

        let err = ExpectError::timeout(Duration::from_secs(1), "pattern", &large_buffer);
        let msg = err.to_string();

        // Should contain truncation indicator
        assert!(msg.contains("lines hidden"));
        // Should show line count
        assert!(msg.contains("lines)"));
    }

    #[test]
    fn error_is_timeout() {
        let timeout = ExpectError::timeout(Duration::from_secs(1), "test", "buffer");
        assert!(timeout.is_timeout());

        let eof = ExpectError::eof("buffer");
        assert!(!eof.is_timeout());
    }

    #[test]
    fn error_buffer() {
        let err = ExpectError::timeout(Duration::from_secs(1), "test", "the buffer");
        assert_eq!(err.buffer(), Some("the buffer"));

        let io_err = ExpectError::Io(std::io::Error::other("test"));
        assert!(io_err.buffer().is_none());
    }

    #[test]
    fn spawn_error_display() {
        let err = SpawnError::command_not_found("/usr/bin/nonexistent");
        assert!(err.to_string().contains("nonexistent"));
    }

    #[test]
    fn format_buffer_snippet_empty() {
        let result = format_buffer_snippet("");
        assert_eq!(result, "(empty buffer)");
    }

    #[test]
    fn format_buffer_snippet_small() {
        let result = format_buffer_snippet("hello\nworld");
        assert!(result.contains("hello"));
        assert!(result.contains("world"));
        assert!(result.contains("bytes"));
    }

    #[test]
    fn pattern_not_found_error() {
        let err = ExpectError::pattern_not_found("prompt>", "some output");
        let msg = err.to_string();
        assert!(msg.contains("prompt>"));
        assert!(msg.contains("some output"));
        assert!(msg.contains("EOF"));
    }

    #[test]
    fn eof_error() {
        let err = ExpectError::eof("final output");
        let msg = err.to_string();
        assert!(msg.contains("end of file"));
        assert!(msg.contains("final output"));
    }

    #[test]
    fn io_with_context_error() {
        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
        let err = ExpectError::io_context("reading config file", io_err);
        let msg = err.to_string();
        assert!(msg.contains("reading config file"));
        assert!(msg.contains("file not found"));
    }

    #[test]
    fn with_io_context_helper() {
        let result: std::io::Result<()> = Err(std::io::Error::new(
            std::io::ErrorKind::PermissionDenied,
            "access denied",
        ));
        let err = ExpectError::with_io_context(result, "writing to log file").unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("writing to log file"));
        assert!(msg.contains("access denied"));
    }

    #[test]
    fn with_io_context_success() {
        let result: std::io::Result<i32> = Ok(42);
        let value = ExpectError::with_io_context(result, "some operation").unwrap();
        assert_eq!(value, 42);
    }
}