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
//! Synchronous wrapper for async expect operations.
//!
//! This module provides a blocking API for users who prefer or require
//! synchronous operations instead of async/await.

use std::time::Duration;

use tokio::runtime::{Builder, Runtime};

#[cfg(unix)]
use crate::backend::AsyncPty;
#[cfg(windows)]
use crate::backend::WindowsAsyncPty;
use crate::config::SessionConfig;
use crate::error::Result;
use crate::expect::Pattern;
use crate::session::Session;
use crate::types::{ControlChar, Match};

/// A synchronous session wrapper.
///
/// This wraps an async session and provides blocking methods for
/// use in synchronous contexts.
#[cfg(unix)]
pub struct SyncSession {
    /// The tokio runtime.
    runtime: Runtime,
    /// The inner async session.
    inner: Session<AsyncPty>,
}

/// A synchronous session wrapper (Windows).
///
/// This wraps an async session and provides blocking methods for
/// use in synchronous contexts using Windows ConPTY.
#[cfg(windows)]
pub struct SyncSession {
    /// The tokio runtime.
    runtime: Runtime,
    /// The inner async session.
    inner: Session<WindowsAsyncPty>,
}

#[cfg(unix)]
impl SyncSession {
    /// Spawn a command and create a session.
    ///
    /// # Errors
    ///
    /// Returns an error if spawning fails.
    pub fn spawn(command: &str, args: &[&str]) -> Result<Self> {
        let runtime = Builder::new_current_thread()
            .enable_all()
            .build()
            .map_err(|e| crate::error::ExpectError::io_context("creating tokio runtime", e))?;

        let inner = runtime.block_on(Session::spawn(command, args))?;

        Ok(Self { runtime, inner })
    }

    /// Spawn with custom configuration.
    ///
    /// # Errors
    ///
    /// Returns an error if spawning fails.
    pub fn spawn_with_config(command: &str, args: &[&str], config: SessionConfig) -> Result<Self> {
        let runtime = Builder::new_current_thread()
            .enable_all()
            .build()
            .map_err(|e| crate::error::ExpectError::io_context("creating tokio runtime", e))?;

        let inner = runtime.block_on(Session::spawn_with_config(command, args, config))?;

        Ok(Self { runtime, inner })
    }

    /// Get the session configuration.
    #[must_use]
    pub const fn config(&self) -> &SessionConfig {
        self.inner.config()
    }

    /// Check if the session is active.
    #[must_use]
    pub const fn is_active(&self) -> bool {
        !self.inner.is_eof()
    }

    /// Get the child process ID.
    #[must_use]
    pub fn pid(&self) -> u32 {
        self.inner.pid()
    }

    /// Send bytes to the session.
    ///
    /// # Errors
    ///
    /// Returns an error if the write fails.
    pub fn send(&mut self, data: &[u8]) -> Result<()> {
        self.runtime.block_on(self.inner.send(data))
    }

    /// Send a string to the session.
    ///
    /// # Errors
    ///
    /// Returns an error if the write fails.
    pub fn send_str(&mut self, s: &str) -> Result<()> {
        self.runtime.block_on(self.inner.send_str(s))
    }

    /// Send a line to the session.
    ///
    /// # Errors
    ///
    /// Returns an error if the write fails.
    pub fn send_line(&mut self, line: &str) -> Result<()> {
        self.runtime.block_on(self.inner.send_line(line))
    }

    /// Send a control character.
    ///
    /// # Errors
    ///
    /// Returns an error if the write fails.
    pub fn send_control(&mut self, ctrl: ControlChar) -> Result<()> {
        self.runtime.block_on(self.inner.send_control(ctrl))
    }

    /// Expect a pattern in the output.
    ///
    /// # Errors
    ///
    /// Returns an error on timeout or EOF.
    pub fn expect(&mut self, pattern: impl Into<Pattern>) -> Result<Match> {
        self.runtime.block_on(self.inner.expect(pattern))
    }

    /// Expect a pattern with a specific timeout.
    ///
    /// # Errors
    ///
    /// Returns an error on timeout or EOF.
    pub fn expect_timeout(
        &mut self,
        pattern: impl Into<Pattern>,
        timeout: Duration,
    ) -> Result<Match> {
        self.runtime
            .block_on(self.inner.expect_timeout(pattern, timeout))
    }

    /// Get the current buffer contents.
    #[must_use]
    pub fn buffer(&mut self) -> String {
        self.inner.buffer()
    }

    /// Clear the buffer.
    pub fn clear_buffer(&mut self) {
        self.inner.clear_buffer();
    }

    /// Resize the terminal.
    ///
    /// # Errors
    ///
    /// Returns an error if the resize fails.
    pub fn resize(&mut self, cols: u16, rows: u16) -> Result<()> {
        self.runtime.block_on(self.inner.resize_pty(cols, rows))
    }

    /// Send a signal to the child process.
    ///
    /// # Errors
    ///
    /// Returns an error if sending the signal fails.
    pub fn signal(&self, signal: i32) -> Result<()> {
        self.inner.signal(signal)
    }

    /// Kill the child process.
    ///
    /// # Errors
    ///
    /// Returns an error if killing fails.
    pub fn kill(&self) -> Result<()> {
        self.inner.kill()
    }

    /// Run an async operation synchronously.
    pub fn block_on<F, T>(&self, future: F) -> T
    where
        F: std::future::Future<Output = T>,
    {
        self.runtime.block_on(future)
    }
}

#[cfg(windows)]
impl SyncSession {
    /// Spawn a command and create a session.
    ///
    /// # Errors
    ///
    /// Returns an error if spawning fails.
    pub fn spawn(command: &str, args: &[&str]) -> Result<Self> {
        let runtime = Builder::new_current_thread()
            .enable_all()
            .build()
            .map_err(|e| crate::error::ExpectError::io_context("creating tokio runtime", e))?;

        let inner = runtime.block_on(Session::spawn(command, args))?;

        Ok(Self { runtime, inner })
    }

    /// Spawn with custom configuration.
    ///
    /// # Errors
    ///
    /// Returns an error if spawning fails.
    pub fn spawn_with_config(command: &str, args: &[&str], config: SessionConfig) -> Result<Self> {
        let runtime = Builder::new_current_thread()
            .enable_all()
            .build()
            .map_err(|e| crate::error::ExpectError::io_context("creating tokio runtime", e))?;

        let inner = runtime.block_on(Session::spawn_with_config(command, args, config))?;

        Ok(Self { runtime, inner })
    }

    /// Get the session configuration.
    #[must_use]
    pub const fn config(&self) -> &SessionConfig {
        self.inner.config()
    }

    /// Check if the session is active.
    #[must_use]
    pub fn is_active(&self) -> bool {
        !self.inner.is_eof()
    }

    /// Get the child process ID.
    #[must_use]
    pub fn pid(&self) -> u32 {
        self.inner.pid()
    }

    /// Send bytes to the session.
    ///
    /// # Errors
    ///
    /// Returns an error if the write fails.
    pub fn send(&mut self, data: &[u8]) -> Result<()> {
        self.runtime.block_on(self.inner.send(data))
    }

    /// Send a string to the session.
    ///
    /// # Errors
    ///
    /// Returns an error if the write fails.
    pub fn send_str(&mut self, s: &str) -> Result<()> {
        self.runtime.block_on(self.inner.send_str(s))
    }

    /// Send a line to the session.
    ///
    /// # Errors
    ///
    /// Returns an error if the write fails.
    pub fn send_line(&mut self, line: &str) -> Result<()> {
        self.runtime.block_on(self.inner.send_line(line))
    }

    /// Send a control character.
    ///
    /// # Errors
    ///
    /// Returns an error if the write fails.
    pub fn send_control(&mut self, ctrl: ControlChar) -> Result<()> {
        self.runtime.block_on(self.inner.send_control(ctrl))
    }

    /// Expect a pattern in the output.
    ///
    /// # Errors
    ///
    /// Returns an error on timeout or EOF.
    pub fn expect(&mut self, pattern: impl Into<Pattern>) -> Result<Match> {
        self.runtime.block_on(self.inner.expect(pattern))
    }

    /// Expect a pattern with a specific timeout.
    ///
    /// # Errors
    ///
    /// Returns an error on timeout or EOF.
    pub fn expect_timeout(
        &mut self,
        pattern: impl Into<Pattern>,
        timeout: Duration,
    ) -> Result<Match> {
        self.runtime
            .block_on(self.inner.expect_timeout(pattern, timeout))
    }

    /// Get the current buffer contents.
    #[must_use]
    pub fn buffer(&mut self) -> String {
        self.inner.buffer()
    }

    /// Clear the buffer.
    pub fn clear_buffer(&mut self) {
        self.inner.clear_buffer();
    }

    /// Resize the terminal.
    ///
    /// # Errors
    ///
    /// Returns an error if the resize fails.
    pub fn resize(&mut self, cols: u16, rows: u16) -> Result<()> {
        self.runtime.block_on(self.inner.resize_pty(cols, rows))
    }

    /// Check if the child process is still running.
    #[must_use]
    pub fn is_running(&self) -> bool {
        self.inner.is_running()
    }

    /// Kill the child process.
    ///
    /// # Errors
    ///
    /// Returns an error if killing fails.
    pub fn kill(&self) -> Result<()> {
        self.inner.kill()
    }

    /// Run an async operation synchronously.
    pub fn block_on<F, T>(&self, future: F) -> T
    where
        F: std::future::Future<Output = T>,
    {
        self.runtime.block_on(future)
    }
}

impl std::fmt::Debug for SyncSession {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SyncSession").finish_non_exhaustive()
    }
}

/// A blocking expect operation.
pub struct BlockingExpect<'a> {
    session: &'a mut SyncSession,
    timeout: Duration,
}

impl<'a> BlockingExpect<'a> {
    /// Create a new blocking expect operation.
    pub const fn new(session: &'a mut SyncSession) -> Self {
        let timeout = session.config().timeout.default;
        Self { session, timeout }
    }

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

    /// Execute the expect operation.
    ///
    /// # Errors
    ///
    /// Returns an error on timeout or EOF.
    pub fn pattern(self, pattern: impl Into<Pattern>) -> Result<Match> {
        self.session.expect_timeout(pattern, self.timeout)
    }
}

/// Run async code synchronously.
///
/// This is a convenience function for running a single async operation
/// without managing a runtime.
///
/// # Errors
///
/// Returns an error if the runtime cannot be created.
pub fn block_on<F, T>(future: F) -> Result<T>
where
    F: std::future::Future<Output = T>,
{
    let runtime = Builder::new_current_thread()
        .enable_all()
        .build()
        .map_err(|e| {
            crate::error::ExpectError::io_context("creating tokio runtime for block_on", e)
        })?;

    Ok(runtime.block_on(future))
}

/// Spawn a session synchronously.
///
/// # Errors
///
/// Returns an error if spawning fails.
pub fn spawn(command: &str, args: &[&str]) -> Result<SyncSession> {
    SyncSession::spawn(command, args)
}

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

    #[test]
    fn block_on_simple() {
        let result = block_on(async { 42 });
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 42);
    }

    #[cfg(unix)]
    #[test]
    fn sync_session_spawn_echo() {
        let mut session =
            SyncSession::spawn("/bin/echo", &["hello"]).expect("Failed to spawn echo");

        // Verify PID is valid
        assert!(session.pid() > 0);

        // Expect the output
        let m = session.expect("hello").expect("Failed to expect hello");
        assert!(m.matched.contains("hello"));
    }
}