mirror of
https://seed.radicle.dev/rad:z3qg5TKmN83afz2fj9z3fQjU8vaYE.git
synced 2026-11-28 22:10:28 +08:00
190 lines
5.4 KiB
Rust
190 lines
5.4 KiB
Rust
//! A Radicle CI adapter for native CI.
|
|
//!
|
|
//! Perform the CI run locally, without any isolation. This is not
|
|
//! safe and secure, but it's simple, and easy to get working. Do not
|
|
//! use this unless you trust the repository.
|
|
//!
|
|
//! The repository must contain a file `.ci/radicle.yaml` that
|
|
//! specifies how CI is run for the repository. For example:
|
|
//!
|
|
//! ```yaml
|
|
//! shell: |
|
|
//! cargo test --locked --workspace
|
|
//! ```
|
|
|
|
use std::{
|
|
fs::File,
|
|
io::Write,
|
|
path::{Path, PathBuf},
|
|
rc::Rc,
|
|
};
|
|
|
|
use log::{debug, info};
|
|
use serde::Deserialize;
|
|
use subprocess::{Popen, PopenConfig, Redirection};
|
|
use uuid::Uuid;
|
|
|
|
use radicle::prelude::Profile;
|
|
use radicle_ci_broker::msg::{Id, Oid, Request, Response, RunId, RunResult};
|
|
|
|
/// Path to the repository's CI run specification. This is relative to
|
|
/// the root of the repository.
|
|
const RUNSPEC_PATH: &str = ".ci/radicle.yaml";
|
|
|
|
/// The main program.
|
|
fn main() -> anyhow::Result<()> {
|
|
pretty_env_logger::init_custom_env("RADICLE_NATIVE_CI_LOG");
|
|
info!("radicle-native-ci starts");
|
|
|
|
let config = std::env::var("RADICLE_NATIVE_CI")?;
|
|
let config = Config::read(Path::new(&config))?;
|
|
debug!("read config: {:#?}", config);
|
|
let state = &config.state;
|
|
if !state.exists() {
|
|
debug!("creating {}", state.display());
|
|
std::fs::create_dir_all(state)?;
|
|
}
|
|
|
|
let run_id = Uuid::new_v4();
|
|
let run_dir = state.join(run_id.to_string());
|
|
debug!("directory for this run: {}", run_dir.display());
|
|
std::fs::create_dir(&run_dir)?;
|
|
|
|
let src = run_dir.join("src");
|
|
let log = run_dir.join("log");
|
|
|
|
let profile = Profile::load()?;
|
|
let storage = profile.storage.path();
|
|
|
|
let req = Request::from_reader(std::io::stdin()).unwrap();
|
|
debug!("request: {:#?}", req);
|
|
|
|
if let Request::Trigger { repo, commit } = req {
|
|
info!("Request to trigger CI on {}, {}", repo, commit);
|
|
run(run_id, storage, repo, commit, &src, &log)?;
|
|
} else {
|
|
let error = Response::error("first request was not Trigger");
|
|
error.to_writer(std::io::stdout())?;
|
|
}
|
|
|
|
info!("radicle-native-ci ends");
|
|
Ok(())
|
|
}
|
|
|
|
/// Perform the CI run.
|
|
fn run(
|
|
run_id: Uuid,
|
|
storage: &Path,
|
|
repo: Id,
|
|
commit: Oid,
|
|
src: &Path,
|
|
log: &Path,
|
|
) -> anyhow::Result<()> {
|
|
let mut log = Rc::new(std::fs::File::create(log)?);
|
|
|
|
logmsg(&mut log, "=== Radicle native CI\n".into())?;
|
|
logmsg(&mut log, format!("=== Repository id: {}\n", repo))?;
|
|
logmsg(&mut log, format!("=== Commit: {}\n", commit))?;
|
|
|
|
let first = Response::triggered(RunId::from(run_id.to_string().as_str()));
|
|
first.to_writer(std::io::stdout())?;
|
|
|
|
let repo = storage.join(repo.canonical());
|
|
debug!("repo path: {}", repo.display());
|
|
|
|
debug!("cloning repository to {}", src.display());
|
|
runcmd(
|
|
&mut log,
|
|
&[
|
|
"git",
|
|
"clone",
|
|
repo.to_str().unwrap(),
|
|
src.to_str().unwrap(),
|
|
],
|
|
storage,
|
|
)?;
|
|
|
|
let runspec = RunSpec::from_file(&src.join(RUNSPEC_PATH))?;
|
|
|
|
debug!("running CI in cloned repository");
|
|
let snippet = format!("set -xeuo pipefail\n{}", &runspec.shell);
|
|
runcmd(&mut log, &["bash", "-c", &snippet], src)?;
|
|
|
|
let second = Response::finished(RunResult::Success);
|
|
second.to_writer(std::io::stdout())?;
|
|
|
|
logmsg(&mut log, "CI run finished successfully".into())?;
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// Run a command in a directory.
|
|
fn runcmd(log: &mut Rc<File>, argv: &[&str], cwd: &Path) -> anyhow::Result<()> {
|
|
logmsg(log, format!("=== Run: {:?}\n---\n", argv))?;
|
|
let mut p = Popen::create(
|
|
argv,
|
|
PopenConfig {
|
|
cwd: Some(cwd.as_os_str().into()),
|
|
stdout: Redirection::RcFile(log.clone()),
|
|
stderr: Redirection::Merge,
|
|
..Default::default()
|
|
},
|
|
)?;
|
|
p.communicate(None)?;
|
|
let exit = p.wait()?;
|
|
debug!("exit: {:?}", exit);
|
|
logmsg(log, "...\n".into())?;
|
|
if !exit.success() {
|
|
let error = Response::error(&format!("command failed: {:?}", argv));
|
|
error.to_writer(std::io::stdout())?;
|
|
return Ok(());
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Write a message to the run log.
|
|
fn logmsg(log: &mut Rc<File>, msg: String) -> anyhow::Result<()> {
|
|
let x = Rc::get_mut(log).unwrap();
|
|
x.write_all(msg.as_bytes())?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Configuration file for `radicle-native-ci`.
|
|
#[derive(Debug, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct Config {
|
|
/// Directory where per-run directories are stored. Each run gets
|
|
/// its own dedicated subdirectory.
|
|
state: PathBuf,
|
|
}
|
|
|
|
impl Config {
|
|
/// Read configuration specification from a file.
|
|
fn read(filename: &Path) -> anyhow::Result<Self> {
|
|
let file = std::fs::File::open(filename)?;
|
|
let config = serde_yaml::from_reader(&file)?;
|
|
Ok(config)
|
|
}
|
|
}
|
|
|
|
/// How to run CI for this repository.
|
|
#[derive(Debug, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
#[allow(dead_code)]
|
|
pub struct RunSpec {
|
|
/// The shell script snippet to run. It will be run with `bash`
|
|
/// and with `set -xeuo pipefail`.
|
|
shell: String,
|
|
}
|
|
|
|
impl RunSpec {
|
|
/// Read run specification from a file.
|
|
fn from_file(filename: &Path) -> anyhow::Result<Self> {
|
|
debug!("loading CI run spec from {}", filename.display());
|
|
let file = std::fs::File::open(filename)?;
|
|
let runspec: RunSpec = serde_yaml::from_reader(&file)?;
|
|
debug!("runspec: {:#?}", runspec);
|
|
Ok(runspec)
|
|
}
|
|
}
|