sublime_standard_tools 0.0.15

A collection of utilities for working with Node.js projects from Rust applications
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
//! # Command Types Definitions
//!
//! ## What
//! This file defines the core types used throughout the command module, including
//! command configurations, execution interfaces, output structures, and queue
//! management types. These types form the foundation for the command execution system.
//!
//! ## How
//! The types are organized into several categories:
//! - Command representation (`Command`, `CommandBuilder`)
//! - Command execution (`CommandExecutor`, `DefaultCommandExecutor`)
//! - Output handling (`CommandOutput`, `StreamOutput`)
//! - Queue management (`CommandQueue`, `QueuedCommand`, `CommandStatus`)
//! - Stream handling (`CommandStream`, `StreamConfig`)
//!
//! ## Why
//! A well-defined type system enables clear separation of concerns and ensures
//! type safety throughout the command execution and management process. These
//! types establish the contracts between different components of the system and
//! provide the necessary abstractions for flexible command processing.

use std::{process::Stdio, time::Instant};

use crate::error::{CommandError, Error, Result};

use tokio::{
    process::{Child, Command},
    time::timeout,
};

use super::types::{
    Command as CmdConfig, CommandOutput, CommandStream, DefaultCommandExecutor,
    GlobalExecutorState, SharedSyncExecutor, StreamConfig, SyncCommandExecutor,
};
use crate::config::CommandConfig;

/// Trait for executing commands with various options.
///
/// This trait defines the contract for command executors, allowing
/// for both synchronous execution with full output capture and
/// streaming execution with real-time output access.
///
/// # Examples
///
/// ```ignore
/// // This example demonstrates implementing the Executor trait
/// use sublime_standard_tools::command::{Executor, Command, CommandOutput};
/// use sublime_standard_tools::error::Result;
///
/// struct MyExecutor;
///
/// #[async_trait::async_trait]
/// impl Executor for MyExecutor {
///     async fn execute(&self, command: Command) -> Result<CommandOutput> {
///         // Implementation here
///         unimplemented!()
///     }
///     // ...
/// }
/// ```
#[async_trait::async_trait]
pub trait Executor: Send + Sync {
    /// Executes a command and returns its output.
    ///
    /// # Arguments
    ///
    /// * `command` - The command to execute
    ///
    /// # Returns
    ///
    /// * `Ok(CommandOutput)` - If the command executed successfully
    ///
    /// # Errors
    ///
    /// Returns an error if the command fails to execute or times out.
    /// * `Err(Error)` - If the command failed to execute
    async fn execute(&self, command: CmdConfig) -> Result<CommandOutput>;

    /// Executes a command and returns a stream of its output.
    ///
    /// # Arguments
    ///
    /// * `command` - The command to execute
    /// * `stream_config` - Configuration for the output stream
    ///
    /// # Returns
    ///
    /// * `Ok((CommandStream, Child))` - If the command was started successfully
    ///
    /// # Errors
    ///
    /// Returns an error if the command fails to start.
    /// * `Err(Error)` - If the command failed to start
    async fn execute_stream(
        &self,
        command: CmdConfig,
        stream_config: StreamConfig,
    ) -> Result<(CommandStream, Child)>;
}

impl DefaultCommandExecutor {
    /// Creates a new `DefaultCommandExecutor` with default configuration.
    ///
    /// # Returns
    ///
    /// A new executor instance using default command configuration
    ///
    /// # Examples
    ///
    /// ```
    /// use sublime_standard_tools::command::DefaultCommandExecutor;
    ///
    /// let executor = DefaultCommandExecutor::new();
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self { config: CommandConfig::default() }
    }

    /// Creates a new `DefaultCommandExecutor` with custom configuration.
    ///
    /// # Arguments
    ///
    /// * `config` - The command configuration to use
    ///
    /// # Returns
    ///
    /// A new executor instance using the provided configuration
    ///
    /// # Examples
    ///
    /// ```
    /// use sublime_standard_tools::command::DefaultCommandExecutor;
    /// use sublime_standard_tools::config::CommandConfig;
    /// use std::time::Duration;
    ///
    /// let config = CommandConfig {
    ///     default_timeout: Duration::from_secs(120),
    ///     ..CommandConfig::default()
    /// };
    /// let executor = DefaultCommandExecutor::new_with_config(config);
    /// ```
    #[must_use]
    pub fn new_with_config(config: CommandConfig) -> Self {
        Self { config }
    }

    /// Gets the current command configuration.
    ///
    /// # Returns
    ///
    /// A reference to the command configuration
    #[must_use]
    pub fn config(&self) -> &CommandConfig {
        &self.config
    }

    /// Builds a tokio Command from our command configuration.
    ///
    /// On Windows, commands are wrapped with `cmd /C` to enable proper resolution
    /// of `.cmd` and `.bat` scripts (like npm, npx, yarn, pnpm) through PATHEXT.
    /// On Unix systems, commands are executed directly.
    ///
    /// # Arguments
    ///
    /// * `config` - The command configuration
    ///
    /// # Returns
    ///
    /// A tokio `Command` configured based on the inputs
    ///
    /// # Examples
    ///
    /// ```ignore
    /// // build_command is a private method
    /// use sublime_standard_tools::command::{DefaultCommandExecutor, Command};
    ///
    /// let config = Command {
    ///     program: "echo".to_string(),
    ///     args: vec!["hello".to_string()],
    ///     env: std::collections::HashMap::new(),
    ///     current_dir: None,
    ///     timeout: Some(std::time::Duration::from_secs(5)),
    /// };
    ///
    /// let tokio_cmd = DefaultCommandExecutor::build_command(&config);
    /// ```
    fn build_command(config: &CmdConfig) -> Command {
        // On Windows, we need to wrap commands with cmd /C to properly resolve
        // .cmd and .bat scripts (npm, npx, yarn, pnpm are all .cmd files).
        // Without this, Command::new("npm") fails because Windows doesn't
        // resolve PATHEXT extensions when spawning processes directly.
        #[cfg(target_os = "windows")]
        let mut cmd = {
            let mut cmd = Command::new("cmd");
            cmd.arg("/C").arg(&config.program);
            cmd.args(&config.args);
            cmd
        };

        #[cfg(not(target_os = "windows"))]
        let mut cmd = {
            let mut cmd = Command::new(&config.program);
            cmd.args(&config.args);
            cmd
        };

        cmd.envs(&config.env).stdout(Stdio::piped()).stderr(Stdio::piped());

        if let Some(dir) = &config.current_dir {
            cmd.current_dir(dir);
        }

        cmd
    }
}

#[async_trait::async_trait]
impl Executor for DefaultCommandExecutor {
    /// Executes a command and returns its complete output.
    ///
    /// This method spawns the command, waits for it to complete with
    /// a timeout, and returns its output including stdout, stderr,
    /// exit code, and execution duration.
    ///
    /// # Arguments
    ///
    /// * `command` - The command to execute
    ///
    /// # Returns
    ///
    /// * `Ok(CommandOutput)` - Command output if successful
    ///
    /// # Errors
    ///
    /// Returns an error if the command fails to execute, times out, or returns a non-zero exit code.
    /// * `Err(Error)` - If the command failed to execute
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use sublime_standard_tools::command::{DefaultCommandExecutor, Executor, CommandBuilder};
    /// use sublime_standard_tools::error::Result;
    ///
    /// # async fn example() -> Result<()> {
    /// let executor = DefaultCommandExecutor::new();
    ///
    /// let cmd = CommandBuilder::new("echo")
    ///     .arg("Hello, world!")
    ///     .timeout(std::time::Duration::from_secs(5))
    ///     .build();
    ///
    /// let output = executor.execute(cmd).await?;
    /// println!("Command output: {}", output.stdout());
    /// # Ok(())
    /// # }
    /// ```
    async fn execute(&self, command: CmdConfig) -> Result<CommandOutput> {
        let start_time = Instant::now();
        let mut cmd = Self::build_command(&command);
        let cmd_str = command.program.clone(); // For error reporting

        let timeout_duration = command.timeout.unwrap_or(self.config.default_timeout);
        let child = cmd.spawn().map_err(|e| {
            Error::Command(CommandError::SpawnFailed {
                cmd: cmd_str.clone(),
                message: e.to_string(),
            })
        })?;

        // Get PID before potentially consuming child with wait_with_output
        let child_pid = child.id();

        // Wait for completion with timeout
        let output_result = timeout(timeout_duration, child.wait_with_output()).await;

        let output = match output_result {
            Ok(Ok(output)) => output,
            Ok(Err(e)) => {
                return Err(Error::Command(CommandError::ExecutionFailed {
                    cmd: cmd_str,
                    message: e.to_string(),
                }));
            }
            Err(_) => {
                // Timeout elapsed
                if let Some(pid) = child_pid {
                    log::warn!(
                        "Process (PID: {pid}) timed out after {timeout_duration:?}. Manual cleanup might be required."
                    );
                } else {
                    log::warn!(
                        "Process timed out after {timeout_duration:?}, but PID was unavailable."
                    );
                }
                return Err(Error::Command(CommandError::Timeout { duration: timeout_duration }));
            }
        };

        let duration = start_time.elapsed();
        let code = output.status.code();
        let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
        let stderr = String::from_utf8_lossy(&output.stderr).into_owned();

        if !output.status.success() {
            return Err(Error::Command(CommandError::NonZeroExitCode {
                cmd: cmd_str,
                code,
                stderr,
            }));
        }

        Ok(CommandOutput::new(code.unwrap_or(0), stdout, stderr, duration))
    }

    /// Executes a command and provides a stream of its output.
    ///
    /// This method spawns the command and returns a stream that allows
    /// reading stdout and stderr lines as they are produced, rather than
    /// waiting for the command to complete.
    ///
    /// # Arguments
    ///
    /// * `command` - The command to execute
    /// * `stream_config` - Configuration for the output stream
    ///
    /// # Returns
    ///
    /// * `Ok((CommandStream, Child))` - The output stream and process handle
    ///
    /// # Errors
    ///
    /// Returns an error if the command fails to start or if stdout/stderr cannot be captured.
    /// * `Err(Error)` - If the command failed to start
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use sublime_standard_tools::command::{DefaultCommandExecutor, Executor, CommandBuilder, StreamConfig};
    /// use std::time::Duration;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let executor = DefaultCommandExecutor::new();
    /// let config = StreamConfig::default();
    ///
    /// let cmd = CommandBuilder::new("ls")
    ///     .arg("-la")
    ///     .build();
    ///
    /// let (mut stream, mut child) = executor.execute_stream(cmd, config).await?;
    ///
    /// // Read output lines as they arrive
    /// while let Ok(Some(output)) = stream.next_timeout(Duration::from_secs(1)).await {
    ///     println!("Got: {:?}", output);
    /// }
    ///
    /// // Wait for the process to complete
    /// let status = child.wait().await?;
    /// println!("Process exited with: {}", status);
    /// # Ok(())
    /// # }
    /// ```
    async fn execute_stream(
        &self,
        command: CmdConfig,
        stream_config: StreamConfig,
    ) -> Result<(CommandStream, Child)> {
        let mut cmd = Self::build_command(&command);
        let cmd_str = command.program.clone(); // For error reporting

        let mut child = cmd.spawn().map_err(|e| {
            Error::Command(CommandError::SpawnFailed { cmd: cmd_str, message: e.to_string() })
        })?;

        let stdout = child
            .stdout
            .take()
            .ok_or(Error::Command(CommandError::CaptureFailed { stream: "stdout".to_string() }))?;
        let stderr = child
            .stderr
            .take()
            .ok_or(Error::Command(CommandError::CaptureFailed { stream: "stderr".to_string() }))?;

        let stream = CommandStream::new(stdout, stderr, &stream_config);

        Ok((stream, child)) // Return the child process handle along with the stream
    }
}

/// Implementation for synchronous command executor
impl SyncCommandExecutor {
    /// Create a new synchronous command executor with default configuration
    ///
    /// Creates a dedicated Tokio runtime for async operations.
    /// This runtime is isolated and doesn't interfere with other
    /// async contexts in the application.
    ///
    /// # Returns
    ///
    /// A new synchronous command executor with default configuration.
    ///
    /// # Errors
    ///
    /// Returns an error if the Tokio runtime cannot be created.
    pub fn new() -> Result<Self> {
        let runtime =
            tokio::runtime::Builder::new_multi_thread().enable_all().build().map_err(|e| {
                Error::Command(CommandError::Generic(format!(
                    "Failed to create runtime for sync executor: {e}"
                )))
            })?;

        Ok(Self { runtime, executor: DefaultCommandExecutor::new() })
    }

    /// Create a new synchronous command executor with custom configuration
    ///
    /// Creates a dedicated Tokio runtime for async operations using the
    /// provided command configuration for timeout and execution settings.
    ///
    /// # Arguments
    ///
    /// * `config` - The command configuration to use
    ///
    /// # Returns
    ///
    /// A new synchronous command executor with the provided configuration.
    ///
    /// # Errors
    ///
    /// Returns an error if the Tokio runtime cannot be created.
    pub fn new_with_config(config: CommandConfig) -> Result<Self> {
        let runtime =
            tokio::runtime::Builder::new_multi_thread().enable_all().build().map_err(|e| {
                Error::Command(CommandError::Generic(format!(
                    "Failed to create runtime for sync executor: {e}"
                )))
            })?;

        Ok(Self { runtime, executor: DefaultCommandExecutor::new_with_config(config) })
    }

    /// Execute a command synchronously
    ///
    /// Executes the command using the underlying async executor
    /// but blocks until completion, providing a synchronous interface.
    ///
    /// # Arguments
    ///
    /// * `command` - Command to execute
    ///
    /// # Returns
    ///
    /// Command output with stdout, stderr, and exit status.
    ///
    /// # Errors
    ///
    /// Returns an error if command execution fails.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use sublime_standard_tools::command::{SyncCommandExecutor, CommandBuilder};
    /// use sublime_standard_tools::error::Result;
    ///
    /// # fn example() -> Result<()> {
    /// let executor = SyncCommandExecutor::new()?;
    /// let command = CommandBuilder::new("echo").arg("Hello").build();
    /// let output = executor.execute_sync(command)?;
    ///
    /// if output.status() == 0 {
    ///     println!("Output: {}", output.stdout());
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn execute_sync(&self, command: CmdConfig) -> Result<CommandOutput> {
        self.runtime.block_on(self.executor.execute(command))
    }

    /// Execute a command synchronously with timeout
    ///
    /// Similar to `execute_sync` but with an explicit timeout.
    /// The command will be terminated if it exceeds the timeout.
    ///
    /// # Arguments
    ///
    /// * `command` - Command to execute
    /// * `timeout` - Maximum execution time
    ///
    /// # Returns
    ///
    /// Command output or timeout error.
    ///
    /// # Errors
    ///
    /// Returns an error if command execution fails or times out.
    pub fn execute_sync_with_timeout(
        &self,
        command: CmdConfig,
        timeout: std::time::Duration,
    ) -> Result<CommandOutput> {
        self.runtime.block_on(async {
            tokio::time::timeout(timeout, self.executor.execute(command))
                .await
                .map_err(|_| Error::Command(CommandError::Timeout { duration: timeout }))?
        })
    }

    /// Get runtime handle for advanced usage
    ///
    /// Provides access to the underlying runtime handle for cases
    /// where manual async/sync bridging is needed.
    ///
    /// # Returns
    ///
    /// Handle to the underlying Tokio runtime.
    pub fn runtime_handle(&self) -> tokio::runtime::Handle {
        self.runtime.handle().clone()
    }
}

/// We cannot implement Default for SyncCommandExecutor following NUNCA rules
/// because runtime creation can fail and Default trait cannot return errors.
/// Use SyncCommandExecutor::new() instead for proper error handling.
///
/// This implementation has been removed to enforce proper error handling patterns.
///
/// We cannot implement Clone for SyncCommandExecutor following NUNCA rules
/// because runtime creation can fail and Clone trait cannot return errors.
/// Use SyncCommandExecutor::new() instead for proper error handling.
///
/// This implementation has been removed to enforce proper error handling patterns.
///
/// Implementation for shared synchronous executor
impl SharedSyncExecutor {
    /// Get the shared synchronous executor instance with default configuration
    ///
    /// Creates the shared instance on first access using default configuration.
    /// This method properly handles creation errors and returns them instead of
    /// panicking. This follows the NUNCA rules - errors are handled, never
    /// ignored with panics or unsafe code.
    ///
    /// # Returns
    ///
    /// Shared synchronous command executor or creation error.
    ///
    /// # Errors
    ///
    /// Returns an error if the underlying SyncCommandExecutor cannot be created.
    pub fn try_instance() -> Result<&'static SharedSyncExecutor> {
        Self::try_instance_with_config(CommandConfig::default())
    }

    /// Get the shared synchronous executor instance with custom configuration
    ///
    /// Creates the shared instance on first access using the provided configuration.
    /// This method properly handles creation errors and returns them instead of
    /// panicking. This follows the NUNCA rules - errors are handled, never
    /// ignored with panics or unsafe code.
    ///
    /// # Arguments
    ///
    /// * `config` - The command configuration to use for the shared instance
    ///
    /// # Returns
    ///
    /// Shared synchronous command executor or creation error.
    ///
    /// # Errors
    ///
    /// Returns an error if the underlying SyncCommandExecutor cannot be created.
    pub fn try_instance_with_config(config: CommandConfig) -> Result<&'static SharedSyncExecutor> {
        use std::sync::{Arc, Mutex, OnceLock};

        // Use a global state that stores either success or error
        static GLOBAL_STATE: OnceLock<Mutex<GlobalExecutorState>> = OnceLock::new();

        let state_lock =
            GLOBAL_STATE.get_or_init(|| Mutex::new(GlobalExecutorState::Uninitialized));

        let mut guard = state_lock.lock().map_err(|_| {
            Error::Command(crate::error::CommandError::Generic(
                "Failed to acquire lock for shared sync executor".to_string(),
            ))
        })?;

        match &*guard {
            GlobalExecutorState::Success(executor) => Ok(executor),
            GlobalExecutorState::Error(error) => Err(error.clone()),
            GlobalExecutorState::Uninitialized => {
                // First access - try to create the instance with provided config
                match SyncCommandExecutor::new_with_config(config) {
                    Ok(sync_executor) => {
                        let shared_executor =
                            SharedSyncExecutor { executor: Arc::new(sync_executor) };

                        // Store the success state
                        *guard = GlobalExecutorState::Success(Box::leak(Box::new(shared_executor)));

                        // Return the reference
                        if let GlobalExecutorState::Success(executor) = &*guard {
                            Ok(executor)
                        } else {
                            // This should never happen, but handle it gracefully
                            Err(Error::Command(crate::error::CommandError::Generic(
                                "Internal state corruption in shared sync executor".to_string(),
                            )))
                        }
                    }
                    Err(e) => {
                        // Store the error for future calls
                        *guard = GlobalExecutorState::Error(e.clone());
                        Err(e)
                    }
                }
            }
        }
    }

    /// Get the shared synchronous executor instance (DEPRECATED)
    ///
    /// This method has been removed following NUNCA rules - no panics allowed.
    /// Use `try_instance()` instead for proper error handling.
    ///
    /// This method has been removed to enforce proper error handling patterns.
    ///
    /// Execute a command using the shared executor
    ///
    /// Convenience method for executing commands with the shared instance.
    ///
    /// # Arguments
    ///
    /// * `command` - Command to execute
    ///
    /// # Returns
    ///
    /// Command output.
    ///
    /// # Errors
    ///
    /// Returns an error if command execution fails.
    pub fn execute(&self, command: CmdConfig) -> Result<CommandOutput> {
        self.executor.execute_sync(command)
    }

    /// Execute a command with timeout using the shared executor
    ///
    /// # Arguments
    ///
    /// * `command` - Command to execute
    /// * `timeout` - Maximum execution time
    ///
    /// # Returns
    ///
    /// Command output or timeout error.
    ///
    /// # Errors
    ///
    /// Returns an error if command execution fails or times out.
    pub fn execute_with_timeout(
        &self,
        command: CmdConfig,
        timeout: std::time::Duration,
    ) -> Result<CommandOutput> {
        self.executor.execute_sync_with_timeout(command, timeout)
    }
}