|
| 1 | +use std::ffi::OsStr; |
| 2 | +use std::io::ErrorKind; |
| 3 | +use std::path::Path; |
| 4 | +use std::process::Stdio; |
| 5 | +use std::sync::Arc; |
| 6 | + |
| 7 | +use anyhow::{Context, Result}; |
| 8 | +use prek_consts::env_vars::EnvVars; |
| 9 | +use prek_consts::prepend_paths; |
| 10 | +use tracing::debug; |
| 11 | + |
| 12 | +use crate::cli::reporter::HookInstallReporter; |
| 13 | +use crate::cli::run::HookRunReporter; |
| 14 | +use crate::hook::{Hook, InstallInfo, InstalledHook}; |
| 15 | +use crate::languages::LanguageImpl; |
| 16 | +use crate::process::Cmd; |
| 17 | +use crate::run::run_by_batch; |
| 18 | +use crate::store::{CacheBucket, Store}; |
| 19 | + |
| 20 | +const PRE_COMMIT_CHANNEL_DIR: &str = ".pre-commit-channel"; |
| 21 | + |
| 22 | +#[derive(Debug, Copy, Clone)] |
| 23 | +pub(crate) struct Coursier; |
| 24 | + |
| 25 | +fn channel_app_name(file_name: &str) -> &str { |
| 26 | + match file_name.rfind('.') { |
| 27 | + Some(0) | None => file_name, |
| 28 | + Some(index) if index + 1 == file_name.len() => file_name, |
| 29 | + Some(index) => &file_name[..index], |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +fn collect_channel_apps(channel_dir: &Path) -> Result<Option<Vec<String>>> { |
| 34 | + let entries = match fs_err::read_dir(channel_dir) { |
| 35 | + Ok(entries) => entries, |
| 36 | + Err(err) if matches!(err.kind(), ErrorKind::NotFound | ErrorKind::NotADirectory) => { |
| 37 | + return Ok(None); |
| 38 | + } |
| 39 | + Err(err) => { |
| 40 | + return Err(err).with_context(|| format!("Failed to read `{}`", channel_dir.display())); |
| 41 | + } |
| 42 | + }; |
| 43 | + |
| 44 | + let mut apps = entries |
| 45 | + .map(|entry| { |
| 46 | + let file_name = entry?.file_name(); |
| 47 | + let file_name = file_name.to_string_lossy(); |
| 48 | + Ok(channel_app_name(&file_name).to_string()) |
| 49 | + }) |
| 50 | + .collect::<Result<Vec<_>>>()?; |
| 51 | + apps.sort_unstable(); |
| 52 | + Ok(Some(apps)) |
| 53 | +} |
| 54 | + |
| 55 | +async fn install_coursier_app( |
| 56 | + cs: &Path, |
| 57 | + env_path: &Path, |
| 58 | + cache_path: &Path, |
| 59 | + source_path: &Path, |
| 60 | + path_env: &OsStr, |
| 61 | + args: &[String], |
| 62 | +) -> Result<()> { |
| 63 | + Cmd::new(cs, "coursier install") |
| 64 | + .current_dir(source_path) |
| 65 | + .arg("install") |
| 66 | + .arg("--dir") |
| 67 | + .arg(env_path) |
| 68 | + .args(args) |
| 69 | + .env(EnvVars::PATH, path_env) |
| 70 | + .env(EnvVars::COURSIER_CACHE, cache_path) |
| 71 | + .check(true) |
| 72 | + .output() |
| 73 | + .await |
| 74 | + .with_context(|| format!("Failed to install coursier app `{}`", args.join(" ")))?; |
| 75 | + |
| 76 | + Ok(()) |
| 77 | +} |
| 78 | + |
| 79 | +impl LanguageImpl for Coursier { |
| 80 | + async fn install( |
| 81 | + &self, |
| 82 | + hook: Arc<Hook>, |
| 83 | + store: &Store, |
| 84 | + reporter: &HookInstallReporter, |
| 85 | + ) -> Result<InstalledHook> { |
| 86 | + let progress = reporter.on_install_start(&hook); |
| 87 | + |
| 88 | + let source_path = hook.repo_path().unwrap_or_else(|| hook.work_dir()); |
| 89 | + let channel_dir = source_path.join(PRE_COMMIT_CHANNEL_DIR); |
| 90 | + let channel_apps = collect_channel_apps(&channel_dir)?; |
| 91 | + |
| 92 | + let mut dependencies = hook |
| 93 | + .additional_dependencies |
| 94 | + .iter() |
| 95 | + .cloned() |
| 96 | + .collect::<Vec<_>>(); |
| 97 | + dependencies.sort_unstable(); |
| 98 | + |
| 99 | + if channel_apps.is_none() && dependencies.is_empty() { |
| 100 | + anyhow::bail!("expected .pre-commit-channel dir or additional_dependencies"); |
| 101 | + } |
| 102 | + |
| 103 | + let cs = which::which("cs") |
| 104 | + .or_else(|_| which::which("coursier")) |
| 105 | + .context( |
| 106 | + "Coursier hooks require system-installed `cs` or `coursier` executables in PATH", |
| 107 | + )?; |
| 108 | + let mut info = InstallInfo::new( |
| 109 | + hook.language, |
| 110 | + hook.env_key_dependencies().clone(), |
| 111 | + &store.hooks_dir(), |
| 112 | + )?; |
| 113 | + |
| 114 | + debug!(%hook, target = %info.env_path.display(), "Installing Coursier environment"); |
| 115 | + |
| 116 | + fs_err::tokio::create_dir_all(&info.env_path).await?; |
| 117 | + let coursier_cache = store.cache_path(CacheBucket::Coursier); |
| 118 | + fs_err::tokio::create_dir_all(&coursier_cache).await?; |
| 119 | + |
| 120 | + let path_env = prepend_paths(&[&info.env_path]).context("Failed to join PATH")?; |
| 121 | + |
| 122 | + if let Some(channel_apps) = channel_apps { |
| 123 | + for app in channel_apps { |
| 124 | + let args = vec![ |
| 125 | + "--default-channels=false".to_string(), |
| 126 | + "--channel".to_string(), |
| 127 | + channel_dir.to_string_lossy().into_owned(), |
| 128 | + app, |
| 129 | + ]; |
| 130 | + install_coursier_app( |
| 131 | + &cs, |
| 132 | + &info.env_path, |
| 133 | + &coursier_cache, |
| 134 | + source_path, |
| 135 | + &path_env, |
| 136 | + &args, |
| 137 | + ) |
| 138 | + .await?; |
| 139 | + } |
| 140 | + } |
| 141 | + |
| 142 | + if !dependencies.is_empty() { |
| 143 | + Cmd::new(&cs, "coursier fetch") |
| 144 | + .current_dir(source_path) |
| 145 | + .arg("fetch") |
| 146 | + .args(&dependencies) |
| 147 | + .env(EnvVars::PATH, &path_env) |
| 148 | + .env(EnvVars::COURSIER_CACHE, &coursier_cache) |
| 149 | + .check(true) |
| 150 | + .output() |
| 151 | + .await |
| 152 | + .with_context(|| { |
| 153 | + format!("Failed to fetch coursier app `{}`", dependencies.join(" ")) |
| 154 | + })?; |
| 155 | + install_coursier_app( |
| 156 | + &cs, |
| 157 | + &info.env_path, |
| 158 | + &coursier_cache, |
| 159 | + source_path, |
| 160 | + &path_env, |
| 161 | + &dependencies, |
| 162 | + ) |
| 163 | + .await?; |
| 164 | + } |
| 165 | + |
| 166 | + info.with_toolchain(cs); |
| 167 | + info.persist_env_path(); |
| 168 | + |
| 169 | + reporter.on_install_complete(progress); |
| 170 | + |
| 171 | + Ok(InstalledHook::Installed { |
| 172 | + hook, |
| 173 | + info: Arc::new(info), |
| 174 | + }) |
| 175 | + } |
| 176 | + |
| 177 | + async fn check_health(&self, _info: &InstallInfo) -> Result<()> { |
| 178 | + Ok(()) |
| 179 | + } |
| 180 | + |
| 181 | + async fn run( |
| 182 | + &self, |
| 183 | + hook: &InstalledHook, |
| 184 | + filenames: &[&Path], |
| 185 | + store: &Store, |
| 186 | + reporter: &HookRunReporter, |
| 187 | + ) -> Result<(i32, Vec<u8>)> { |
| 188 | + let progress = reporter.on_run_start(hook, filenames.len()); |
| 189 | + |
| 190 | + let env_path = hook.env_path().expect("Coursier must have env path"); |
| 191 | + let coursier_cache = store.cache_path(CacheBucket::Coursier); |
| 192 | + let path_env = prepend_paths(&[env_path]).context("Failed to join PATH")?; |
| 193 | + let entry = hook.entry.resolve(Some(&path_env), store)?; |
| 194 | + |
| 195 | + let run = async |batch: &[&Path]| { |
| 196 | + let mut output = Cmd::new(&entry[0], "run coursier hook") |
| 197 | + .current_dir(hook.work_dir()) |
| 198 | + .args(&entry[1..]) |
| 199 | + .envs(&hook.env) |
| 200 | + .args(&hook.args) |
| 201 | + .args(batch) |
| 202 | + .check(false) |
| 203 | + .stdin(Stdio::null()) |
| 204 | + .env(EnvVars::PATH, &path_env) |
| 205 | + .env(EnvVars::COURSIER_CACHE, &coursier_cache) |
| 206 | + .pty_output_with_sink(reporter.output_sink(progress)) |
| 207 | + .await?; |
| 208 | + |
| 209 | + reporter.on_run_progress(progress, batch.len() as u64); |
| 210 | + |
| 211 | + output.stdout.extend(output.stderr); |
| 212 | + let code = output.status.code().unwrap_or(1); |
| 213 | + anyhow::Ok((code, output.stdout)) |
| 214 | + }; |
| 215 | + |
| 216 | + let results = run_by_batch(hook, filenames, entry.argv(), run).await?; |
| 217 | + |
| 218 | + let mut combined_status = 0; |
| 219 | + let mut combined_output = Vec::new(); |
| 220 | + |
| 221 | + for (code, output) in results { |
| 222 | + combined_status |= code; |
| 223 | + combined_output.extend(output); |
| 224 | + } |
| 225 | + |
| 226 | + reporter.on_run_complete(progress); |
| 227 | + |
| 228 | + Ok((combined_status, combined_output)) |
| 229 | + } |
| 230 | +} |
| 231 | + |
| 232 | +#[cfg(test)] |
| 233 | +mod tests { |
| 234 | + use super::channel_app_name; |
| 235 | + |
| 236 | + #[test] |
| 237 | + fn channel_app_name_drops_descriptor_extension() { |
| 238 | + assert_eq!(channel_app_name("scalafmt.json"), "scalafmt"); |
| 239 | + assert_eq!(channel_app_name("foo.bar.json"), "foo.bar"); |
| 240 | + } |
| 241 | + |
| 242 | + #[test] |
| 243 | + fn channel_app_name_keeps_dotfiles_and_trailing_dots() { |
| 244 | + assert_eq!(channel_app_name(".scalafmt"), ".scalafmt"); |
| 245 | + assert_eq!(channel_app_name("scalafmt."), "scalafmt."); |
| 246 | + } |
| 247 | +} |
0 commit comments