diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..e1f75e7 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1 @@ +github: stjepang diff --git a/.github/workflows/build-and-test.yaml b/.github/workflows/build-and-test.yaml new file mode 100644 index 0000000..19d1ebb --- /dev/null +++ b/.github/workflows/build-and-test.yaml @@ -0,0 +1,51 @@ +name: Build and test + +on: + push: + branches: + - master + pull_request: + +jobs: + build_and_test: + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest] + rust: [nightly, beta, stable] + steps: + - uses: actions/checkout@v2 + + - name: Set current week of the year in environnement + if: startsWith(matrix.os, 'ubuntu') || startsWith(matrix.os, 'macOS') + run: echo "::set-env name=CURRENT_WEEK::$(date +%V)" + + - name: Set current week of the year in environnement + if: startsWith(matrix.os, 'windows') + run: echo "::set-env name=CURRENT_WEEK::$(Get-Date -UFormat %V)" + + - name: Install latest ${{ matrix.rust }} + uses: actions-rs/toolchain@v1 + with: + toolchain: ${{ matrix.rust }} + profile: minimal + override: true + + - name: Run cargo check + uses: actions-rs/cargo@v1 + with: + command: check + args: --all --bins --examples --tests --all-features + + - name: Run cargo check (without dev-dependencies to catch missing feature flags) + if: startsWith(matrix.rust, 'nightly') + uses: actions-rs/cargo@v1 + with: + command: check + args: -Z features=dev_dep + + - name: Run cargo test + uses: actions-rs/cargo@v1 + with: + command: test diff --git a/.github/workflows/lint.yaml b/.github/workflows/lint.yaml new file mode 100644 index 0000000..7e9bd98 --- /dev/null +++ b/.github/workflows/lint.yaml @@ -0,0 +1,26 @@ +name: Lint + +on: + push: + branches: + - master + pull_request: + +jobs: + clippy: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + + - name: Set current week of the year in environnement + run: echo "::set-env name=CURRENT_WEEK::$(date +%V)" + + - uses: actions-rs/toolchain@v1 + with: + toolchain: stable + profile: minimal + components: clippy + - uses: actions-rs/clippy-check@v1 + with: + token: ${{ secrets.GITHUB_TOKEN }} + args: --all-features -- -W clippy::all diff --git a/.github/workflows/security.yaml b/.github/workflows/security.yaml new file mode 100644 index 0000000..8f722e7 --- /dev/null +++ b/.github/workflows/security.yaml @@ -0,0 +1,20 @@ +name: Security audit + +on: + push: + branches: + - master + pull_request: + +jobs: + security_audit: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + + - name: Set current week of the year in environnement + run: echo "::set-env name=CURRENT_WEEK::$(date +%V)" + + - uses: actions-rs/audit-check@v1 + with: + token: ${{ secrets.GITHUB_TOKEN }} diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..ad9e8a3 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,3 @@ +# Version 0.1.1 + +- Initial version diff --git a/Cargo.toml b/Cargo.toml index 34711bc..49b7654 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,16 +1,22 @@ [package] name = "async-process" -version = "0.1.0" +version = "0.1.1" authors = ["Stjepan Glavina "] edition = "2018" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +description = "Async interface for working with processes" +license = "Apache-2.0 OR MIT" +repository = "https://github.com/stjepang/async-process" +homepage = "https://github.com/stjepang/async-process" +documentation = "https://docs.rs/async-process" +keywords = ["process", "spawn", "command", "subprocess", "child"] +categories = ["asynchronous", "os"] +readme = "README.md" [dependencies] async-channel = "1.4.0" cfg-if = "0.1.10" -futures-lite = "0.1.11" once_cell = "1.4.1" +futures-lite = "0.1.11" [target.'cfg(unix)'.dependencies] async-io = "0.1.11" @@ -21,13 +27,8 @@ blocking = "0.5.1" [target.'cfg(windows)'.dependencies.winapi] version = "0.3.9" +default-features = false features = [ - "handleapi", - "winerror", - "minwindef", - "processthreadsapi", - "synchapi", - "threadpoollegacyapiset", "winbase", "winnt", ] diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..31aa793 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,23 @@ +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..72cb714 --- /dev/null +++ b/README.md @@ -0,0 +1,71 @@ +# async-process + +[![Build](https://github.com/stjepang/async-process/workflows/Build%20and%20test/badge.svg)]( +https://github.com/stjepang/async-process/actions) +[![License](https://img.shields.io/badge/license-MIT%2FApache--2.0-blue.svg)]( +https://github.com/stjepang/async-process) +[![Cargo](https://img.shields.io/crates/v/async-process.svg)]( +https://crates.io/crates/async-process) +[![Documentation](https://docs.rs/async-process/badge.svg)]( +https://docs.rs/async-process) + +Async interface for working with processes. + +This crate is an async version of `std::process`. + +## Implementation + +A background thread named "async-process" is lazily created on first use, which waits for +spawned child processes to exit and then calls the `wait()` syscall to clean up the "zombie" +processes. This is unlike the `process` API in the standard library, where dropping a running +`Child` leaks its resources. + +This crate uses [`async-io`] for async I/O on Unix-like systems and [`blocking`] for async I/O +on Windows. + +[`async-io`]: https://docs.rs/async-io +[`blocking`]: https://docs.rs/blocking + +## Examples + +Spawn a process and collect its output: + +```rust +use async_process::Command; + +let out = Command::new("echo").arg("hello").arg("world").output().await?; +assert_eq!(out.stdout, b"hello world\n"); +``` + +Read the output line-by-line as it gets produced: + +```rust +use async_process::{Command, Stdio}; +use futures_lite::{AsyncBufReadExt, StreamExt, io::BufReader}; + +let mut child = Command::new("find") + .arg(".") + .stdout(Stdio::piped()) + .spawn()?; + +let mut lines = BufReader::new(child.stdout.take().unwrap()).lines(); + +while let Some(line) = lines.next().await { + println!("{}", line?); +} +``` + +## License + +Licensed under either of + + * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) + * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) + +at your option. + +#### Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in the work by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. diff --git a/examples/foo.rs b/examples/foo.rs deleted file mode 100644 index 94d74ad..0000000 --- a/examples/foo.rs +++ /dev/null @@ -1,29 +0,0 @@ -use std::io; -use std::os::unix::process::ExitStatusExt; - -use async_process::{Command, ExitStatus, Stdio}; -use futures_lite::*; - -fn main() -> io::Result<()> { - future::block_on(async { - // dbg!(std::process::Command::new("ls").arg(".").spawn()?.wait_with_output())?; - - dbg!( - Command::new("ls") - .arg(".") - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .status() - .await - )?; - - // let mut child = Command::new("/bin/sh") - // .arg("-c") - // .arg("kill -9 $$") - // .spawn()?; - // let status = child.status().await?; - // dbg!(status); - - Ok(()) - }) -} diff --git a/src/lib.rs b/src/lib.rs index 8dfc42e..7381af2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,9 +1,59 @@ -//! Async execution and interaction with processes. +//! Async interface for working with processes. +//! +//! This crate is an async version of [`std::process`]. +//! +//! # Implementation +//! +//! A background thread named "async-process" is lazily created on first use, which waits for +//! spawned child processes to exit and then calls the `wait()` syscall to clean up the "zombie" +//! processes. This is unlike the `process` API in the standard library, where dropping a running +//! `Child` leaks its resources. +//! +//! This crate uses [`async-io`] for async I/O on Unix-like systems and [`blocking`] for async I/O +//! on Windows. +//! +//! [`async-io`]: https://docs.rs/async-io +//! [`blocking`]: https://docs.rs/blocking +//! +//! # Examples +//! +//! Spawn a process and collect its output: +//! +//! ```no_run +//! # futures_lite::future::block_on(async { +//! use async_process::Command; +//! +//! let out = Command::new("echo").arg("hello").arg("world").output().await?; +//! assert_eq!(out.stdout, b"hello world\n"); +//! # std::io::Result::Ok(()) }); +//! ``` +//! +//! Read the output line-by-line as it gets produced: +//! +//! ```no_run +//! # futures_lite::future::block_on(async { +//! use async_process::{Command, Stdio}; +//! use futures_lite::{AsyncBufReadExt, StreamExt, io::BufReader}; +//! +//! let mut child = Command::new("find") +//! .arg(".") +//! .stdout(Stdio::piped()) +//! .spawn()?; +//! +//! let mut lines = BufReader::new(child.stdout.take().unwrap()).lines(); +//! +//! while let Some(line) = lines.next().await { +//! println!("{}", line?); +//! } +//! # std::io::Result::Ok(()) }); +//! ``` #![cfg_attr(unix, forbid(unsafe_code))] #![warn(missing_docs, missing_debug_implementations, rust_2018_idioms)] use std::ffi::OsStr; +use std::fmt; +use std::future::Future; use std::path::Path; use std::pin::Pin; use std::sync::{Arc, Mutex}; @@ -15,22 +65,52 @@ use async_channel::{Receiver, Sender}; use async_io::Async; #[cfg(windows)] use blocking::Unblock; -use futures_lite::*; +use futures_lite::{future, io, AsyncReadExt}; use once_cell::sync::Lazy; #[doc(no_inline)] pub use std::process::{ExitStatus, Output, Stdio}; +/// A spawned child process. +/// +/// The process can be in running or exited state. Use [`status()`][`Child::status()`] or +/// [`output()`][`Child::output()`] to wait for it to exit. +/// +/// If the [`Child`] is dropped, the process keeps running in the background. +/// +/// # Examples +/// +/// Spawn a process and wait for it to complete: +/// +/// ```no_run +/// # futures_lite::future::block_on(async { +/// use async_process::Command; +/// +/// Command::new("cp").arg("a.txt").arg("b.txt").status().await?; +/// # std::io::Result::Ok(()) }); +/// ``` pub struct Child { + /// The handle for writing to the child's standard input (stdin), if it has been captured. pub stdin: Option, + + /// The handle for reading from the child's standard output (stdout), if it has been captured. pub stdout: Option, + + /// The handle for reading from the child's standard error (stderr), if it has been captured. pub stderr: Option, + /// The inner handle to the child process. child: Arc>, + + /// A channel that gets closed when the process exits. exited: Receiver<()>, } impl Child { + /// Wraps the inner child process handle and registers it in the global process list. + /// + /// The "async-process" thread waits for processes in the global list and cleans up the + /// resources when they exit. fn new(mut child: std::process::Child) -> io::Result { cfg_if::cfg_if! { if #[cfg(windows)] { @@ -81,12 +161,16 @@ impl Child { } } else if #[cfg(unix)] { + static SIGNALS: Lazy = Lazy::new(|| { + signal_hook::iterator::Signals::new(&[signal_hook::SIGCHLD]) + .expect("cannot set signal handler for SIGCHLD") + }); + + // Make sure the signal handler is registered before interacting with the process. + Lazy::force(&SIGNALS); + // Waits for the next SIGCHLD signal. fn wait_sigchld() { - static SIGNALS: Lazy = Lazy::new(|| { - signal_hook::iterator::Signals::new(&[signal_hook::SIGCHLD]) - .expect("cannot set signal handler for SIGCHLD") - }); SIGNALS.forever().next(); } @@ -149,20 +233,87 @@ impl Child { }) } + /// Returns the OS-assigned process identifier associated with this child. + /// + /// # Examples + /// + /// ```no_run + /// # futures_lite::future::block_on(async { + /// use async_process::Command; + /// + /// let mut child = Command::new("ls").spawn()?; + /// println!("id: {}", child.id()); + /// # std::io::Result::Ok(()) }); + /// ``` pub fn id(&self) -> u32 { self.child.lock().unwrap().id() } + /// Forces the child process to exit. + /// + /// If the child has already exited, an [`InvalidInput`] error is returned. + /// + /// This is equivalent to sending a SIGKILL on Unix platforms. + /// + /// [`InvalidInput`]: `std::io::ErrorKind::InvalidInput` + /// + /// # Examples + /// + /// ```no_run + /// # futures_lite::future::block_on(async { + /// use async_process::Command; + /// + /// let mut child = Command::new("yes").spawn()?; + /// child.kill()?; + /// println!("exit status: {}", child.status().await?); + /// # std::io::Result::Ok(()) }); + /// ``` pub fn kill(&mut self) -> io::Result<()> { self.child.lock().unwrap().kill() } - // NOTE: unlike status(), does not drop stdin + /// Returns the exit status if the process has exited. + /// + /// Unlike [`status()`][`Child::status()`], this method will not drop the stdin handle. + /// + /// # Examples + /// + /// ```no_run + /// # futures_lite::future::block_on(async { + /// use async_process::Command; + /// + /// let mut child = Command::new("ls").spawn()?; + /// + /// match child.try_status()? { + /// None => println!("still running"), + /// Some(status) => println!("exited with: {}", status), + /// } + /// # std::io::Result::Ok(()) }); + /// ``` pub fn try_status(&mut self) -> io::Result> { self.child.lock().unwrap().try_wait() } - // NOTE: drops stdin + /// Drops the stdin handle and waits for the process to exit. + /// + /// Closing the stdin of the process helps avoid deadlocks. It ensures that the process does + /// not block waiting for input from the parent process while the parent waits for the child to + /// exit. + /// + /// # Examples + /// + /// ```no_run + /// # futures_lite::future::block_on(async { + /// use async_process::{Command, Stdio}; + /// + /// let mut child = Command::new("cp") + /// .arg("a.txt") + /// .arg("b.txt") + /// .spawn()?; + /// + /// println!("exit status: {}", child.status().await?); + /// # std::io::Result::Ok(()) }); + /// ``` pub fn status(&mut self) -> impl Future> { self.stdin.take(); let child = self.child.clone(); @@ -174,10 +325,34 @@ impl Child { } } - // NOTE: this closes stdin and drains stdout+stderr + /// Drops the stdin handle and collects the output of the process. + /// + /// Closing the stdin of the process helps avoid deadlocks. It ensures that the process does + /// not block waiting for input from the parent process while the parent waits for the child to + /// exit. + /// + /// In order to capture the output of the process, [`Command::stdout()`] and + /// [`Command::stderr()`] must be configured with [`Stdio::piped()`]. + /// + /// # Examples + /// + /// ```no_run + /// # futures_lite::future::block_on(async { + /// use async_process::{Command, Stdio}; + /// + /// let child = Command::new("ls") + /// .stdout(Stdio::piped()) + /// .stderr(Stdio::piped()) + /// .spawn()?; + /// + /// let out = child.output().await?; + /// # std::io::Result::Ok(()) }); + /// ``` pub fn output(mut self) -> impl Future> { + // A future that waits for the exit status. let status = self.status(); + // A future that collects stdout. let stdout = self.stdout.take(); let stdout = async move { let mut v = Vec::new(); @@ -187,6 +362,7 @@ impl Child { Ok(v) }; + // A future that collects stderr. let stderr = self.stderr.take(); let stderr = async move { let mut v = Vec::new(); @@ -208,12 +384,27 @@ impl Child { } } +impl fmt::Debug for Child { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Child") + .field("stdin", &self.stdin) + .field("stdout", &self.stdout) + .field("stderr", &self.stderr) + .finish() + } +} + +/// A handle to a child process's standard input (stdin). +/// +/// When a [`ChildStdin`] is dropped, the underlying handle gets clossed. If the child process was +/// previously blocked on input, it becomes unblocked after dropping. +#[derive(Debug)] pub struct ChildStdin( #[cfg(windows)] Unblock, #[cfg(unix)] Async, ); -impl AsyncWrite for ChildStdin { +impl io::AsyncWrite for ChildStdin { fn poll_write( mut self: Pin<&mut Self>, cx: &mut Context<'_>, @@ -231,12 +422,16 @@ impl AsyncWrite for ChildStdin { } } +/// A handle to a child process's standard output (stdout). +/// +/// When a [`ChildStdout`] is dropped, the underlying handle gets closed. +#[derive(Debug)] pub struct ChildStdout( #[cfg(windows)] Unblock, #[cfg(unix)] Async, ); -impl AsyncRead for ChildStdout { +impl io::AsyncRead for ChildStdout { fn poll_read( mut self: Pin<&mut Self>, cx: &mut Context<'_>, @@ -246,12 +441,16 @@ impl AsyncRead for ChildStdout { } } +/// A handle to a child process's standard error (stderr). +/// +/// When a [`ChildStderr`] is dropped, the underlying handle gets closed. +#[derive(Debug)] pub struct ChildStderr( #[cfg(windows)] Unblock, #[cfg(unix)] Async, ); -impl AsyncRead for ChildStderr { +impl io::AsyncRead for ChildStderr { fn poll_read( mut self: Pin<&mut Self>, cx: &mut Context<'_>, @@ -261,89 +460,292 @@ impl AsyncRead for ChildStderr { } } -pub struct Command(std::process::Command); +/// A builder for spawning processes. +/// +/// # Examples +/// +/// ```no_run +/// # futures_lite::future::block_on(async { +/// use async_process::Command; +/// +/// let output = if cfg!(target_os = "windows") { +/// Command::new("cmd").args(&["/C", "echo hello"]).output().await? +/// } else { +/// Command::new("sh").arg("-c").arg("echo hello").output().await? +/// }; +/// # std::io::Result::Ok(()) }); +/// ``` +#[derive(Debug)] +pub struct Command { + cmd: std::process::Command, + stdin: Option, + stdout: Option, + stderr: Option, +} impl Command { + /// Constructs a new [`Command`] for launching `program`. + /// + /// The initial configuration (the working directory and environment variables) is inherited + /// from the current process. + /// + /// # Examples + /// + /// ``` + /// use async_process::Command; + /// + /// let mut cmd = Command::new("ls"); + /// ``` pub fn new>(program: S) -> Command { - Command(std::process::Command::new(program)) + Command { + cmd: std::process::Command::new(program), + stdin: None, + stdout: None, + stderr: None, + } } + /// Adds a single argument to pass to the program. + /// + /// # Examples + /// + /// ``` + /// use async_process::Command; + /// + /// let mut cmd = Command::new("echo"); + /// cmd.arg("hello"); + /// cmd.arg("world"); + /// ``` pub fn arg>(&mut self, arg: S) -> &mut Command { - self.0.arg(arg); + self.cmd.arg(arg); self } + /// Adds multiple arguments to pass to the program. + /// + /// # Examples + /// + /// ``` + /// use async_process::Command; + /// + /// let mut cmd = Command::new("echo"); + /// cmd.args(&["hello", "world"]); + /// ``` pub fn args(&mut self, args: I) -> &mut Command where I: IntoIterator, S: AsRef, { - self.0.args(args); + self.cmd.args(args); self } + /// Configures an environment variable for the new process. + /// + /// Note that environment variable names are case-insensitive (but case-preserving) on Windows, + /// and case-sensitive on all other platforms. + /// + /// # Examples + /// + /// ``` + /// use async_process::Command; + /// + /// let mut cmd = Command::new("ls"); + /// cmd.env("PATH", "/bin"); + /// ``` pub fn env(&mut self, key: K, val: V) -> &mut Command where K: AsRef, V: AsRef, { - self.0.env(key, val); + self.cmd.env(key, val); self } + /// Configures multiple environment variables for the new process. + /// + /// Note that environment variable names are case-insensitive (but case-preserving) on Windows, + /// and case-sensitive on all other platforms. + /// + /// # Examples + /// + /// ``` + /// use async_process::Command; + /// + /// let mut cmd = Command::new("ls"); + /// cmd.envs(vec![("PATH", "/bin"), ("TERM", "xterm-256color")]); + /// ``` pub fn envs(&mut self, vars: I) -> &mut Command where I: IntoIterator, K: AsRef, V: AsRef, { - self.0.envs(vars); + self.cmd.envs(vars); self } + /// Removes an environment variable mapping. + /// + /// # Examples + /// + /// ``` + /// use async_process::Command; + /// + /// let mut cmd = Command::new("ls"); + /// cmd.env_remove("PATH"); + /// ``` pub fn env_remove>(&mut self, key: K) -> &mut Command { - self.0.env_remove(key); + self.cmd.env_remove(key); self } + /// Removes all environment variable mappings. + /// + /// # Examples + /// + /// ``` + /// use async_process::Command; + /// + /// let mut cmd = Command::new("ls"); + /// cmd.env_clear(); + /// ``` pub fn env_clear(&mut self) -> &mut Command { - self.0.env_clear(); + self.cmd.env_clear(); self } + /// Configures the working directory for the new process. + /// + /// # Examples + /// + /// ``` + /// use async_process::Command; + /// + /// let mut cmd = Command::new("ls"); + /// cmd.current_dir("/"); + /// ``` pub fn current_dir>(&mut self, dir: P) -> &mut Command { - self.0.current_dir(dir); + self.cmd.current_dir(dir); self } + /// Configures the standard input (stdin) for the new process. + /// + /// # Examples + /// + /// ``` + /// use async_process::{Command, Stdio}; + /// + /// let mut cmd = Command::new("cat"); + /// cmd.stdin(Stdio::null()); + /// ``` pub fn stdin>(&mut self, cfg: T) -> &mut Command { - self.0.stdin(cfg); + self.stdin = Some(cfg.into()); self } + /// Configures the standard output (stdout) for the new process. + /// + /// # Examples + /// + /// ``` + /// use async_process::{Command, Stdio}; + /// + /// let mut cmd = Command::new("ls"); + /// cmd.stdout(Stdio::piped()); + /// ``` pub fn stdout>(&mut self, cfg: T) -> &mut Command { - self.0.stdout(cfg); + self.stdout = Some(cfg.into()); self } + /// Configures the standard error (stderr) for the new process. + /// + /// # Examples + /// + /// ``` + /// use async_process::{Command, Stdio}; + /// + /// let mut cmd = Command::new("ls"); + /// cmd.stderr(Stdio::piped()); + /// ``` pub fn stderr>(&mut self, cfg: T) -> &mut Command { - self.0.stderr(cfg); + self.stderr = Some(cfg.into()); self } + /// Executes the command and returns the [`Child`] handle to it. + /// + /// If not configured, stdin, stdout and stderr will be set to [`Stdio::inherit()`]. + /// + /// After spawning the process, stdin, stdout, and stderr become unconfigured again. + /// + /// # Examples + /// + /// ```no_run + /// # futures_lite::future::block_on(async { + /// use async_process::Command; + /// + /// let child = Command::new("ls").spawn()?; + /// # std::io::Result::Ok(()) }); + /// ``` pub fn spawn(&mut self) -> io::Result { - Child::new(self.0.spawn()?) + let (stdin, stdout, stderr) = (self.stdin.take(), self.stdout.take(), self.stderr.take()); + self.cmd.stdin(stdin.unwrap_or(Stdio::inherit())); + self.cmd.stdout(stdout.unwrap_or(Stdio::inherit())); + self.cmd.stderr(stderr.unwrap_or(Stdio::inherit())); + + Child::new(self.cmd.spawn()?) } + /// Executes the command, waits for it to exit, and returns the exit status. + /// + /// If not configured, stdin, stdout and stderr will be set to [`Stdio::inherit()`]. + /// + /// After spawning the process, stdin, stdout, and stderr become unconfigured again. + /// + /// # Examples + /// + /// ```no_run + /// # futures_lite::future::block_on(async { + /// use async_process::Command; + /// + /// let status = Command::new("cp") + /// .arg("a.txt") + /// .arg("b.txt") + /// .status() + /// .await?; + /// # std::io::Result::Ok(()) }); + /// ``` pub fn status(&mut self) -> impl Future> { let child = self.spawn(); async { child?.status().await } } + /// Executes the command and collects its output. + /// + /// If not configured, stdin will be set to [`Stdio::null()`], and stdout and stderr will be + /// set to [`Stdio::piped()`]. + /// + /// After spawning the process, stdin, stdout, and stderr become unconfigured again. + /// + /// # Examples + /// + /// ```no_run + /// # futures_lite::future::block_on(async { + /// use async_process::Command; + /// + /// let child = Command::new("ls").spawn()?; + /// # std::io::Result::Ok(()) }); + /// ``` pub fn output(&mut self) -> impl Future> { - self.0.stdout(Stdio::piped()); - self.0.stderr(Stdio::piped()); - let child = self.spawn(); - async { child?.output().await } + let (stdin, stdout, stderr) = (self.stdin.take(), self.stdout.take(), self.stderr.take()); + self.cmd.stdin(stdin.unwrap_or(Stdio::null())); + self.cmd.stdout(stdout.unwrap_or(Stdio::piped())); + self.cmd.stderr(stderr.unwrap_or(Stdio::piped())); + + let child = self.cmd.spawn(); + async { Child::new(child?)?.output().await } } } diff --git a/tests/process.rs b/tests/std.rs similarity index 99% rename from tests/process.rs rename to tests/std.rs index 0d457ec..913fb50 100644 --- a/tests/process.rs +++ b/tests/std.rs @@ -1,3 +1,5 @@ +//! These tests are borrowed from the `std::process` test suite. + use std::env; use std::str;