use std::path::Path;
use std::process::Stdio;
use std::str;
use std::sync::Arc;
use anyhow::{Context, Result, anyhow};
use prek_consts::env_vars::EnvVars;
use prek_consts::prepend_paths;
use semver::Version;
use tracing::debug;
use url::Url;
use crate::cli::reporter::HookInstallReporter;
use crate::cli::run::HookRunReporter;
use crate::hook::InstalledHook;
use crate::hook::{Hook, InstallInfo};
use crate::languages::LanguageBackend;
use crate::languages::node::NodeRequest;
use crate::languages::node::installer::{NodeInstaller, bin_dir, lib_dir, query_node_version};
use crate::languages::node::version::EXTRA_KEY_LTS;
use crate::process::Cmd;
use crate::run::run_by_batch;
use crate::store::{CacheBucket, Store, ToolBucket};
#[derive(Debug, Copy, Clone)]
pub(crate) struct Node;
const NPM_CONFIG_PREFIX_ENV: &str = "npm_config_prefix";
const NPM_CONFIG_CACHE_ENV: &str = "npm_config_cache";
const NPM_CONFIG_ENVS_TO_REMOVE: &[&str] = &[
"NPM_CONFIG_PREFIX",
"npm_config_prefix",
"NPM_CONFIG_GLOBAL_PREFIX",
"npm_config_global_prefix",
"NPM_CONFIG_LOCAL_PREFIX",
"npm_config_local_prefix",
"NPM_CONFIG_CACHE",
"npm_config_cache",
];
#[async_trait::async_trait(?Send)]
impl LanguageBackend for Node {
async fn install(
&self,
store: &Store,
hook: Arc<Hook>,
reporter: &HookInstallReporter,
) -> Result<InstalledHook> {
let progress = reporter.on_install_start(&hook);
let node_dir = store.tools_path(ToolBucket::Node);
let installer = NodeInstaller::new(node_dir);
let node_request: &NodeRequest = hook.language_request.version();
let node = installer
.install(store, node_request, hook.language_request.allows_download())
.await
.context("Failed to install node")?;
let mut info = InstallInfo::new(&hook, &store.hooks_dir())?;
let lts = serde_json::to_string(&node.version().lts).context("Failed to serialize LTS")?;
info.with_toolchain(node.node().to_path_buf());
info.with_language_version(node.version().version.clone());
info.with_extra(EXTRA_KEY_LTS, <s);
let bin_dir = bin_dir(&info.env_path);
let lib_dir = lib_dir(&info.env_path);
fs_err::tokio::create_dir_all(&bin_dir).await?;
fs_err::tokio::create_dir_all(&lib_dir).await?;
let (deps, includes_git_hook_repo) = node_install_dependencies(&hook)?;
if deps.is_empty() {
debug!("No dependencies to install");
} else {
let node_bin = node.node().parent().expect("Node binary must have parent");
let new_path = prepend_paths(&[&bin_dir, node_bin]).context("Failed to join PATH")?;
let npm_cache = store.cache_path(CacheBucket::Npm);
let mut cmd = Cmd::new(node.npm());
cmd.arg("install");
if includes_git_hook_repo && query_npm_version(node.npm(), &new_path).await?.major >= 12
{
cmd.arg("--allow-git=root");
}
cmd.arg("-g")
.arg("--no-progress")
.arg("--no-save")
.arg("--no-fund")
.arg("--no-audit")
.args(&deps)
.env(EnvVars::PATH, new_path)
.env(EnvVars::NODE_PATH, &lib_dir);
apply_npm_config_env(&mut cmd, &info.env_path, &npm_cache);
cmd.check(true).output().await?;
}
info.persist_env_path();
reporter.on_install_complete(progress);
Ok(InstalledHook::Installed {
hook,
info: Arc::new(info),
})
}
async fn check_health(&self, info: &InstallInfo) -> Result<()> {
let version = query_node_version(&info.toolchain)
.await
.context("Failed to query node version")?;
if version.version != info.language_version {
anyhow::bail!(
"Node version mismatch: expected {}, found {}",
info.language_version,
version.version
);
}
Ok(())
}
async fn run(
&self,
store: &Store,
hook: &InstalledHook,
filenames: &[&Path],
reporter: &HookRunReporter,
) -> Result<(i32, Vec<u8>)> {
let progress = reporter.on_run_start(hook, filenames.len());
let env_dir = hook.env_path().expect("Node must have env path");
let node_bin = hook.toolchain_dir().expect("Node binary must have parent");
let new_path =
prepend_paths(&[&bin_dir(env_dir), node_bin]).context("Failed to join PATH")?;
let entry = hook.entry.resolve(Some(&new_path), store)?;
let npm_cache = store.cache_path(CacheBucket::Npm);
let run = async |batch: &[&Path]| {
let mut cmd = Cmd::new(&entry[0]);
cmd.current_dir(hook.work_dir())
.args(&entry[1..])
.env(EnvVars::PATH, &new_path)
.env(EnvVars::NODE_PATH, lib_dir(env_dir))
.envs(&hook.env);
apply_npm_config_env(&mut cmd, env_dir, &npm_cache);
let output = cmd
.args(&hook.args)
.file_args(batch)
.check(false)
.stdin(Stdio::null())
.pty_output_with_sink(reporter.output_sink(progress))
.await?;
reporter.on_run_progress(progress, batch.len() as u64);
anyhow::Ok(output)
};
let output = run_by_batch(hook, filenames, entry.argv(), run).await?;
reporter.on_run_complete(progress);
Ok(output)
}
}
fn node_install_dependencies(hook: &Hook) -> Result<(Vec<String>, bool)> {
let mut deps = Vec::with_capacity(hook.additional_dependencies.len() + 1);
let mut includes_git_hook_repo = false;
if let Some(repo_path) = hook.repo_path() {
let file_url = Url::from_file_path(repo_path).map_err(|()| {
anyhow!(
"Failed to convert Node hook repository path to a file URL: {}",
repo_path.display()
)
})?;
deps.push(format!("git+{file_url}"));
includes_git_hook_repo = true;
}
deps.extend(hook.additional_dependencies.iter().cloned());
Ok((deps, includes_git_hook_repo))
}
async fn query_npm_version(npm: &Path, path: &std::ffi::OsStr) -> Result<Version> {
let output = Cmd::new(npm)
.arg("--version")
.env(EnvVars::PATH, path)
.check(true)
.output()
.await?;
Version::parse(str::from_utf8(&output.stdout)?.trim()).context("Failed to parse npm version")
}
fn apply_npm_config_env(cmd: &mut Cmd, prefix: &Path, cache: &Path) {
for key in NPM_CONFIG_ENVS_TO_REMOVE {
cmd.env_remove(key);
}
cmd.env(NPM_CONFIG_PREFIX_ENV, prefix);
cmd.env(NPM_CONFIG_CACHE_ENV, cache);
}