|
| 1 | +/* |
| 2 | + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 3 | + * SPDX-License-Identifier: Apache-2.0. |
| 4 | + */ |
| 5 | + |
| 6 | +//! Module for interacting with Cargo. |
| 7 | +
|
| 8 | +use anyhow::{Context, Result}; |
| 9 | +use std::path::{Path, PathBuf}; |
| 10 | +use std::process::{Command, Output}; |
| 11 | + |
| 12 | +macro_rules! cmd { |
| 13 | + [ $( $x:expr ),* ] => { |
| 14 | + { |
| 15 | + let mut cmd = Cmd::new(); |
| 16 | + $(cmd.push($x);)* |
| 17 | + cmd |
| 18 | + } |
| 19 | + }; |
| 20 | +} |
| 21 | + |
| 22 | +/// Confirms that cargo exists on the path. |
| 23 | +pub async fn confirm_installed_on_path() -> Result<()> { |
| 24 | + cmd!["cargo", "--version"] |
| 25 | + .spawn() |
| 26 | + .await |
| 27 | + .context("cargo is not installed on the PATH")?; |
| 28 | + Ok(()) |
| 29 | +} |
| 30 | + |
| 31 | +/// Returns a `Cmd` that, when spawned, will asynchronously run `cargo publish` in the given crate path. |
| 32 | +pub fn publish_task(crate_path: &Path) -> Cmd { |
| 33 | + cmd!["cargo", "publish"].working_dir(crate_path) |
| 34 | +} |
| 35 | + |
| 36 | +#[derive(Default)] |
| 37 | +pub struct Cmd { |
| 38 | + parts: Vec<String>, |
| 39 | + working_dir: Option<PathBuf>, |
| 40 | +} |
| 41 | + |
| 42 | +impl Cmd { |
| 43 | + fn new() -> Cmd { |
| 44 | + Default::default() |
| 45 | + } |
| 46 | + |
| 47 | + fn push(&mut self, part: impl Into<String>) { |
| 48 | + self.parts.push(part.into()); |
| 49 | + } |
| 50 | + |
| 51 | + fn working_dir(mut self, working_dir: impl AsRef<Path>) -> Self { |
| 52 | + self.working_dir = Some(working_dir.as_ref().into()); |
| 53 | + self |
| 54 | + } |
| 55 | + |
| 56 | + /// Returns a plan string that can be output to the user to describe the command. |
| 57 | + pub fn plan(&self) -> String { |
| 58 | + let mut plan = String::new(); |
| 59 | + if let Some(working_dir) = &self.working_dir { |
| 60 | + plan.push_str(&format!("[in {:?}]: ", working_dir)); |
| 61 | + } |
| 62 | + plan.push_str(&self.parts.join(" ")); |
| 63 | + plan |
| 64 | + } |
| 65 | + |
| 66 | + /// Runs the command asynchronously. |
| 67 | + pub async fn spawn(mut self) -> Result<Output> { |
| 68 | + let working_dir = self |
| 69 | + .working_dir |
| 70 | + .take() |
| 71 | + .unwrap_or_else(|| std::env::current_dir().unwrap()); |
| 72 | + let mut command: Command = self.into(); |
| 73 | + tokio::task::spawn_blocking(move || Ok(command.current_dir(working_dir).output()?)).await? |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +impl From<Cmd> for Command { |
| 78 | + fn from(cmd: Cmd) -> Self { |
| 79 | + assert!(!cmd.parts.is_empty()); |
| 80 | + let mut command = Command::new(&cmd.parts[0]); |
| 81 | + for i in 1..cmd.parts.len() { |
| 82 | + command.arg(&cmd.parts[i]); |
| 83 | + } |
| 84 | + command |
| 85 | + } |
| 86 | +} |
0 commit comments