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
//! Configuration types for rust-expect.
//!
//! This module defines configuration structures for sessions, timeouts,
//! logging, and other customizable behavior.

use std::collections::HashMap;
use std::path::PathBuf;
use std::time::Duration;

/// Default timeout duration (30 seconds).
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);

/// Default buffer size (100 MB).
pub const DEFAULT_BUFFER_SIZE: usize = 100 * 1024 * 1024;

/// Default terminal width.
pub const DEFAULT_TERMINAL_WIDTH: u16 = 80;

/// Default terminal height.
pub const DEFAULT_TERMINAL_HEIGHT: u16 = 24;

/// Default TERM environment variable value.
pub const DEFAULT_TERM: &str = "xterm-256color";

/// Default delay before send operations.
pub const DEFAULT_DELAY_BEFORE_SEND: Duration = Duration::from_millis(50);

/// Configuration for a session.
#[derive(Debug, Clone)]
pub struct SessionConfig {
    /// The command to execute.
    pub command: String,

    /// Command arguments.
    pub args: Vec<String>,

    /// Environment variables to set.
    pub env: HashMap<String, String>,

    /// Whether to inherit the parent environment.
    pub inherit_env: bool,

    /// Working directory for the process.
    pub working_dir: Option<PathBuf>,

    /// Terminal dimensions (width, height).
    pub dimensions: (u16, u16),

    /// Timeout configuration.
    pub timeout: TimeoutConfig,

    /// Buffer configuration.
    pub buffer: BufferConfig,

    /// Logging configuration.
    pub logging: LoggingConfig,

    /// Line ending configuration.
    pub line_ending: LineEnding,

    /// Encoding configuration.
    pub encoding: EncodingConfig,

    /// Delay before send operations.
    pub delay_before_send: Duration,
}

impl Default for SessionConfig {
    fn default() -> Self {
        let mut env = HashMap::new();
        env.insert("TERM".to_string(), DEFAULT_TERM.to_string());

        Self {
            command: String::new(),
            args: Vec::new(),
            env,
            inherit_env: true,
            working_dir: None,
            dimensions: (DEFAULT_TERMINAL_WIDTH, DEFAULT_TERMINAL_HEIGHT),
            timeout: TimeoutConfig::default(),
            buffer: BufferConfig::default(),
            logging: LoggingConfig::default(),
            line_ending: LineEnding::default(),
            encoding: EncodingConfig::default(),
            delay_before_send: DEFAULT_DELAY_BEFORE_SEND,
        }
    }
}

impl SessionConfig {
    /// Create a new session configuration with the given command.
    #[must_use]
    pub fn new(command: impl Into<String>) -> Self {
        Self {
            command: command.into(),
            ..Default::default()
        }
    }

    /// Set the command arguments.
    #[must_use]
    pub fn args<I, S>(mut self, args: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.args = args.into_iter().map(Into::into).collect();
        self
    }

    /// Add an environment variable.
    #[must_use]
    pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.env.insert(key.into(), value.into());
        self
    }

    /// Set whether to inherit the parent environment.
    #[must_use]
    pub const fn inherit_env(mut self, inherit: bool) -> Self {
        self.inherit_env = inherit;
        self
    }

    /// Set the working directory.
    #[must_use]
    pub fn working_dir(mut self, path: impl Into<PathBuf>) -> Self {
        self.working_dir = Some(path.into());
        self
    }

    /// Set the terminal dimensions.
    #[must_use]
    pub const fn dimensions(mut self, width: u16, height: u16) -> Self {
        self.dimensions = (width, height);
        self
    }

    /// Set the default timeout.
    #[must_use]
    pub const fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout.default = timeout;
        self
    }

    /// Set the line ending style.
    #[must_use]
    pub const fn line_ending(mut self, line_ending: LineEnding) -> Self {
        self.line_ending = line_ending;
        self
    }

    /// Set the delay before send operations.
    #[must_use]
    pub const fn delay_before_send(mut self, delay: Duration) -> Self {
        self.delay_before_send = delay;
        self
    }
}

/// Configuration for timeouts.
#[derive(Debug, Clone)]
pub struct TimeoutConfig {
    /// Default timeout for expect operations.
    pub default: Duration,

    /// Timeout for spawn operations.
    pub spawn: Duration,

    /// Timeout for close operations.
    pub close: Duration,
}

impl Default for TimeoutConfig {
    fn default() -> Self {
        Self {
            default: DEFAULT_TIMEOUT,
            spawn: Duration::from_secs(60),
            close: Duration::from_secs(10),
        }
    }
}

impl TimeoutConfig {
    /// Create a new timeout configuration with the given default timeout.
    #[must_use]
    pub fn new(default: Duration) -> Self {
        Self {
            default,
            ..Default::default()
        }
    }

    /// Set the spawn timeout.
    #[must_use]
    pub const fn spawn(mut self, timeout: Duration) -> Self {
        self.spawn = timeout;
        self
    }

    /// Set the close timeout.
    #[must_use]
    pub const fn close(mut self, timeout: Duration) -> Self {
        self.close = timeout;
        self
    }
}

/// Configuration for the output buffer.
#[derive(Debug, Clone)]
pub struct BufferConfig {
    /// Maximum buffer size in bytes.
    pub max_size: usize,

    /// Size of the search window for pattern matching.
    pub search_window: Option<usize>,

    /// Whether to use a ring buffer (discard oldest data when full).
    pub ring_buffer: bool,
}

impl Default for BufferConfig {
    fn default() -> Self {
        Self {
            max_size: DEFAULT_BUFFER_SIZE,
            search_window: None,
            ring_buffer: true,
        }
    }
}

impl BufferConfig {
    /// Create a new buffer configuration with the given max size.
    #[must_use]
    pub fn new(max_size: usize) -> Self {
        Self {
            max_size,
            ..Default::default()
        }
    }

    /// Set the search window size.
    #[must_use]
    pub const fn search_window(mut self, size: usize) -> Self {
        self.search_window = Some(size);
        self
    }

    /// Set whether to use a ring buffer.
    #[must_use]
    pub const fn ring_buffer(mut self, enabled: bool) -> Self {
        self.ring_buffer = enabled;
        self
    }
}

/// Configuration for logging.
#[derive(Debug, Clone, Default)]
pub struct LoggingConfig {
    /// Path to log file.
    pub log_file: Option<PathBuf>,

    /// Whether to echo output to stdout.
    pub log_user: bool,

    /// Log format.
    pub format: LogFormat,

    /// Whether to log sent data separately from received data.
    pub separate_io: bool,

    /// Patterns to redact from logs.
    pub redact_patterns: Vec<String>,
}

impl LoggingConfig {
    /// Create a new logging configuration.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the log file path.
    #[must_use]
    pub fn log_file(mut self, path: impl Into<PathBuf>) -> Self {
        self.log_file = Some(path.into());
        self
    }

    /// Set whether to echo to stdout.
    #[must_use]
    pub const fn log_user(mut self, enabled: bool) -> Self {
        self.log_user = enabled;
        self
    }

    /// Set the log format.
    #[must_use]
    pub const fn format(mut self, format: LogFormat) -> Self {
        self.format = format;
        self
    }

    /// Add a pattern to redact from logs.
    #[must_use]
    pub fn redact(mut self, pattern: impl Into<String>) -> Self {
        self.redact_patterns.push(pattern.into());
        self
    }
}

/// Log format options.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum LogFormat {
    /// Raw output (no formatting).
    #[default]
    Raw,

    /// Timestamped output.
    Timestamped,

    /// Newline-delimited JSON.
    Ndjson,

    /// Asciicast v2 format (asciinema compatible).
    Asciicast,
}

/// Line ending styles.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum LineEnding {
    /// Unix-style line ending (LF).
    #[default]
    Lf,

    /// Windows-style line ending (CRLF).
    CrLf,

    /// Classic Mac line ending (CR).
    Cr,
}

impl LineEnding {
    /// Get the line ending as a string.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Lf => "\n",
            Self::CrLf => "\r\n",
            Self::Cr => "\r",
        }
    }

    /// Get the line ending as bytes.
    #[must_use]
    pub const fn as_bytes(self) -> &'static [u8] {
        match self {
            Self::Lf => b"\n",
            Self::CrLf => b"\r\n",
            Self::Cr => b"\r",
        }
    }

    /// Detect the appropriate line ending for the current platform.
    #[must_use]
    pub const fn platform_default() -> Self {
        if cfg!(windows) { Self::CrLf } else { Self::Lf }
    }
}

/// Configuration for text encoding.
#[derive(Debug, Clone)]
pub struct EncodingConfig {
    /// The encoding to use (default: UTF-8).
    pub encoding: Encoding,

    /// How to handle invalid sequences.
    pub error_handling: EncodingErrorHandling,

    /// Whether to normalize line endings.
    pub normalize_line_endings: bool,
}

impl Default for EncodingConfig {
    fn default() -> Self {
        Self {
            encoding: Encoding::Utf8,
            error_handling: EncodingErrorHandling::Replace,
            normalize_line_endings: false,
        }
    }
}

impl EncodingConfig {
    /// Create a new encoding configuration.
    #[must_use]
    pub fn new(encoding: Encoding) -> Self {
        Self {
            encoding,
            ..Default::default()
        }
    }

    /// Set the error handling mode.
    #[must_use]
    pub const fn error_handling(mut self, mode: EncodingErrorHandling) -> Self {
        self.error_handling = mode;
        self
    }

    /// Set whether to normalize line endings.
    #[must_use]
    pub const fn normalize_line_endings(mut self, normalize: bool) -> Self {
        self.normalize_line_endings = normalize;
        self
    }
}

/// Supported text encodings.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Encoding {
    /// UTF-8 encoding.
    #[default]
    Utf8,

    /// Raw bytes (no encoding).
    Raw,

    /// ISO-8859-1 (Latin-1).
    #[cfg(feature = "legacy-encoding")]
    Latin1,

    /// Windows-1252.
    #[cfg(feature = "legacy-encoding")]
    Windows1252,
}

/// How to handle encoding errors.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum EncodingErrorHandling {
    /// Replace invalid sequences with the replacement character.
    #[default]
    Replace,

    /// Skip invalid sequences.
    Skip,

    /// Return an error on invalid sequences.
    Strict,

    /// Escape invalid bytes as hex.
    Escape,
}

/// Configuration for interact mode.
#[derive(Debug, Clone)]
pub struct InteractConfig {
    /// Escape character to exit interact mode.
    pub escape_char: Option<char>,

    /// Timeout for idle detection.
    pub idle_timeout: Option<Duration>,

    /// Whether to echo input.
    pub echo: bool,

    /// Output hooks.
    pub output_hooks: Vec<InteractHook>,

    /// Input hooks.
    pub input_hooks: Vec<InteractHook>,
}

impl Default for InteractConfig {
    fn default() -> Self {
        Self {
            escape_char: Some('\x1d'), // Ctrl+]
            idle_timeout: None,
            echo: true,
            output_hooks: Vec::new(),
            input_hooks: Vec::new(),
        }
    }
}

impl InteractConfig {
    /// Create a new interact configuration.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the escape character.
    #[must_use]
    pub const fn escape_char(mut self, c: char) -> Self {
        self.escape_char = Some(c);
        self
    }

    /// Disable the escape character.
    #[must_use]
    pub const fn no_escape(mut self) -> Self {
        self.escape_char = None;
        self
    }

    /// Set the idle timeout.
    #[must_use]
    pub const fn idle_timeout(mut self, timeout: Duration) -> Self {
        self.idle_timeout = Some(timeout);
        self
    }

    /// Set whether to echo input.
    #[must_use]
    pub const fn echo(mut self, enabled: bool) -> Self {
        self.echo = enabled;
        self
    }
}

/// A hook for interact mode.
#[derive(Debug, Clone)]
pub struct InteractHook {
    /// The pattern to match.
    pub pattern: String,

    /// Whether this is a regex pattern.
    pub is_regex: bool,
}

impl InteractHook {
    /// Create a new interact hook with a literal pattern.
    #[must_use]
    pub fn literal(pattern: impl Into<String>) -> Self {
        Self {
            pattern: pattern.into(),
            is_regex: false,
        }
    }

    /// Create a new interact hook with a regex pattern.
    #[must_use]
    pub fn regex(pattern: impl Into<String>) -> Self {
        Self {
            pattern: pattern.into(),
            is_regex: true,
        }
    }
}

/// Configuration for human-like typing.
#[derive(Debug, Clone)]
pub struct HumanTypingConfig {
    /// Base delay between characters.
    pub base_delay: Duration,

    /// Variance in delay (random offset from base).
    pub variance: Duration,

    /// Chance of making a typo (0.0 to 1.0).
    pub typo_chance: f32,

    /// Chance of correcting a typo (0.0 to 1.0).
    pub correction_chance: f32,
}

impl Default for HumanTypingConfig {
    fn default() -> Self {
        Self {
            base_delay: Duration::from_millis(100),
            variance: Duration::from_millis(50),
            typo_chance: 0.01,
            correction_chance: 0.85,
        }
    }
}

impl HumanTypingConfig {
    /// Create a new human typing configuration.
    #[must_use]
    pub fn new(base_delay: Duration, variance: Duration) -> Self {
        Self {
            base_delay,
            variance,
            ..Default::default()
        }
    }

    /// Set the typo chance.
    #[must_use]
    pub const fn typo_chance(mut self, chance: f32) -> Self {
        self.typo_chance = chance;
        self
    }

    /// Set the correction chance.
    #[must_use]
    pub const fn correction_chance(mut self, chance: f32) -> Self {
        self.correction_chance = chance;
        self
    }
}

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

    #[test]
    fn session_config_builder() {
        let config = SessionConfig::new("bash")
            .args(["-l", "-i"])
            .env("MY_VAR", "value")
            .dimensions(120, 40)
            .timeout(Duration::from_secs(10));

        assert_eq!(config.command, "bash");
        assert_eq!(config.args, vec!["-l", "-i"]);
        assert_eq!(config.env.get("MY_VAR"), Some(&"value".to_string()));
        assert_eq!(config.dimensions, (120, 40));
        assert_eq!(config.timeout.default, Duration::from_secs(10));
    }

    #[test]
    fn line_ending_as_str() {
        assert_eq!(LineEnding::Lf.as_str(), "\n");
        assert_eq!(LineEnding::CrLf.as_str(), "\r\n");
        assert_eq!(LineEnding::Cr.as_str(), "\r");
    }

    #[test]
    fn default_config_has_term() {
        let config = SessionConfig::default();
        assert_eq!(config.env.get("TERM"), Some(&"xterm-256color".to_string()));
    }

    #[test]
    fn logging_config_builder() {
        let config = LoggingConfig::new()
            .log_file("/tmp/session.log")
            .log_user(true)
            .format(LogFormat::Ndjson)
            .redact("password");

        assert_eq!(config.log_file, Some(PathBuf::from("/tmp/session.log")));
        assert!(config.log_user);
        assert_eq!(config.format, LogFormat::Ndjson);
        assert_eq!(config.redact_patterns, vec!["password"]);
    }
}