use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::thread;
use std::time::{Duration, Instant};
use flareapp_otlp::KeyValue;
use crate::config::Config;
const TIMEOUT: Duration = Duration::from_secs(1);
const POLL_INTERVAL: Duration = Duration::from_millis(5);
pub(crate) fn source_folder(config: &Config) -> Option<PathBuf> {
if config.git_hash.is_some() {
return None;
}
let folder = PathBuf::from(config.application_path.as_deref()?);
folder.is_dir().then_some(folder)
}
pub(crate) fn attributes(folder: &Path) -> Vec<KeyValue> {
let deadline = Instant::now() + TIMEOUT;
let Some(hash) = run(folder, &["rev-parse", "HEAD"], deadline) else {
return Vec::new();
};
let mut attributes = vec![KeyValue::new("git.hash", hash)];
if let Some(branch) = run(folder, &["symbolic-ref", "--short", "HEAD"], deadline) {
attributes.push(KeyValue::new("git.branch", branch));
}
if let Some(tag) = run(
folder,
&[
"for-each-ref",
"--count=1",
"--sort=-creatordate",
"--format=%(refname:short)",
"refs/tags",
],
deadline,
) {
attributes.push(KeyValue::new("git.tag", tag));
}
attributes
}
fn run(folder: &Path, args: &[&str], deadline: Instant) -> Option<String> {
let mut child = Command::new("git")
.arg("-C")
.arg(folder)
.args(args)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.ok()?;
let status = loop {
match child.try_wait() {
Ok(Some(status)) => break status,
Ok(None) if Instant::now() < deadline => thread::sleep(POLL_INTERVAL),
_ => {
let _ = child.kill();
let _ = child.wait();
return None;
}
}
};
let mut output = String::new();
child.stdout.take()?.read_to_string(&mut output).ok()?;
let output = output.trim();
(status.success() && !output.is_empty()).then(|| output.to_owned())
}
#[cfg(test)]
pub(crate) fn test_repository() -> PathBuf {
use std::sync::atomic::{AtomicUsize, Ordering};
static COUNT: AtomicUsize = AtomicUsize::new(0);
let folder = std::env::temp_dir().join(format!(
"flareapp-git-{}-{}",
std::process::id(),
COUNT.fetch_add(1, Ordering::Relaxed)
));
let _ = std::fs::remove_dir_all(&folder);
std::fs::create_dir_all(&folder).unwrap();
let git = |args: &[&str]| {
let status = Command::new("git")
.arg("-C")
.arg(&folder)
.args([
"-c",
"user.name=Flare",
"-c",
"user.email=flare@example.test",
])
.args(["-c", "commit.gpgsign=false", "-c", "tag.gpgsign=false"])
.args(args)
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
assert!(status.unwrap().success(), "git {args:?} failed");
};
git(&["init", "--initial-branch=main"]);
git(&["commit", "--allow-empty", "--message", "Add the checkout"]);
git(&["tag", "v1.0.0"]);
folder
}
#[cfg(test)]
mod tests {
use flareapp_otlp::AnyValue;
use super::*;
use crate::test_support::attribute;
#[test]
fn skips_the_source_folder_when_the_hash_is_known() {
let folder = env!("CARGO_MANIFEST_DIR");
assert_eq!(
source_folder(&Config::new().application_path(folder)),
Some(PathBuf::from(folder))
);
assert_eq!(
source_folder(&Config::new().application_path(folder).git_hash("4f2a9c1e")),
None
);
assert_eq!(
source_folder(&Config::new().application_path("/does/not/exist")),
None
);
}
#[test]
fn reads_nothing_outside_a_repository() {
assert_eq!(
attributes(&std::env::temp_dir().join("flareapp-no-such-folder")),
Vec::new()
);
}
#[test]
fn reads_the_commit_of_a_repository() {
let folder = test_repository();
let attributes = attributes(&folder);
std::fs::remove_dir_all(&folder).unwrap();
let text = |key| attribute(&attributes, key).and_then(AnyValue::as_str);
assert_eq!(text("git.hash").map(str::len), Some(40));
assert_eq!(text("git.branch"), Some("main"));
assert_eq!(text("git.tag"), Some("v1.0.0"));
assert_eq!(attributes.len(), 3);
}
}