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
//! This crate provides an abstraction over [`Command`] with manual `npm` commands
//! in a simple and easy package with fluent API.
//!
//! `npm_rs` exposes [NpmEnv] to configure the npm execution enviroment and
//! [Npm] to use said enviroment to execute npm commands.
//!
//! # Example
//! ```no_run
//! use npm_rs::*;
//!
//! let exit_status = NpmEnv::default()
//!        .with_env("NODE_ENV", "production")
//!        .init()
//!        .install(None)
//!        .run("build")
//!        .exec()?;
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! [NpmEnv] implements [`Clone`] while running under a nightly toolchain
//! and with the feature `nightly` is enabled.
//! ```ignore
//! // Cargo.toml
//!
//! [dev.dependencies]
//! npm_rs = { version = "0.1", features = ["nightly"] }
//! ```

#![cfg_attr(feature = "nightly", feature(command_access))]
use std::{
    ffi::OsStr,
    path::Path,
    process::{Command, ExitStatus},
};

use cfg_if::cfg_if;

cfg_if! {
    if #[cfg(target_family = "windows")] {
        const CMD: &str = "cmd.exe";
        const OPT: &str = "/C";
    } else {
        const CMD: &str = "bash";
        const OPT: &str = "-c";
    }
}

const NPM: &str = "npm";
const NPM_INIT: &str = "init";
const NPM_INSTALL: &str = "install";
const NPM_UNINSTALL: &str = "uninstall";
const NPM_UPDATE: &str = "update";
const NPM_RUN: &str = "run";

/// This struct is used to create the enviroment in which npm will execute commands.
/// `NpmEnv` uses [`Command`] so it takes all the env variables in your system.
///
/// After the environment is configured, use [`NpmEnv::init()`] to start issuing commands to [`Npm`].
/// # Example
/// ```no_run
/// use npm_rs::*;
///
/// let npm = NpmEnv::default()
///                  .with_env("NODE_ENV", "production")
///                  .init();
/// ```
pub struct NpmEnv(Command);

/// This struct is used to execute npm commands.
/// Can be created from [`NpmEnv`] of using [`Default`].
///
/// After queuing the desired commands, use [`Npm::exec()`] to execute them.
/// # Example
/// ```no_run
/// use npm_rs::*;
///
/// Npm::default().install(Some(&["tailwindcss"])).exec()?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub struct Npm {
    cmd: Command,
    args: Vec<String>,
}

impl Default for NpmEnv {
    fn default() -> Self {
        let mut cmd = Command::new(CMD);
        cmd.arg(OPT);
        cmd.current_dir(std::env::current_dir().unwrap());

        Self(cmd)
    }
}

#[cfg(feature = "nightly")]
impl Clone for NpmEnv {
    fn clone(&self) -> Self {
        let mut cmd = Command::new(self.0.get_program());
        cmd.args(self.0.get_args());
        cmd.current_dir(self.0.get_current_dir().unwrap());

        Self(cmd)
    }
}

impl NpmEnv {
    /// Inserts or updates a enviroment variable mapping.
    pub fn with_env<K, V>(mut self, key: K, val: V) -> Self
    where
        K: AsRef<OsStr>,
        V: AsRef<OsStr>,
    {
        self.0.env(key, val);
        self
    }

    /// Inserts or updates multiple environment variable mappings.
    pub fn with_envs<I, K, V>(mut self, vars: I) -> Self
    where
        I: IntoIterator<Item = (K, V)>,
        K: AsRef<OsStr>,
        V: AsRef<OsStr>,
    {
        self.0.envs(vars);
        self
    }

    /// Clears the entire environment map for [`Npm`].
    pub fn clear_envs(mut self) -> Self {
        self.0.env_clear();
        self
    }

    /// Removes an enviroment variable mapping.
    pub fn remove_env<K>(mut self, key: K) -> Self
    where
        K: AsRef<OsStr>,
    {
        self.0.env_remove(key);
        self
    }

    /// Sets the working directory for [`Npm`].
    pub fn set_path<P>(mut self, path: P) -> Self
    where
        P: AsRef<Path>,
    {
        self.0.current_dir(path);
        self
    }

    /// Initilizes [`Npm`] with the configured environment.
    ///
    /// This method will be `NpmEnv::init(&self)` when [`Command`] derives [`Clone`].
    pub fn init(self) -> Npm {
        Npm {
            cmd: self.0,
            args: Default::default(),
        }
    }
}

impl Default for Npm {
    fn default() -> Self {
        NpmEnv::default().init()
    }
}

impl Npm {
    fn npm_append(&mut self, npm_cmd: &str, chain: &[&str]) {
        self.args.push(
            [NPM, npm_cmd]
                .iter()
                .chain(chain)
                .copied()
                .collect::<Vec<_>>()
                .join(" "),
        );
    }

    /// Same behaviour as [npm-init -y](https://docs.npmjs.com/cli/v7/commands/npm-init#yes).
    /// Initializes a package, creating a `package.json` file with the default template.
    pub fn init(mut self) -> Self {
        self.npm_append(NPM_INIT, &["-y"]);
        self
    }

    /// Same behaviour as [npm-install](https://docs.npmjs.com/cli/v7/commands/npm-install).
    /// - If `args =`[`None`]: Installs all the dependencies listed in `package.json` into the local `node_modules` folder.
    /// - If `args =`[`Some`]: Installs any package in `args` into the local `node_modules` folder.
    pub fn install(mut self, args: Option<&[&str]>) -> Self {
        self.npm_append(NPM_INSTALL, args.unwrap_or_default());
        self
    }

    /// Same behaviour as [npm-uninstall](https://docs.npmjs.com/cli/v7/commands/npm-uninstall).
    /// Uninstalls the given packages in `pkg`.
    pub fn uninstall(mut self, pkg: &[&str]) -> Self {
        self.npm_append(NPM_UNINSTALL, pkg);
        self
    }

    /// Same behaviour as [npm-update](https://docs.npmjs.com/cli/v7/commands/npm-update).
    /// - If `args =`[`None`]: Updates all the local dependencies (local `node_modules` folder).
    /// - If `args =`[`Some`]: Updates any package in `pkg`.
    pub fn update(mut self, pkg: Option<&[&str]>) -> Self {
        self.npm_append(NPM_UPDATE, pkg.unwrap_or_default());
        self
    }

    /// Same behaviour as [npm-run-script](https://docs.npmjs.com/cli/v7/commands/npm-run-script).
    /// Runs an arbitrary `command` from `package.json`'s "scripts" object.
    pub fn run(mut self, command: &str) -> Self {
        self.args.push([NPM, NPM_RUN, command].join(" "));
        self
    }

    /// Runs a custom npm command.
    ///
    /// # Arguments
    /// - `command`: command to execute.
    /// - `args`: arguments of `command`.
    ///
    /// # Example
    /// ```no_run
    /// use npm_rs::*;
    ///
    /// Npm::default().custom("audit", None).exec()?; // Equivalent to `npm audit`.
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn custom(mut self, command: &str, args: Option<&[&str]>) -> Self {
        self.npm_append(command, args.unwrap_or_default());
        self
    }

    /// Executes all the commands in the invokation order used, waiting for its completion status.
    ///
    /// # Example
    /// ```no_run
    /// use npm_rs::*;
    ///
    /// let status = Npm::default().install(None).run("build").exec()?; // Executes npm install && npm run build.
    /// assert!(status.success()); // Will `panic` if not completed successfully.
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn exec(mut self) -> Result<ExitStatus, std::io::Error> {
        self.cmd.arg(self.args.join(" && "));
        self.cmd.status()
    }
}