Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support docker language #67

Merged
merged 24 commits into from
Nov 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
# Insta snapshots.
*.pending-snap

# JetBrains IDE
.idea

# macOS
**/.DS_Store

Expand Down
9 changes: 9 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 5 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,10 @@ path = "src/main.rs"
name = "pre-commit"

[features]
default = []
default = ["docker"]
profiler = ["dep:pprof", "profiler-flamegraph"]
profiler-flamegraph = ["pprof/flamegraph"]
docker = []

[dependencies]
anstream = "0.6.15"
Expand All @@ -36,11 +37,13 @@ http = "1.1.0"
indicatif = "0.17.8"
indoc = "2.0.5"
itertools = "0.13.0"
md5 = "0.7.0"
owo-colors = "4.1.0"
rand = "0.8.5"
rayon = "1.10.0"
rusqlite = { version = "0.32.1", features = ["bundled"] }
serde = { version = "1.0.210", features = ["derive"] }
serde_json = "1.0.132"
serde_yaml = "0.9.34"
shlex = "1.3.0"
tempfile = "3.13.0"
Expand All @@ -54,6 +57,7 @@ url = { version = "2.5.2", features = ["serde"] }
which = "6.0.3"

[target.'cfg(unix)'.dependencies]
libc = "0.2.164"
pprof = { version = "0.14.0", optional = true }

[dev-dependencies]
Expand Down
247 changes: 247 additions & 0 deletions src/languages/docker.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,247 @@
use std::borrow::Cow;
use std::collections::HashMap;
use std::ffi::OsStr;
use std::fs;
use std::sync::Arc;

use anstream::ColorChoice;
use anyhow::Result;
use assert_cmd::output::{OutputError, OutputOkExt};
use fancy_regex::Regex;
use tokio::process::Command;
use tracing::trace;

use crate::config::Language;
use crate::fs::CWD;
use crate::hook::Hook;
use crate::languages::{LanguageImpl, DEFAULT_VERSION};
use crate::run::run_by_batch;

const PRE_COMMIT_LABEL: &str = "PRE_COMMIT";

#[derive(Debug, Copy, Clone)]
pub struct Docker;

impl Docker {
fn docker_tag(hook: &Hook) -> Option<String> {
hook.path()
.file_name()
.and_then(OsStr::to_str)
.map(|s| format!("pre-commit-{:x}", md5::compute(s)))
}

async fn build_docker_image(hook: &Hook, pull: bool) -> Result<()> {
let mut cmd = Command::new("docker");

let cmd = cmd
.arg("build")
.arg("--tag")
.arg(Self::docker_tag(hook).expect("Failed to get docker tag"))
.arg("--label")
.arg(PRE_COMMIT_LABEL);

if pull {
cmd.arg("--pull");
}

// This must come last for old versions of docker.
// see https://github.com/pre-commit/pre-commit/issues/477
cmd.arg(".");

cmd.current_dir(hook.path())
.output()
.await
.map_err(OutputError::with_cause)?
.ok()?;

Ok(())
}

/// see <https://stackoverflow.com/questions/23513045/how-to-check-if-a-process-is-running-inside-docker-container>
fn is_in_docker() -> bool {
if fs::metadata("/.dockerenv").is_ok() || fs::metadata("/run/.containerenv").is_ok() {
return true;
}
false
}

/// Get container id the process is running in.
///
/// There are no reliable way to get the container id inside container, see
/// <https://stackoverflow.com/questions/20995351/how-can-i-get-docker-linux-container-information-from-within-the-container-itsel>
fn current_container_id() -> Result<String> {
// Adapted from https://github.com/open-telemetry/opentelemetry-java-instrumentation/pull/7167/files
let regex = Regex::new(r".*/docker/containers/([0-9a-f]{64})/.*").expect("invalid regex");
let cgroup_path = fs::read_to_string("/proc/self/cgroup")?;
let Some(captures) = regex.captures(&cgroup_path)? else {
anyhow::bail!("Failed to get container id: no match found");
};
let Some(id) = captures.get(1).map(|m| m.as_str().to_string()) else {
anyhow::bail!("Failed to get container id: no capture found");
};
Ok(id)
}

/// Get the path of the current directory in the host.
async fn get_docker_path(path: &str) -> Result<Cow<'_, str>> {
if !Self::is_in_docker() {
return Ok(Cow::Borrowed(path));
};

let Ok(container_id) = Self::current_container_id() else {
return Ok(Cow::Borrowed(path));
};

trace!(?container_id, "Get container id");

if let Ok(output) = Command::new("docker")
.arg("inspect")
.arg("--format")
.arg("'{{json .Mounts}}'")
.arg(&container_id)
.output()
.await
{
#[derive(serde::Deserialize, Debug)]
struct Mount {
#[serde(rename = "Source")]
source: String,
#[serde(rename = "Destination")]
destination: String,
}

let stdout = String::from_utf8_lossy(&output.stdout);
let stdout = stdout.trim().trim_matches('\'');
let mounts: Vec<Mount> = serde_json::from_str(stdout)?;

trace!(?mounts, "Get docker mounts");

for mount in mounts {
if path.starts_with(&mount.destination) {
let mut path = path.replace(&mount.destination, &mount.source);
if path.contains('\\') {
// Replace `/` with `\` on Windows
path = path.replace('/', "\\");
}
return Ok(Cow::Owned(path));
}
}
}

Ok(Cow::Borrowed(path))
}

async fn docker_cmd() -> Result<Command> {
let mut command = Command::new("docker");
command.arg("run").arg("--rm");

match ColorChoice::global() {
ColorChoice::Always | ColorChoice::AlwaysAnsi => {
command.arg("--tty");
}
_ => {}
}

// Run as a non-root user
#[cfg(unix)]
{
command.arg("--user");
command.arg(format!("{}:{}", unsafe { libc::geteuid() }, unsafe {
libc::getegid()
}));
}

command
.arg("-v")
// https://docs.docker.com/engine/reference/commandline/run/#mount-volumes-from-container-volumes-from
.arg(format!(
"{}:/src:ro,Z",
Self::get_docker_path(&CWD.to_string_lossy()).await?
))
.arg("--workdir")
.arg("/src");

Ok(command)
}
}

impl LanguageImpl for Docker {
fn name(&self) -> Language {
Language::Docker
}

fn default_version(&self) -> &str {
DEFAULT_VERSION
}

fn environment_dir(&self) -> Option<&str> {
Some("docker")
}

async fn install(&self, hook: &Hook) -> Result<()> {
let env = hook.environment_dir().expect("No environment dir found");

Docker::build_docker_image(hook, true).await?;
fs_err::create_dir_all(env)?;
Ok(())
}

async fn check_health(&self) -> Result<()> {
todo!()
}

async fn run(
&self,
hook: &Hook,
filenames: &[&String],
env_vars: Arc<HashMap<&'static str, String>>,
) -> Result<(i32, Vec<u8>)> {
Docker::build_docker_image(hook, false).await?;

let docker_tag = Docker::docker_tag(hook).expect("Failed to get docker tag");

let cmds = shlex::split(&hook.entry).ok_or(anyhow::anyhow!("Failed to parse entry"))?;

let cmds = Arc::new(cmds);
let hook_args = Arc::new(hook.args.clone());

let run = move |batch: Vec<String>| {
let cmds = cmds.clone();
let docker_tag = docker_tag.clone();
let hook_args = hook_args.clone();
let env_vars = env_vars.clone();

async move {
// docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
let mut cmd = Docker::docker_cmd().await?;
let cmd = cmd
.arg("--entrypoint")
.arg(&cmds[0])
.arg(&docker_tag)
.args(&cmds[1..])
.args(hook_args.as_ref())
.args(batch)
.stderr(std::process::Stdio::inherit())
.envs(env_vars.as_ref());

let mut output = cmd.output().await?;
output.stdout.extend(output.stderr);
let code = output.status.code().unwrap_or(1);
anyhow::Ok((code, output.stdout))
}
};

let results = run_by_batch(hook, filenames, run).await?;

// Collect results
let mut combined_status = 0;
let mut combined_output = Vec::new();

for (code, output) in results {
combined_status |= code;
combined_output.extend(output);
}

Ok((combined_status, combined_output))
}
}
Loading