use crate::git;
use crate::ui::{error_sign, valid_sign, warning_sign};
use std::path::Path;
use std::process::{Command, Stdio};
use std::sync::OnceLock;
static OVERRIDE: OnceLock<Vec<String>> = OnceLock::new();
static NOT_THE_INDEX: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
pub fn override_file_set(files: Vec<String>) {
NOT_THE_INDEX.store(true, std::sync::atomic::Ordering::SeqCst);
let _ = OVERRIDE.set(files);
}
pub fn not_the_index() -> bool {
NOT_THE_INDEX.load(std::sync::atomic::Ordering::SeqCst)
}
const DOC_EXTS: &[&str] = &[".md", ".mdx", ".rst", ".adoc"];
pub fn staged_docs_only() -> bool {
if not_the_index() {
return false;
}
let Some(raw) = git::stdout_paths(&["diff", "--cached", "--no-renames", "--name-status"])
else {
return false;
};
!raw.is_empty()
&& raw.len() % 2 == 0
&& raw.chunks(2).all(|pair| {
pair[0] == "M"
&& !pair[1].starts_with("adr/")
&& DOC_EXTS.iter().any(|e| pair[1].ends_with(e))
})
}
pub fn staged_files(exts: &[&str]) -> Vec<String> {
if let Some(all) = OVERRIDE.get() {
return all
.iter()
.filter(|f| exts.is_empty() || exts.iter().any(|e| f.ends_with(e)))
.cloned()
.collect();
}
static INDEX: OnceLock<Vec<String>> = OnceLock::new();
INDEX
.get_or_init(|| {
match git::stdout_paths(&["diff", "--diff-filter=d", "--cached", "--name-only"]) {
Some(files) => files,
None => {
warn(
"git would not list the staged files — the checks are judging \
an EMPTY set, not a verified one",
);
Vec::new()
}
}
})
.iter()
.filter(|f| exts.is_empty() || exts.iter().any(|e| f.ends_with(e)))
.cloned()
.collect()
}
pub fn tracked_files() -> Option<Vec<String>> {
static TRACKED: OnceLock<Option<Vec<String>>> = OnceLock::new();
TRACKED
.get_or_init(|| match git::stdout_paths(&["ls-files"]) {
Some(files) => Some(files),
None => {
warn(
"git would not list the repository's files — opt-in gated checks \
will run rather than be skipped on an unverified answer",
);
None
}
})
.clone()
}
pub fn repo_root() -> String {
static ROOT: OnceLock<String> = OnceLock::new();
ROOT.get_or_init(|| {
git::stdout(&["rev-parse", "--show-toplevel"]).unwrap_or_else(|| ".".into())
})
.clone()
}
pub fn repo_root_checked() -> Result<String, String> {
git::stdout(&["rev-parse", "--show-toplevel"])
.filter(|s| !s.is_empty())
.ok_or_else(|| "not inside a git repository".to_string())
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Ambient {
Path { path: String, version: Version },
Npx { version: String },
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Version {
Known(String),
Unknown,
TimedOut,
}
pub(crate) const PROBE_DEADLINE: std::time::Duration = std::time::Duration::from_secs(5);
pub(crate) fn pinned_tool(root: &str, tool: &str) -> Option<String> {
if let Some(p) = in_bin_dir(&format!("{root}/node_modules/.bin"), tool) {
return Some(p);
}
let common = git::stdout(&["rev-parse", "--path-format=absolute", "--git-common-dir"])?;
let main = Path::new(&common).parent()?;
in_bin_dir(&main.join("node_modules/.bin").to_string_lossy(), tool)
}
enum Found {
Tool(Vec<String>, Ambient),
NpxHung,
Nothing,
}
fn ambient_tool(root: &str, tool: &str) -> Found {
if let Some(path) = which(tool) {
let argv = vec![path.clone()];
let version = probe_version(&argv, root);
return Found::Tool(argv, Ambient::Path { path, version });
}
if which("npx").is_none() {
return Found::Nothing;
}
let npx = vec![program("npx"), "--no-install".to_string(), tool.to_string()];
match probe_version(&npx, root) {
Version::Known(version) => Found::Tool(npx, Ambient::Npx { version }),
Version::TimedOut => Found::NpxHung,
Version::Unknown => Found::Nothing,
}
}
fn probe_version(argv: &[String], root: &str) -> Version {
static NEVER: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
let mut probe = argv.to_vec();
probe.push("--version".to_string());
let deadline = std::time::Instant::now() + PROBE_DEADLINE;
match crate::tree_run::run_output(&probe, Path::new(root), deadline, &NEVER) {
Ok(out) => version_in(&out).map_or(Version::Unknown, Version::Known),
Err(crate::tree_run::TreeRun::TimedOut) => Version::TimedOut,
Err(_) => Version::Unknown,
}
}
fn version_in(out: &str) -> Option<String> {
out.lines().find_map(|line| {
let word = line.trim_start();
let word = word.strip_prefix('v').unwrap_or(word);
let end = word
.find(|c: char| !(c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '+')))
.unwrap_or(word.len());
let v = &word[..end];
let mut parts = v.splitn(3, '.');
let whole = |p: Option<&str>| {
p.is_some_and(|s| !s.is_empty() && s.chars().all(|c| c.is_ascii_digit()))
};
let (major, minor) = (parts.next(), parts.next());
let patch_starts = parts
.next()
.is_some_and(|s| s.starts_with(|c: char| c.is_ascii_digit()));
(whole(major) && whole(minor) && patch_starts).then(|| v.to_string())
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum JsTool {
Pinned(Vec<String>),
Ambient { argv: Vec<String>, ambient: Ambient },
NotInstalled,
NpxHung,
Missing,
}
pub(crate) struct JsUse {
pub(crate) tool: JsTool,
name: &'static str,
manager: crate::snapshot_prep::Manager,
}
pub(crate) fn resolve_js_tool(root: &str, name: &'static str) -> JsUse {
let manifest = std::fs::read_to_string(Path::new(root).join("package.json")).ok();
let manager = manifest
.as_deref()
.and_then(crate::snapshot_prep::declared_manager)
.or_else(|| crate::snapshot_prep::Manager::from_root_lockfile(Path::new(root)))
.unwrap_or(crate::snapshot_prep::Manager::Npm);
let tool = if let Some(p) = pinned_tool(root, name) {
JsTool::Pinned(vec![p])
} else if manifest
.as_deref()
.is_some_and(|text| package_json_declares(text, name))
{
JsTool::NotInstalled
} else {
match ambient_tool(root, name) {
Found::Tool(argv, ambient) => JsTool::Ambient { argv, ambient },
Found::NpxHung => JsTool::NpxHung,
Found::Nothing => JsTool::Missing,
}
};
JsUse {
tool,
name,
manager,
}
}
impl JsUse {
pub(crate) fn warn_ambient(&self, ambient: &Ambient) {
let name = self.name;
let (from, version) = match ambient {
Ambient::Npx { version } => {
("npx's cache".to_string(), Version::Known(version.clone()))
}
Ambient::Path { path, version } => (path.clone(), version.clone()),
};
let secs = PROBE_DEADLINE.as_secs();
let (named, pin, note) = match &version {
Version::Known(v) => (format!("{name} {v}"), format!("{name}@{v}"), ""),
Version::Unknown => (
format!("{name} (unknown version)"),
name.to_string(),
" (latest, not necessarily this one)",
),
Version::TimedOut => (
format!("{name} (no --version in {secs} s)"),
name.to_string(),
" (latest, not necessarily this one)",
),
};
warn(&format!(
"{} from {} is not in the root package.json",
crate::ui::sanitize(&named),
crate::ui::sanitize(&from)
));
warn(&format!(
"Pin it: {}{note}",
hl(&self.manager.add_dev_command(&pin))
));
}
pub(crate) fn warn_unavailable(&self) {
let name = self.name;
match &self.tool {
JsTool::NotInstalled => warn(&format!(
"{name} is in package.json but not installed: run {}",
hl(&format!("{} install", self.manager.tool()))
)),
JsTool::NpxHung => warn(&format!(
"npx --no-install {name} --version did not answer in {} s. Pin it: {}",
PROBE_DEADLINE.as_secs(),
hl(&self.manager.add_dev_command(name))
)),
JsTool::Missing => warn(&format!(
"{name} config found but no {name} binary. Run {}",
hl(&self.manager.add_dev_command(name))
)),
JsTool::Pinned(_) | JsTool::Ambient { .. } => {}
}
}
}
fn package_json_declares(text: &str, tool: &str) -> bool {
let text = text.strip_prefix('\u{feff}').unwrap_or(text);
let mut p = JsonWalk {
b: text.as_bytes(),
i: 0,
depth: 0,
};
p.declares(tool).unwrap_or(false)
}
const MAX_JSON_DEPTH: u16 = 128;
struct JsonWalk<'a> {
b: &'a [u8],
i: usize,
depth: u16,
}
impl JsonWalk<'_> {
fn ws(&mut self) {
while self.b.get(self.i).is_some_and(u8::is_ascii_whitespace) {
self.i += 1;
}
}
fn eat(&mut self, c: u8) -> Option<()> {
self.ws();
(self.b.get(self.i) == Some(&c)).then(|| self.i += 1)
}
fn string(&mut self) -> Option<&[u8]> {
self.eat(b'"')?;
let start = self.i;
loop {
match *self.b.get(self.i)? {
b'\\' => self.i += 2,
b'"' => {
self.i += 1;
return self.b.get(start..self.i - 1);
}
_ => self.i += 1,
}
}
}
fn value(&mut self) -> Option<()> {
self.ws();
match *self.b.get(self.i)? {
b'"' => self.string().map(|_| ()),
b'{' => self.nested(|w| w.object(|_, w| w.value())),
b'[' => self.nested(|w| {
w.i += 1;
if w.eat(b']').is_some() {
return Some(());
}
loop {
w.value()?;
if w.eat(b',').is_none() {
return w.eat(b']');
}
}
}),
_ => {
let start = self.i;
while self
.b
.get(self.i)
.is_some_and(|c| !matches!(c, b',' | b'}' | b']') && !c.is_ascii_whitespace())
{
self.i += 1;
}
(self.i > start).then_some(())
}
}
}
fn nested(&mut self, f: impl FnOnce(&mut Self) -> Option<()>) -> Option<()> {
if self.depth >= MAX_JSON_DEPTH {
return None;
}
self.depth += 1;
let r = f(self);
self.depth -= 1;
r
}
fn object(&mut self, mut member: impl FnMut(&[u8], &mut Self) -> Option<()>) -> Option<()> {
self.eat(b'{')?;
if self.eat(b'}').is_some() {
return Some(());
}
loop {
let key = self.string()?.to_vec();
self.eat(b':')?;
member(&key, self)?;
if self.eat(b',').is_none() {
return self.eat(b'}');
}
}
}
fn declares(&mut self, tool: &str) -> Option<bool> {
let mut found = false;
self.object(|key, w| {
if key == b"dependencies" || key == b"devDependencies" {
w.ws();
if w.b.get(w.i) == Some(&b'{') {
return w.object(|dep, w2| {
found |= dep == tool.as_bytes();
w2.value()
});
}
}
w.value()
})?;
self.ws();
(self.i == self.b.len()).then_some(found)
}
}
pub fn which(tool: &str) -> Option<String> {
which_on(&std::env::var_os("PATH")?, tool)
}
pub fn which_on(path: &std::ffi::OsStr, tool: &str) -> Option<String> {
let exts: Vec<String> = if cfg!(windows) {
std::env::var("PATHEXT")
.unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".into())
.split(';')
.filter(|e| !e.is_empty())
.map(|e| e.to_lowercase())
.collect()
} else {
Vec::new()
};
for dir in std::env::split_paths(path) {
for e in &exts {
let c = dir.join(format!("{tool}{e}"));
if c.is_file() {
return Some(c.to_string_lossy().into_owned());
}
}
let bare = dir.join(tool);
if bare.is_file() {
return Some(bare.to_string_lossy().into_owned());
}
}
None
}
fn in_bin_dir(dir: &str, tool: &str) -> Option<String> {
let bare = Path::new(dir).join(tool);
if bare.is_file() {
return Some(bare.to_string_lossy().into_owned());
}
if cfg!(windows) {
for e in [".cmd", ".exe", ".bat", ".ps1"] {
let c = Path::new(dir).join(format!("{tool}{e}"));
if c.is_file() {
return Some(c.to_string_lossy().into_owned());
}
}
}
None
}
pub fn program(name: &str) -> String {
which(name).unwrap_or_else(|| name.to_string())
}
pub fn first_existing(root: &str, names: &[&str]) -> Option<String> {
names
.iter()
.find(|n| Path::new(root).join(n).exists())
.map(|n| (*n).to_string())
}
pub fn strip_git_env(cmd: &mut Command) {
for (k, _) in std::env::vars_os() {
let key = k.to_string_lossy();
if key.starts_with("GIT_") {
cmd.env_remove(&k);
}
}
cmd.env_remove(INDEX_ENV);
cmd.env_remove(INDEX_GIT_DIR_ENV);
}
pub const INDEX_ENV: &str = "GREENGATE_INDEX_FILE";
pub const INDEX_GIT_DIR_ENV: &str = "GREENGATE_INDEX_GIT_DIR";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommitIndex {
pub file: std::path::PathBuf,
pub git_dir: std::path::PathBuf,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum IndexLookupError {
CurrentDir(String),
Git { args: String, why: String },
}
impl std::fmt::Display for IndexLookupError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::CurrentDir(e) => write!(f, "current directory: {e}"),
Self::Git { args, why } => write!(f, "git {args} failed: {why}"),
}
}
}
pub fn commit_index() -> Result<CommitIndex, IndexLookupError> {
let here = std::env::current_dir().map_err(|e| IndexLookupError::CurrentDir(e.to_string()))?;
let absolute = |p: std::path::PathBuf| if p.is_absolute() { p } else { here.join(p) };
let git_path = |args: &[&str]| -> Result<std::path::PathBuf, IndexLookupError> {
let out = crate::git::stdout_raw_or_why(args).map_err(|why| IndexLookupError::Git {
args: args.join(" "),
why,
})?;
Ok(path_from_bytes(strip_one_newline(out)))
};
let file = match std::env::var_os("GIT_INDEX_FILE").filter(|v| !v.is_empty()) {
Some(named) => std::path::PathBuf::from(named),
None => git_path(&["rev-parse", "--git-path", "index"])?,
};
let git_dir = git_path(&["rev-parse", "--absolute-git-dir"])?;
Ok(CommitIndex {
file: absolute(file),
git_dir,
})
}
fn strip_one_newline(mut out: Vec<u8>) -> Vec<u8> {
if out.last() == Some(&b'\n') {
out.pop();
}
out
}
#[cfg(unix)]
fn path_from_bytes(bytes: Vec<u8>) -> std::path::PathBuf {
use std::os::unix::ffi::OsStringExt;
std::path::PathBuf::from(std::ffi::OsString::from_vec(bytes))
}
#[cfg(not(unix))]
fn path_from_bytes(bytes: Vec<u8>) -> std::path::PathBuf {
std::path::PathBuf::from(String::from_utf8_lossy(&bytes).into_owned())
}
pub fn check_timeout(settings: &crate::config::Settings) -> u64 {
*settings.timeout.get_or_init(|| {
crate::config::integer_or(settings, "greengate.timeout", 3600, 0..=86_400) as u64
})
}
pub fn idle_timeout(settings: &crate::config::Settings) -> u64 {
*settings.idle.get_or_init(|| {
crate::config::integer_or(settings, "greengate.idleTimeout", 120, 0..=86_400) as u64
})
}
pub fn idle_cpu_credit(settings: &crate::config::Settings) -> bool {
*settings
.idle_cpu
.get_or_init(|| crate::config::boolean_or(settings, "greengate.idleCpuCredit", true))
}
pub fn lock_wait(settings: &crate::config::Settings) -> LockWait {
match *settings.lock_wait.get_or_init(|| {
crate::config::integer_or(settings, "greengate.lockWait", 600, 0..=86_400) as u64
}) {
0 => LockWait::UntilCeiling,
s => LockWait::Secs(s),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LockWait {
Secs(u64),
UntilCeiling,
}
pub(crate) fn unique_name(prefix: &str) -> String {
use std::collections::hash_map::RandomState;
use std::hash::{BuildHasher, Hash, Hasher};
let pid = std::process::id();
let mut hasher = RandomState::new().build_hasher();
pid.hash(&mut hasher);
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_nanos()
.hash(&mut hasher);
format!("{prefix}-{pid}-{:016x}", hasher.finish())
}
pub fn human_secs(secs: u64) -> String {
match secs {
s if s < 60 => format!("{s}s"),
s if s < 3600 => format!("{}m{:02}s", s / 60, s % 60),
s => format!("{}h{:02}m", s / 3600, (s % 3600) / 60),
}
}
pub const LAST_LINE_CHARS: usize = 200;
pub const BUSY_MILLI_CORES: u32 = 100;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CpuState {
Off = 0,
Waiting = 1,
Measuring = 2,
Unavailable = 3,
}
pub struct Activity {
base: std::time::Instant,
last_out: std::sync::atomic::AtomicU64,
last_busy: std::sync::atomic::AtomicU64,
measured_since: std::sync::atomic::AtomicU64,
last_measured: std::sync::atomic::AtomicU64,
rate_milli: std::sync::atomic::AtomicU32,
interval_ms: std::sync::atomic::AtomicU32,
cpu: std::sync::atomic::AtomicU8,
wait_since: std::sync::atomic::AtomicU64,
wait_kind: std::sync::atomic::AtomicU8,
waited_ns: std::sync::atomic::AtomicU64,
last_wait_kind: std::sync::atomic::AtomicU8,
budget_secs: std::sync::atomic::AtomicU32,
load_avg_milli: std::sync::atomic::AtomicU32,
load_cores: std::sync::atomic::AtomicU32,
load_factor_milli: std::sync::atomic::AtomicU32,
last_line: std::sync::Mutex<String>,
}
impl Activity {
pub fn new() -> std::sync::Arc<Activity> {
std::sync::Arc::new(Activity {
base: std::time::Instant::now(),
last_out: Default::default(),
last_busy: Default::default(),
measured_since: Default::default(),
last_measured: Default::default(),
rate_milli: Default::default(),
interval_ms: Default::default(),
cpu: std::sync::atomic::AtomicU8::new(CpuState::Off as u8),
wait_since: Default::default(),
wait_kind: Default::default(),
waited_ns: Default::default(),
last_wait_kind: Default::default(),
budget_secs: Default::default(),
load_avg_milli: Default::default(),
load_cores: Default::default(),
load_factor_milli: Default::default(),
last_line: std::sync::Mutex::new(String::new()),
})
}
pub fn last_wait_kind(&self) -> Option<crate::hooks::wait::WaitKind> {
crate::hooks::wait::WaitKind::from_code(
self.last_wait_kind
.load(std::sync::atomic::Ordering::Relaxed),
)
}
pub fn stderr_line(&self, raw: &str) {
use std::sync::atomic::Ordering::Relaxed;
let line = crate::hooks::wait::strip_csi(raw);
if !line.trim().is_empty() {
let mut keep = self.last_line.lock().unwrap_or_else(|p| p.into_inner());
keep.clear();
keep.extend(line.trim().chars().take(LAST_LINE_CHARS));
}
match crate::hooks::wait::marker(&line) {
Some(kind) => {
self.wait_kind.store(kind.code(), Relaxed);
self.last_wait_kind.store(kind.code(), Relaxed);
let _ = self
.wait_since
.compare_exchange(0, self.now() + 1, Relaxed, Relaxed);
}
None => self.end_wait(),
}
}
pub fn end_wait(&self) {
use std::sync::atomic::Ordering::Relaxed;
let since = self.wait_since.swap(0, Relaxed);
if since != 0 {
let spent = self.now().saturating_sub(since - 1);
self.waited_ns.fetch_add(spent, Relaxed);
}
self.wait_kind.store(0, Relaxed);
}
pub fn waiting(&self) -> Option<(crate::hooks::wait::WaitKind, std::time::Duration)> {
use std::sync::atomic::Ordering::Relaxed;
let since = self.wait_since.load(Relaxed);
if since == 0 {
return None;
}
let kind = crate::hooks::wait::WaitKind::from_code(self.wait_kind.load(Relaxed))?;
Some((kind, self.since(since - 1)))
}
pub fn waited_total(&self) -> std::time::Duration {
use std::sync::atomic::Ordering::Relaxed;
let banked = std::time::Duration::from_nanos(self.waited_ns.load(Relaxed));
banked + self.waiting().map_or(std::time::Duration::ZERO, |(_, d)| d)
}
pub fn last_line(&self) -> Option<String> {
let keep = self.last_line.lock().unwrap_or_else(|p| p.into_inner());
(!keep.is_empty()).then(|| keep.clone())
}
pub fn set_load(&self, budget_secs: u64, load: crate::load::Load, factor_milli: u32) {
use std::sync::atomic::Ordering::Relaxed;
self.budget_secs
.store(u32::try_from(budget_secs).unwrap_or(u32::MAX), Relaxed);
self.load_avg_milli.store(load.avg1_milli, Relaxed);
self.load_cores.store(load.cores, Relaxed);
self.load_factor_milli.store(factor_milli, Relaxed);
}
pub fn load_scale(&self) -> Option<(u64, crate::load::Load, u32)> {
use std::sync::atomic::Ordering::Relaxed;
let factor = self.load_factor_milli.load(Relaxed);
if factor <= 1000 {
return None;
}
Some((
u64::from(self.budget_secs.load(Relaxed)),
crate::load::Load {
avg1_milli: self.load_avg_milli.load(Relaxed),
cores: self.load_cores.load(Relaxed),
},
factor,
))
}
fn offset(&self, at: std::time::Instant) -> u64 {
u64::try_from(at.saturating_duration_since(self.base).as_nanos()).unwrap_or(u64::MAX)
}
fn now(&self) -> u64 {
self.offset(std::time::Instant::now())
}
fn since(&self, offset: u64) -> std::time::Duration {
std::time::Duration::from_nanos(self.now().saturating_sub(offset))
}
pub fn touch(&self) {
self.last_out
.fetch_max(self.now(), std::sync::atomic::Ordering::Relaxed);
}
pub fn quiet_for(&self) -> std::time::Duration {
self.since(self.last_out.load(std::sync::atomic::Ordering::Relaxed))
}
pub fn silence_for(&self) -> std::time::Duration {
if self.waiting().is_some() {
std::time::Duration::ZERO
} else {
self.quiet_for()
}
}
pub fn still_for(&self) -> std::time::Duration {
let busy = self.last_busy.load(std::sync::atomic::Ordering::Relaxed);
self.silence_for().min(self.since(busy))
}
pub fn cpu_state(&self) -> CpuState {
match self.cpu.load(std::sync::atomic::Ordering::Relaxed) {
1 => CpuState::Waiting,
2 => CpuState::Measuring,
3 => CpuState::Unavailable,
_ => CpuState::Off,
}
}
fn set_cpu_state(&self, s: CpuState) {
self.cpu
.store(s as u8, std::sync::atomic::Ordering::Relaxed);
}
pub fn fresh_rate(&self) -> Option<u32> {
if self.cpu_state() != CpuState::Measuring {
return None;
}
let end = self
.last_measured
.load(std::sync::atomic::Ordering::Relaxed);
if end == 0 {
return None;
}
let every = u64::from(self.interval_ms.load(std::sync::atomic::Ordering::Relaxed));
let stale = std::time::Duration::from_millis(2 * every.max(1));
(self.since(end - 1) <= stale)
.then(|| self.rate_milli.load(std::sync::atomic::Ordering::Relaxed))
}
pub fn verdict(&self) -> CpuVerdict {
match self.cpu_state() {
CpuState::Off => return CpuVerdict::NotSampled,
CpuState::Waiting | CpuState::Unavailable => return CpuVerdict::Unmeasured,
CpuState::Measuring => {}
}
if let Some(rate) = self.fresh_rate().filter(|r| *r >= BUSY_MILLI_CORES) {
return CpuVerdict::BusyAtKill(rate);
}
let since = self
.measured_since
.load(std::sync::atomic::Ordering::Relaxed);
match (since, self.fresh_rate()) {
(s, Some(_)) if s != 0 => CpuVerdict::MeasuredIdle(self.since(s - 1).as_secs()),
_ => CpuVerdict::Unmeasured,
}
}
pub fn record(
&self,
obs: crate::proctree::Observation,
at: std::time::Instant,
interval: std::time::Duration,
) {
use std::sync::atomic::Ordering::Relaxed;
self.interval_ms.store(
u32::try_from(interval.as_millis()).unwrap_or(u32::MAX),
Relaxed,
);
match obs {
crate::proctree::Observation::Baseline => {
self.measured_since.store(self.offset(at) + 1, Relaxed);
self.set_cpu_state(CpuState::Waiting);
}
crate::proctree::Observation::Window(w) => {
let milli = w.milli_cores();
self.rate_milli.store(milli, Relaxed);
self.last_measured.store(self.offset(w.end) + 1, Relaxed);
if milli >= BUSY_MILLI_CORES {
self.last_busy.fetch_max(self.offset(w.start), Relaxed);
}
if w.gapped {
self.measured_since.store(self.offset(w.end) + 1, Relaxed);
}
self.set_cpu_state(CpuState::Measuring);
}
crate::proctree::Observation::Skipped => {}
crate::proctree::Observation::Unmeasured => {
self.measured_since.store(0, Relaxed);
self.set_cpu_state(CpuState::Unavailable);
}
}
}
pub fn enable_cpu(&self) {
self.set_cpu_state(CpuState::Waiting);
}
pub fn gate(&self) -> CpuGate {
match self.verdict() {
CpuVerdict::NotSampled => CpuGate::NotSampled,
CpuVerdict::MeasuredIdle(_) | CpuVerdict::BusyAtKill(_) => CpuGate::Measured,
CpuVerdict::Unmeasured => CpuGate::Unmeasured,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CpuGate {
NotSampled,
Measured,
Unmeasured,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CpuVerdict {
NotSampled,
MeasuredIdle(u64),
Unmeasured,
BusyAtKill(u32),
}
pub fn cores(milli: u32) -> String {
format!("~{}.{} cores", milli / 1000, (milli % 1000) / 100)
}
pub fn network_probe_budget(settings: &crate::config::Settings) -> u64 {
match check_timeout(settings) {
0 => 0,
t => t.min(30),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Why {
Ceiling(u64),
Silence(u64),
Waited(crate::hooks::wait::WaitKind, u64),
}
#[derive(Debug, Clone)]
pub struct Killed {
pub why: Why,
pub ran_secs: u64,
pub quiet_secs: Option<u64>,
pub cpu: CpuVerdict,
pub idle_secs: u64,
pub waiting: Option<(crate::hooks::wait::WaitKind, u64)>,
pub last_line: Option<String>,
pub load: Option<(crate::load::Load, u32)>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Clocks {
pub ceiling: Option<u64>,
pub silence: Option<u64>,
pub lock_wait: LockWait,
pub extended: Option<u64>,
pub scale: u64,
}
impl Clocks {
pub fn ceiling_only(wall_secs: u64) -> Clocks {
Clocks {
ceiling: (wall_secs > 0).then_some(wall_secs),
silence: None,
lock_wait: LockWait::UntilCeiling,
extended: None,
scale: 1,
}
}
pub fn from_settings(settings: &crate::config::Settings, idle_secs: u64) -> Clocks {
let wall = check_timeout(settings);
let scale = idle_load_scale(settings);
Clocks {
ceiling: (wall > 0).then_some(wall),
silence: (idle_secs > 0).then_some(idle_secs),
lock_wait: lock_wait(settings),
extended: (idle_secs > 0).then(|| idle_secs.saturating_mul(scale)),
scale,
}
}
}
const LOAD_EVERY: std::time::Duration = std::time::Duration::from_secs(5);
pub fn idle_load_scale(settings: &crate::config::Settings) -> u64 {
*settings.idle_load_scale.get_or_init(|| {
crate::config::host_integer_or(settings, "greengate.idleLoadScale", 4, 1..=16) as u64
})
}
pub enum Ran {
Status(std::process::ExitStatus),
TimedOut(Killed),
}
pub fn status_within(
settings: &crate::config::Settings,
cmd: &mut Command,
) -> std::io::Result<Ran> {
if crate::host_slots::before_spawn(settings)? {
cmd.env(crate::host_slots::HELD_ENV, "held");
}
crate::host_slots::bound(cmd);
status_within_secs(cmd, check_timeout(settings))
}
pub fn status_within_secs(cmd: &mut Command, budget_secs: u64) -> std::io::Result<Ran> {
if budget_secs == 0 {
return cmd.status().map(Ran::Status);
}
let mut child = cmd.spawn()?;
wait_within(&mut child, Clocks::ceiling_only(budget_secs), None)
}
fn run_observed(
settings: &crate::config::Settings,
cmd: &mut Command,
on_output: impl Fn(&[u8]) + Send + Sync + 'static,
ceiling_left: Option<u64>,
) -> std::io::Result<Ran> {
let shared = std::sync::Arc::new(on_output);
let for_stdout = std::sync::Arc::clone(&shared);
run_observed_split(
settings,
cmd,
move |bytes| for_stdout(bytes),
move |bytes| shared(bytes),
ceiling_left,
)
}
type OnBytes = std::sync::Arc<dyn Fn(&[u8]) + Send + Sync>;
fn run_observed_split(
settings: &crate::config::Settings,
cmd: &mut Command,
on_stdout: impl Fn(&[u8]) + Send + Sync + 'static,
on_stderr: impl Fn(&[u8]) + Send + Sync + 'static,
ceiling_left: Option<u64>,
) -> std::io::Result<Ran> {
if crate::host_slots::before_spawn(settings)? {
cmd.env(crate::host_slots::HELD_ENV, "held");
}
crate::host_slots::bound(cmd);
cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
let activity = Activity::new();
let on_stdout: OnBytes = std::sync::Arc::new(on_stdout);
let on_stderr: OnBytes = std::sync::Arc::new(on_stderr);
let mut child = cmd.spawn()?;
activity.touch();
let mut readers = Vec::new();
let pipes = [
(
child
.stdout
.take()
.map(|p| Box::new(p) as Box<dyn std::io::Read + Send>),
false,
on_stdout,
),
(
child
.stderr
.take()
.map(|p| Box::new(p) as Box<dyn std::io::Read + Send>),
true,
on_stderr,
),
];
for (pipe, is_stderr, on_output) in pipes {
let Some(pipe) = pipe else { continue };
let activity = std::sync::Arc::clone(&activity);
readers.push(std::thread::spawn(move || {
let mut pipe = pipe;
let mut chunk = [0u8; 4096];
let mut framer = crate::hooks::wait::LineFramer::default();
let mut pending: Vec<u8> = Vec::new();
loop {
match std::io::Read::read(&mut pipe, &mut chunk) {
Ok(0) | Err(_) => break,
Ok(n) => {
activity.touch();
if is_stderr {
for line in framer.feed(&chunk[..n]) {
activity.stderr_line(&line);
}
} else {
activity.end_wait();
}
pending.extend_from_slice(&chunk[..n]);
if let Some(end) = whole_lines(&pending) {
on_output(&pending[..end]);
pending.drain(..end);
}
}
}
}
if !pending.is_empty() {
on_output(&pending);
}
}));
}
let _attached = crate::live::current_sink()
.map(|(stage, idx)| stage.attach(idx, std::sync::Arc::clone(&activity)));
let idle = idle_timeout(settings);
let sampler = (idle > 0 && idle_cpu_credit(settings) && crate::proctree::SUPPORTED)
.then(|| CpuSampler::start(child.id(), std::sync::Arc::clone(&activity), idle));
let mut clocks = Clocks::from_settings(settings, idle);
if let Some(left) = ceiling_left {
clocks.ceiling = Some(left.max(1));
}
let ran = wait_within(&mut child, clocks, Some(&activity));
if let Some(s) = sampler {
s.stop();
}
for r in readers {
let _ = r.join();
}
if let Ok(Ran::Status(_)) = &ran {
let waited = activity.waited_total();
if waited >= std::time::Duration::from_secs(1) {
let what = activity
.last_wait_kind()
.map_or("a lock", crate::hooks::wait::WaitKind::describe);
say(&format!(
" (waited {} for {what})",
human_secs(waited.as_secs())
));
}
}
ran
}
struct CpuSampler {
stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
handle: std::thread::JoinHandle<()>,
}
impl CpuSampler {
fn start(pid: u32, activity: std::sync::Arc<Activity>, idle_secs: u64) -> CpuSampler {
activity.enable_cpu();
let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let flag = std::sync::Arc::clone(&stop);
let handle = std::thread::Builder::new()
.name("greengate-cpu".into())
.spawn(move || sample_loop(pid, &activity, idle_secs, &flag))
.expect("spawn the CPU sampler thread");
CpuSampler { stop, handle }
}
fn stop(self) {
self.stop.store(true, std::sync::atomic::Ordering::Relaxed);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(1);
while !self.handle.is_finished() && std::time::Instant::now() < deadline {
std::thread::sleep(std::time::Duration::from_millis(10));
}
if self.handle.is_finished() {
let _ = self.handle.join();
}
}
}
pub fn sampling_schedule(idle_secs: u64) -> (std::time::Duration, std::time::Duration) {
let ms = std::time::Duration::from_millis;
let budget = std::time::Duration::from_secs(idle_secs);
let first = (budget / 3)
.min(std::time::Duration::from_secs(30))
.max(ms(250));
let every = (budget / 4).clamp(ms(250), std::time::Duration::from_secs(10));
(first, every)
}
fn sample_loop(
pid: u32,
activity: &Activity,
idle_secs: u64,
stop: &std::sync::atomic::AtomicBool,
) {
use std::sync::atomic::Ordering::Relaxed;
let (first, every) = sampling_schedule(idle_secs);
let mut limits = crate::proctree::Limits::default();
if let Some(n) = std::env::var("GREENGATE_CPU_MAX_PROCS")
.ok()
.and_then(|v| v.trim().parse::<usize>().ok())
{
limits.max_procs = n;
}
let trace = std::env::var_os("GREENGATE_CPU_TRACE");
let mut tracker = crate::proctree::Tracker::default();
let nap = |d: std::time::Duration| {
let until = std::time::Instant::now() + d;
while !stop.load(Relaxed) && std::time::Instant::now() < until {
std::thread::sleep(std::time::Duration::from_millis(50));
}
};
while !stop.load(Relaxed) {
if activity.silence_for() < first {
tracker = crate::proctree::Tracker::default();
nap(std::time::Duration::from_millis(100));
continue;
}
let snap = crate::proctree::snapshot(pid, &tracker.seen(), &limits);
let at = std::time::Instant::now();
let traced = trace.as_ref().map(|_| match &snap {
crate::proctree::Snapshot::Complete(procs) => procs.clone(),
_ => Vec::new(),
});
let obs = tracker.observe(at, snap);
if let (Some(path), Some(procs)) = (&trace, traced) {
trace_sample(path, pid, &procs, &obs);
}
activity.record(obs, at, every);
nap(every);
}
}
fn trace_sample(
path: &std::ffi::OsStr,
root: u32,
procs: &[crate::proctree::Proc],
obs: &crate::proctree::Observation,
) {
use std::io::Write;
let Ok(mut f) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(path)
else {
return;
};
let mut text = String::new();
for p in procs {
text.push_str(&format!(
"{} {} {} {}\n",
p.id.pid, p.id.start, p.ppid, p.cpu_ns
));
}
let obs = match obs {
crate::proctree::Observation::Window(w) => {
format!("window {} milli-cores", w.milli_cores())
}
other => format!("{other:?}").to_lowercase(),
};
text.push_str(&format!("# root {root} {obs}\n"));
let _ = f.write_all(text.as_bytes());
}
pub fn status_streamed(
settings: &crate::config::Settings,
cmd: &mut Command,
retry: Retry,
) -> std::io::Result<Ran> {
let Some((stage, idx)) = crate::live::current_sink() else {
return status_within(settings, cmd);
};
if crate::live::watching() {
cmd.env("FORCE_COLOR", "1")
.env("CLICOLOR_FORCE", "1")
.env("CARGO_TERM_COLOR", "always");
}
let first = run_observed(
settings,
cmd,
{
let stage = std::sync::Arc::clone(&stage);
move |bytes| stage.append_raw(idx, bytes)
},
None,
);
stage.runner_exit(idx, exit_of(&first));
let Ok(Ran::TimedOut(k)) = &first else {
return first;
};
let Some(left) = retry_budget(retry, k, check_timeout(settings)) else {
return first;
};
let what = crate::host_slots::current_check()
.unwrap_or_else(|| cmd.get_program().to_string_lossy().into_owned());
say(&format!(
"{} was killed while it looked like it was waiting ({}); retrying once{}.",
hl(&what),
k.last_line.as_deref().unwrap_or(""),
match left {
Some(s) => format!(" with {} left", human_secs(s)),
None => String::new(),
}
));
let second = run_observed(
settings,
cmd,
{
let stage = std::sync::Arc::clone(&stage);
move |bytes| stage.append_raw(idx, bytes)
},
left,
);
stage.runner_exit(idx, exit_of(&second));
second
}
fn whole_lines(pending: &[u8]) -> Option<usize> {
match pending.iter().rposition(|&b| b == b'\n') {
Some(i) => Some(i + 1),
None if pending.len() >= LINE_HOLD => Some(pending.len()),
None => None,
}
}
const LINE_HOLD: usize = 64 * 1024;
fn exit_of(ran: &std::io::Result<Ran>) -> Option<i32> {
match ran {
Ok(Ran::Status(s)) => s.code(),
_ => None,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Retry {
Once,
Never,
}
pub fn retry_budget(retry: Retry, k: &Killed, ceiling: u64) -> Option<Option<u64>> {
if retry == Retry::Never || !matches!(k.why, Why::Silence(_)) {
return None;
}
if !k
.last_line
.as_deref()
.is_some_and(crate::hooks::wait::looks_like_wait)
{
return None;
}
if ceiling == 0 {
return Some(None);
}
let left = ceiling.saturating_sub(k.ran_secs);
(left >= k.idle_secs.max(1)).then_some(Some(left))
}
pub fn capture_within(
settings: &crate::config::Settings,
cmd: &mut Command,
) -> Option<(Ran, String)> {
let text = std::sync::Arc::new(std::sync::Mutex::new(String::new()));
let sink = std::sync::Arc::clone(&text);
let ran = run_observed(
settings,
cmd,
move |bytes| {
sink.lock()
.unwrap_or_else(|p| p.into_inner())
.push_str(&String::from_utf8_lossy(bytes));
},
None,
)
.ok()?;
let text = std::sync::Arc::try_unwrap(text)
.map(|m| m.into_inner().unwrap_or_else(|p| p.into_inner()))
.unwrap_or_default();
Some((ran, text))
}
pub struct CapturedOutput {
pub ran: Ran,
pub stdout: String,
pub stderr: String,
}
pub fn capture_stdout_within(
settings: &crate::config::Settings,
cmd: &mut Command,
) -> std::io::Result<CapturedOutput> {
let out = std::sync::Arc::new(std::sync::Mutex::new(Vec::<u8>::new()));
let err = std::sync::Arc::new(std::sync::Mutex::new(Vec::<u8>::new()));
let (out_sink, err_sink) = (std::sync::Arc::clone(&out), std::sync::Arc::clone(&err));
let ran = run_observed_split(
settings,
cmd,
move |bytes| {
out_sink
.lock()
.unwrap_or_else(|p| p.into_inner())
.extend_from_slice(bytes);
},
move |bytes| {
err_sink
.lock()
.unwrap_or_else(|p| p.into_inner())
.extend_from_slice(bytes);
},
None,
)?;
let take = |sink: std::sync::Arc<std::sync::Mutex<Vec<u8>>>| {
let bytes = std::mem::take(&mut *sink.lock().unwrap_or_else(|p| p.into_inner()));
String::from_utf8_lossy(&bytes).into_owned()
};
Ok(CapturedOutput {
ran,
stdout: take(out),
stderr: take(err),
})
}
pub(crate) fn wait_within(
child: &mut std::process::Child,
clocks: Clocks,
activity: Option<&Activity>,
) -> std::io::Result<Ran> {
let started = std::time::Instant::now();
let clocks = match activity {
Some(_) => clocks,
None => Clocks {
silence: None,
extended: None,
..clocks
},
};
if clocks.ceiling.is_none() && clocks.silence.is_none() {
return child.wait().map(Ran::Status);
}
let mut live = clocks;
let mut load: Option<(crate::load::Load, u32)> = None;
let mut next_load = started;
loop {
if let Some(status) = child.try_wait()? {
return Ok(Ran::Status(status));
}
let now = std::time::Instant::now();
if let (Some(idle), Some(a)) = (clocks.silence, activity) {
if clocks.scale > 1 && now >= next_load {
next_load = now + LOAD_EVERY;
if let Some(l) = crate::load::read() {
let factor = l.factor_milli(clocks.scale);
let applied = crate::load::scaled_budget(idle, l, clocks.scale, clocks.ceiling);
live.silence = Some(applied);
a.set_load(applied, l, factor);
load = (factor > 1000).then_some((l, factor));
}
}
}
let quiet = activity.map(|a| a.still_for());
let waiting = activity.and_then(Activity::waiting);
let gate = activity.map_or(CpuGate::NotSampled, Activity::gate);
let why = judge(now.duration_since(started), quiet, waiting, gate, &live);
if let Some(why) = why {
let _ = child.kill();
let _ = child.wait();
return Ok(Ran::TimedOut(Killed {
why,
ran_secs: now.duration_since(started).as_secs(),
quiet_secs: activity.map(|a| a.quiet_for().as_secs()),
cpu: activity.map_or(CpuVerdict::NotSampled, Activity::verdict),
idle_secs: clocks.silence.unwrap_or(0),
waiting: waiting.map(|(k, d)| (k, d.as_secs())),
last_line: activity.and_then(Activity::last_line),
load,
}));
}
std::thread::sleep(std::time::Duration::from_millis(25));
}
}
pub fn judge(
ran: std::time::Duration,
quiet: Option<std::time::Duration>,
waiting: Option<(crate::hooks::wait::WaitKind, std::time::Duration)>,
cpu: CpuGate,
clocks: &Clocks,
) -> Option<Why> {
if let Some(wall) = clocks.ceiling {
if ran >= std::time::Duration::from_secs(wall) {
return Some(Why::Ceiling(wall));
}
}
if let Some((kind, waited)) = waiting {
let budget = match clocks.lock_wait {
LockWait::Secs(s) => Some(s),
LockWait::UntilCeiling if clocks.ceiling.is_some() => None,
LockWait::UntilCeiling => clocks.extended,
};
return match budget {
Some(b) if waited >= std::time::Duration::from_secs(b) => Some(Why::Waited(kind, b)),
_ => None,
};
}
let budget = match cpu {
CpuGate::NotSampled | CpuGate::Measured => clocks.silence,
CpuGate::Unmeasured => clocks.extended.or(clocks.silence),
};
if let (Some(idle), Some(q)) = (budget, quiet) {
if q >= std::time::Duration::from_secs(idle) {
return Some(Why::Silence(idle));
}
}
None
}
pub fn say_timed_out(what: &str, k: Killed) {
match k.why {
Why::Silence(budget) => {
let stretched = match (k.cpu, k.load) {
_ if budget == k.idle_secs => String::new(),
(CpuVerdict::Unmeasured, _) => format!(
" (the extended budget, {} × {}: its CPU could not be measured)",
human_secs(k.idle_secs),
hl("greengate.idleLoadScale")
),
(_, Some((load, factor))) => format!(
" ({} stretched {} by a load average of {} on {} cores — {})",
human_secs(k.idle_secs),
crate::load::factor_text(factor),
load.avg1_text(),
load.cores,
hl("greengate.idleLoadScale")
),
_ => String::new(),
};
fail(&match k.cpu {
CpuVerdict::MeasuredIdle(covered) => format!(
"{} printed nothing for {}{stretched} and did no measurable CPU work \
(< 0.1 core) in the last {} of it; killed after {} — a tool this idle \
is stuck, not slow. {} raises the silence budget (0 disables)",
hl(what),
human_secs(budget),
human_secs(covered.max(1)),
human_secs(k.ran_secs),
hl("git config greengate.idleTimeout <secs>")
),
_ => format!(
"{} printed nothing for {}{stretched}{} and was killed after {} — a tool \
this quiet is usually stuck, not slow. {} raises the silence budget (0 \
disables)",
hl(what),
human_secs(budget),
if k.cpu == CpuVerdict::Unmeasured && stretched.is_empty() {
" (CPU not measured)"
} else {
""
},
human_secs(k.ran_secs),
hl("git config greengate.idleTimeout <secs>")
),
})
}
Why::Waited(kind, budget) => fail(&format!(
"{} waited {} for {} and was killed after {} — {}. {} raises the wait budget \
(0: until the ceiling)",
hl(what),
human_secs(budget),
kind.describe(),
human_secs(k.ran_secs),
kind.holders(),
hl("git config greengate.lockWait <secs>")
)),
Why::Ceiling(budget) => {
let verdict = match (k.quiet_secs, k.cpu) {
(_, _) if k.waiting.is_some() => {
let (kind, w) = k.waiting.expect("checked");
format!(
" It was waiting for {} for the last {} — {}.",
kind.describe(),
human_secs(w),
kind.holders()
)
}
(Some(q), CpuVerdict::BusyAtKill(m)) if k.idle_secs > 0 && q >= k.idle_secs => {
format!(
" It printed nothing for the last {} but kept its CPU busy ({}), so the \
silence budget did not stop it: a busy loop, or a tool that prints only \
at the end (give it a per-file reporter). {} kills quiet runs at the \
silence budget whatever their CPU.",
human_secs(q),
cores(m),
hl("git config greengate.idleCpuCredit false")
)
}
(Some(q), CpuVerdict::Unmeasured) if k.idle_secs > 0 && q >= k.idle_secs => {
format!(
" It printed nothing for the last {} and its CPU could not be measured, \
so only the extended silence budget applied. {} kills quiet runs at \
the silence budget whatever their CPU.",
human_secs(q),
hl("git config greengate.idleCpuCredit false")
)
}
(Some(q), _) if q < 30 => format!(
" It was still printing ({} since its last line): slow, not stuck.",
human_secs(q)
),
(Some(q), _) => format!(" Its last output was {} ago.", human_secs(q)),
(None, _) => String::new(),
};
fail(&format!(
"{} timed out: ran for {} and was killed at the ceiling. {} raises it \
(0 disables).{verdict}",
hl(what),
human_secs(budget),
hl("git config greengate.timeout <secs>")
))
}
}
}
pub fn bounded_success(settings: &crate::config::Settings, cmd: &mut Command, what: &str) -> bool {
match status_streamed(settings, cmd, Retry::Once) {
Ok(Ran::Status(s)) => s.success(),
Ok(Ran::TimedOut(b)) => {
say_timed_out(what, b);
false
}
Err(_) => false,
}
}
pub fn run(
settings: &crate::config::Settings,
root: &str,
argv: &[String],
extra: &[String],
) -> bool {
let Some((program, rest)) = argv.split_first() else {
return true;
};
let mut cmd = Command::new(program);
cmd.args(rest)
.args(extra)
.current_dir(root)
.stdin(Stdio::null());
strip_git_env(&mut cmd);
bounded_success(settings, &mut cmd, program)
}
pub fn run_quiet(
settings: &crate::config::Settings,
root: &str,
argv: &[String],
extra: &[String],
) -> bool {
let Some((program, rest)) = argv.split_first() else {
return true;
};
let mut cmd = Command::new(program);
cmd.args(rest)
.args(extra)
.current_dir(root)
.stdin(Stdio::null());
strip_git_env(&mut cmd);
match run_observed(settings, &mut cmd, |_| {}, None) {
Ok(Ran::Status(s)) => s.success(),
Ok(Ran::TimedOut(b)) => {
say_timed_out(program, b);
false
}
Err(_) => false,
}
}
pub fn fixing_enabled(settings: &crate::config::Settings) -> bool {
!not_the_index() && fixing_requested(settings)
}
pub fn fixing_requested(settings: &crate::config::Settings) -> bool {
*settings
.fixing
.get_or_init(|| crate::config::boolean_or(settings, "greengate.fix", false))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Restaged {
Nothing,
Staged,
Failed(Vec<String>),
}
static INDEX_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
pub fn restage(paths: &[String]) -> Restaged {
if not_the_index() {
return Restaged::Nothing;
}
let changed: Vec<String> = paths
.iter()
.filter(|p| !git::succeeds(&["diff", "--quiet", "--", p]))
.cloned()
.collect();
if changed.is_empty() {
return Restaged::Nothing;
}
let mut args = vec!["add", "--"];
args.extend(changed.iter().map(String::as_str));
let _serialised = INDEX_LOCK.lock().unwrap_or_else(|e| e.into_inner());
const BACKOFF_MS: [u64; 3] = [50, 150, 400];
if git::succeeds(&args) {
return Restaged::Staged;
}
for wait in BACKOFF_MS {
std::thread::sleep(std::time::Duration::from_millis(wait));
if git::succeeds(&args) {
return Restaged::Staged;
}
}
Restaged::Failed(changed)
}
pub fn ok(settings: &crate::config::Settings, msg: &str) {
if crate::live::quiet(settings) {
return;
}
crate::live::say(&format!("{} {msg}", valid_sign()));
}
pub fn fail(msg: &str) {
if crate::host_slots::deferred_here() {
return;
}
crate::live::say(&format!("{} {msg}", error_sign()));
}
pub fn warn(msg: &str) {
if crate::host_slots::deferred_here() {
return;
}
crate::live::say(&format!("{} {msg}", warning_sign()));
}
pub fn say(msg: &str) {
crate::live::say(msg);
}
pub fn hl(s: &str) -> String {
crate::ui::highlight(s)
}
#[cfg(test)]
mod tests {
#[cfg(unix)]
#[test]
fn capture_stdout_within_keeps_the_streams_apart() {
let settings = crate::config::Settings::default();
let mut cmd = std::process::Command::new(super::program("sh"));
cmd.args([
"-c",
"printf '{\"a\":1}'; printf 'npm warn x\\n' >&2; exit 3",
]);
let captured = super::capture_stdout_within(&settings, &mut cmd).expect("sh runs");
assert_eq!(captured.stdout, "{\"a\":1}", "stdout alone");
assert_eq!(captured.stderr, "npm warn x\n", "stderr alone");
match captured.ran {
super::Ran::Status(s) => assert_eq!(s.code(), Some(3), "the real exit status"),
super::Ran::TimedOut(_) => panic!("a one-line child timed out"),
}
}
#[cfg(unix)]
#[test]
fn stderr_only_output_leaves_stdout_empty() {
let settings = crate::config::Settings::default();
let mut cmd = std::process::Command::new(super::program("sh"));
cmd.args(["-c", "printf 'only a warning\\n' >&2"]);
let captured = super::capture_stdout_within(&settings, &mut cmd).expect("sh runs");
assert!(
captured.stdout.is_empty(),
"stdout must be empty, got {:?}",
captured.stdout
);
assert_eq!(captured.stderr, "only a warning\n");
assert!(matches!(captured.ran, super::Ran::Status(s) if s.success()));
}
#[test]
fn only_the_one_newline_git_prints_is_stripped() {
assert_eq!(super::strip_one_newline(b"/r/.git\n".to_vec()), b"/r/.git");
assert_eq!(super::strip_one_newline(b"/r/x\r\n".to_vec()), b"/r/x\r");
assert_eq!(super::strip_one_newline(b"/r/x".to_vec()), b"/r/x");
}
#[test]
fn a_git_path_becomes_the_same_path() {
assert_eq!(
super::path_from_bytes(b"/r/.git/index".to_vec()),
std::path::PathBuf::from("/r/.git/index")
);
}
#[test]
fn a_lookup_error_says_git_s_reason() {
let e = super::IndexLookupError::Git {
args: "rev-parse --git-path index".into(),
why: "fatal: not a git repository".into(),
};
assert_eq!(
e.to_string(),
"git rev-parse --git-path index failed: fatal: not a git repository"
);
}
fn window(
start: std::time::Instant,
end: std::time::Instant,
milli: u64,
) -> crate::proctree::Observation {
let wall = u64::try_from(end.duration_since(start).as_nanos())
.unwrap_or(u64::MAX)
.max(1);
let gain = wall * milli / 1000;
crate::proctree::Observation::Window(crate::proctree::Window {
start,
end,
gain_ns: gain,
gapped: false,
})
}
#[test]
fn a_gapped_window_is_never_claimed_as_measured_idle() {
use super::{Activity, CpuVerdict};
use crate::proctree::{Observation, Window};
let s = std::time::Duration::from_secs;
let every = s(10);
let a = Activity::new();
a.enable_cpu();
let t0 = std::time::Instant::now() - s(30);
a.record(Observation::Baseline, t0, every);
a.record(Observation::Skipped, t0 + s(10), every);
let gap_end = std::time::Instant::now();
a.record(
Observation::Window(Window {
start: t0,
end: gap_end,
gain_ns: 0,
gapped: true,
}),
gap_end,
every,
);
assert_eq!(a.verdict(), CpuVerdict::MeasuredIdle(0));
assert_eq!(a.gate(), super::CpuGate::Measured);
let busy = Activity::new();
busy.enable_cpu();
busy.record(Observation::Baseline, t0, every);
busy.record(Observation::Skipped, t0 + s(10), every);
let now = std::time::Instant::now();
busy.record(window_gapped(t0, now, 3000), now, every);
assert_eq!(busy.verdict(), CpuVerdict::BusyAtKill(3000));
assert!(busy.still_for() < s(1));
}
fn window_gapped(
start: std::time::Instant,
end: std::time::Instant,
milli: u64,
) -> crate::proctree::Observation {
match window(start, end, milli) {
crate::proctree::Observation::Window(w) => {
crate::proctree::Observation::Window(crate::proctree::Window { gapped: true, ..w })
}
o => o,
}
}
#[test]
fn the_sampling_schedule_follows_the_budget_within_floors() {
use super::sampling_schedule;
let ms = std::time::Duration::from_millis;
let third = |secs: u64| std::time::Duration::from_secs(secs) / 3;
assert_eq!(sampling_schedule(1), (third(1), ms(250)));
assert_eq!(sampling_schedule(2), (third(2), ms(500)));
assert_eq!(sampling_schedule(120), (ms(30_000), ms(10_000)));
assert_eq!(sampling_schedule(0), (ms(250), ms(250)));
}
#[test]
fn busy_work_resets_the_still_time_but_not_the_output_silence() {
use super::Activity;
let a = Activity::new();
a.touch();
std::thread::sleep(std::time::Duration::from_millis(60));
let quiet = a.quiet_for();
assert!(a.still_for() >= quiet.saturating_sub(std::time::Duration::from_millis(5)));
a.enable_cpu();
let now = std::time::Instant::now();
a.record(
window(now - std::time::Duration::from_millis(10), now, 2000),
now,
std::time::Duration::from_secs(1),
);
assert!(a.still_for() < std::time::Duration::from_millis(40));
assert!(a.quiet_for() >= std::time::Duration::from_millis(60));
}
#[test]
fn the_cpu_verdict_claims_only_what_was_measured() {
use super::{Activity, CpuVerdict};
use crate::proctree::Observation;
let s = std::time::Duration::from_secs;
let every = s(10);
let off = Activity::new();
assert_eq!(off.verdict(), CpuVerdict::NotSampled);
let waiting = Activity::new();
waiting.enable_cpu();
assert_eq!(waiting.verdict(), CpuVerdict::Unmeasured);
let now = std::time::Instant::now();
let before = now - s(1);
let idle = Activity::new();
idle.enable_cpu();
let t0 = std::time::Instant::now();
idle.record(Observation::Baseline, t0, every);
std::thread::sleep(std::time::Duration::from_millis(1050));
let t1 = std::time::Instant::now();
idle.record(window(t0, t1, 20), t1, every);
assert_eq!(idle.verdict(), CpuVerdict::MeasuredIdle(1));
let busy = Activity::new();
busy.enable_cpu();
busy.record(Observation::Baseline, before, every);
busy.record(window(before, now, 3900), now, every);
assert_eq!(busy.verdict(), CpuVerdict::BusyAtKill(3900));
let broken = Activity::new();
broken.enable_cpu();
broken.record(Observation::Baseline, before, every);
broken.record(window(before, now, 20), now, every);
broken.record(Observation::Unmeasured, now, every);
assert_eq!(broken.verdict(), CpuVerdict::Unmeasured);
assert_eq!(broken.gate(), super::CpuGate::Unmeasured);
assert_eq!(off.gate(), super::CpuGate::NotSampled);
assert_eq!(idle.gate(), super::CpuGate::Measured);
assert_eq!(busy.gate(), super::CpuGate::Measured);
}
#[test]
fn a_stale_rate_expires() {
use super::{Activity, CpuVerdict};
use crate::proctree::Observation;
let a = Activity::new();
a.enable_cpu();
let then = std::time::Instant::now();
let tick = std::time::Duration::from_millis(5);
let earlier = then - std::time::Duration::from_secs(1);
a.record(Observation::Baseline, earlier, tick);
a.record(window(earlier, then, 3000), then, tick);
std::thread::sleep(std::time::Duration::from_millis(40));
assert_eq!(a.fresh_rate(), None);
assert_eq!(a.verdict(), CpuVerdict::Unmeasured);
}
#[test]
fn cores_read_as_one_decimal() {
assert_eq!(super::cores(3900), "~3.9 cores");
assert_eq!(super::cores(420), "~0.4 cores");
assert_eq!(super::cores(100), "~0.1 cores");
}
#[test]
fn the_clocks_judge_silence_and_ceiling_separately() {
use super::{judge, CpuGate, Why};
use std::time::Duration as D;
let s = D::from_secs;
let c = |ceiling: Option<u64>, silence: Option<u64>| super::Clocks {
ceiling,
silence,
lock_wait: super::LockWait::Secs(600),
extended: silence,
scale: 1,
};
assert_eq!(
judge(
s(900),
Some(s(0)),
None,
CpuGate::NotSampled,
&c(Some(3600), Some(5))
),
None
);
assert_eq!(
judge(
s(900),
Some(s(4)),
None,
CpuGate::NotSampled,
&c(Some(3600), Some(5))
),
None
);
assert_eq!(
judge(
s(30),
Some(s(5)),
None,
CpuGate::NotSampled,
&c(Some(3600), Some(5))
),
Some(Why::Silence(5))
);
assert_eq!(
judge(
s(900),
None,
None,
CpuGate::NotSampled,
&c(Some(3600), Some(5))
),
None
);
assert_eq!(
judge(
s(3600),
Some(s(0)),
None,
CpuGate::NotSampled,
&c(Some(3600), Some(120))
),
Some(Why::Ceiling(3600))
);
assert_eq!(
judge(
s(3600),
Some(s(600)),
None,
CpuGate::NotSampled,
&c(Some(3600), Some(120))
),
Some(Why::Ceiling(3600))
);
assert_eq!(
judge(
s(86_400),
Some(s(86_400)),
None,
CpuGate::NotSampled,
&c(None, None)
),
None
);
assert_eq!(
judge(
s(86_400),
Some(s(1)),
None,
CpuGate::NotSampled,
&c(None, Some(120))
),
None
);
}
#[test]
fn a_declared_wait_answers_to_its_own_budget() {
use super::{judge, Clocks, CpuGate, LockWait, Why};
use crate::hooks::wait::{CargoLockWhat, WaitKind};
use std::time::Duration as D;
let s = D::from_secs;
let kind = WaitKind::CargoLock(CargoLockWhat::BuildDirectory);
let clocks = Clocks {
ceiling: Some(3600),
silence: Some(120),
lock_wait: LockWait::Secs(600),
extended: Some(480),
scale: 4,
};
assert_eq!(
judge(
s(1300),
Some(s(0)),
Some((kind, s(599))),
CpuGate::Measured,
&clocks
),
None
);
assert_eq!(
judge(
s(1300),
Some(s(0)),
Some((kind, s(600))),
CpuGate::Measured,
&clocks
),
Some(Why::Waited(kind, 600))
);
assert_eq!(
judge(
s(3600),
Some(s(0)),
Some((kind, s(3000))),
CpuGate::Measured,
&clocks
),
Some(Why::Ceiling(3600))
);
let until = Clocks {
lock_wait: LockWait::UntilCeiling,
..clocks
};
assert_eq!(
judge(
s(3000),
Some(s(0)),
Some((kind, s(2900))),
CpuGate::Measured,
&until
),
None
);
let open = Clocks {
ceiling: None,
..until
};
assert_eq!(
judge(
s(3000),
Some(s(0)),
Some((kind, s(479))),
CpuGate::Measured,
&open
),
None
);
assert_eq!(
judge(
s(3000),
Some(s(0)),
Some((kind, s(480))),
CpuGate::Measured,
&open
),
Some(Why::Waited(kind, 480))
);
}
#[test]
fn a_wait_like_silence_kill_earns_one_retry_under_the_remaining_ceiling() {
use super::{retry_budget, CpuVerdict, Killed, Retry, Why};
use crate::hooks::wait::{CargoLockWhat, WaitKind};
let k = |why: Why, line: &str, ran: u64| Killed {
why,
ran_secs: ran,
quiet_secs: Some(ran),
cpu: CpuVerdict::MeasuredIdle(1),
idle_secs: 120,
waiting: None,
last_line: Some(line.to_string()),
load: None,
};
let wait = "waiting for lock on x";
assert_eq!(
retry_budget(Retry::Once, &k(Why::Silence(120), wait, 120), 3600),
Some(Some(3480))
);
assert_eq!(
retry_budget(Retry::Once, &k(Why::Silence(120), wait, 120), 0),
Some(None)
);
assert_eq!(
retry_budget(Retry::Never, &k(Why::Silence(120), wait, 120), 3600),
None
);
assert_eq!(
retry_budget(
Retry::Once,
&k(Why::Silence(120), "test_lock.py::x", 120),
3600
),
None
);
assert_eq!(
retry_budget(Retry::Once, &k(Why::Ceiling(3600), wait, 3600), 3600),
None
);
let waited = Why::Waited(WaitKind::CargoLock(CargoLockWhat::BuildDirectory), 600);
assert_eq!(retry_budget(Retry::Once, &k(waited, wait, 700), 3600), None);
assert_eq!(
retry_budget(Retry::Once, &k(Why::Silence(120), wait, 3500), 3600),
None
);
}
#[test]
fn an_unmeasured_cpu_answers_to_the_extended_budget() {
use super::{judge, Clocks, CpuGate, LockWait, Why};
use std::time::Duration as D;
let s = D::from_secs;
let clocks = Clocks {
ceiling: None,
silence: Some(120),
lock_wait: LockWait::Secs(600),
extended: Some(480),
scale: 4,
};
assert_eq!(
judge(s(500), Some(s(300)), None, CpuGate::Unmeasured, &clocks),
None
);
assert_eq!(
judge(s(500), Some(s(479)), None, CpuGate::Unmeasured, &clocks),
None
);
assert_eq!(
judge(s(500), Some(s(480)), None, CpuGate::Unmeasured, &clocks),
Some(Why::Silence(480))
);
assert_eq!(
judge(s(500), Some(s(120)), None, CpuGate::Measured, &clocks),
Some(Why::Silence(120))
);
assert_eq!(
judge(s(500), Some(s(120)), None, CpuGate::NotSampled, &clocks),
Some(Why::Silence(120))
);
let off = Clocks {
silence: None,
extended: None,
..clocks
};
assert_eq!(
judge(s(86_400), Some(s(86_400)), None, CpuGate::Unmeasured, &off),
None
);
}
#[test]
fn a_marker_line_pauses_the_silence_clock_until_another_line() {
use super::Activity;
use crate::hooks::wait::{CargoLockWhat, WaitKind};
let a = Activity::new();
a.touch();
assert_eq!(a.waiting(), None);
a.stderr_line(" Blocking waiting for file lock on package cache");
std::thread::sleep(std::time::Duration::from_millis(30));
let (kind, waited) = a.waiting().expect("a wait is in progress");
assert_eq!(kind, WaitKind::CargoLock(CargoLockWhat::PackageCache));
assert!(waited >= std::time::Duration::from_millis(30));
assert_eq!(a.silence_for(), std::time::Duration::ZERO);
assert_eq!(a.still_for(), std::time::Duration::ZERO);
assert!(a.quiet_for() >= std::time::Duration::from_millis(30));
a.stderr_line("\u{1b}[1m Blocking\u{1b}[0m waiting for file lock on build directory");
let (kind, again) = a.waiting().expect("still waiting");
assert_eq!(kind, WaitKind::CargoLock(CargoLockWhat::BuildDirectory));
assert!(again >= waited);
a.touch();
a.stderr_line(" Checking foo v0.1.0");
assert_eq!(a.waiting(), None);
assert!(a.waited_total() >= std::time::Duration::from_millis(30));
assert_eq!(a.last_wait_kind(), Some(kind));
assert_eq!(a.last_line().as_deref(), Some("Checking foo v0.1.0"));
assert!(a.silence_for() < std::time::Duration::from_millis(20));
a.stderr_line("Waiting to acquire write lock for `x`");
assert!(a.waiting().is_some());
a.end_wait();
assert_eq!(a.waiting(), None);
}
#[cfg(unix)]
#[test]
fn the_deadline_kills_a_sleeper_and_spares_a_finisher() {
let started = std::time::Instant::now();
let mut slow = Command::new(program("sleep"));
slow.arg("300").stdin(Stdio::null());
match status_within_secs(&mut slow, 1) {
Ok(Ran::TimedOut(Killed {
why: Why::Ceiling(1),
quiet_secs: None,
..
})) => {}
other => panic!("expected TimedOut(1), got {:?}", other.map(|_| "ran")),
}
assert!(
started.elapsed() < std::time::Duration::from_secs(60),
"the kill did not happen at the deadline"
);
let mut quick = Command::new(program("true"));
quick.stdin(Stdio::null());
match status_within_secs(&mut quick, 60) {
Ok(Ran::Status(s)) => assert!(s.success()),
other => panic!("expected a clean exit, got {:?}", other.map(|_| "?")),
}
}
use super::*;
#[test]
fn which_finds_a_real_binary_and_not_a_fake_one() {
assert!(which("git").is_some());
assert!(which("definitely-not-a-real-binary-xyz").is_none());
}
#[test]
#[cfg(windows)]
fn windows_prefers_an_executable_extension_over_a_bare_file() {
let dir = std::env::temp_dir().join("greengate-which-order");
let _ = std::fs::create_dir_all(&dir);
std::fs::write(dir.join("faketool"), "#!/bin/sh\n").unwrap();
std::fs::write(dir.join("faketool.cmd"), "@echo off\n").unwrap();
let found = which_on(dir.as_os_str(), "faketool").unwrap();
assert!(found.ends_with(".cmd"), "got {found}");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn restage_distinguishes_nothing_from_failure() {
let _cwd = crate::TEST_CWD.lock().unwrap_or_else(|p| p.into_inner());
let outside = std::env::temp_dir()
.join("greengate-restage-outside-any-repo")
.to_string_lossy()
.into_owned();
assert_eq!(
restage(std::slice::from_ref(&outside)),
Restaged::Failed(vec![outside]),
"a `git add` git refuses must report Failed, never Nothing"
);
assert_eq!(
restage(&[]),
Restaged::Nothing,
"no paths is nothing to do, and nothing wrong"
);
}
#[test]
fn no_hook_spawns_a_bare_program_name() {
let needle = concat!("Command", "::new(");
let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/src/hooks");
let mut scanned = 0usize;
for entry in std::fs::read_dir(dir).expect("hooks dir").flatten() {
let path = entry.path();
if path.extension().and_then(|e| e.to_str()) != Some("rs") {
continue;
}
scanned += 1;
let src = std::fs::read_to_string(&path).expect("read a hook module");
for (n, line) in src.lines().enumerate() {
if line.trim_start().starts_with("//") {
continue;
}
let Some(after) = line.split_once(needle) else {
continue;
};
assert!(
!after.1.starts_with('"'),
"{}:{} spawns a bare name — route it through `program()` or \
the path `which()` already resolved: {}",
path.display(),
n + 1,
line.trim()
);
}
}
assert!(
scanned > 10,
"the scan found almost nothing: {scanned} files"
);
}
#[test]
fn first_existing_picks_the_earliest_present_name() {
let dir = std::env::temp_dir().join("greengate-first-existing-test");
let _ = std::fs::create_dir_all(&dir);
let root = dir.to_string_lossy().into_owned();
let _ = std::fs::write(dir.join("second"), "x");
assert_eq!(
first_existing(&root, &["first", "second", "third"]).as_deref(),
Some("second")
);
assert_eq!(first_existing(&root, &["nope"]), None);
let _ = std::fs::remove_dir_all(&dir);
}
}
#[cfg(test)]
mod js_tool_tests {
use super::{package_json_declares, version_in};
#[test]
fn package_json_declares_a_dev_dependency() {
assert!(package_json_declares(
r#"{"devDependencies":{"prettier":"3.9.10"}}"#,
"prettier"
));
assert!(package_json_declares(
"{\n \"name\": \"x\",\n \"dependencies\": { \"eslint\": \"9.1.0\" }\n}\n",
"eslint"
));
assert!(package_json_declares(
"\u{feff}{\"devDependencies\":{\"prettier\":\"3.9.10\"}}",
"prettier"
));
}
#[test]
fn package_json_declares_gives_up_on_deep_nesting() {
let deep = format!(
"{{\"x\":{}{},\"devDependencies\":{{\"prettier\":\"3\"}}}}",
"[".repeat(100_000),
"]".repeat(100_000)
);
assert!(!package_json_declares(&deep, "prettier"));
let fine = format!(
"{{\"x\":{}{},\"devDependencies\":{{\"prettier\":\"3\"}}}}",
"[".repeat(50),
"]".repeat(50)
);
assert!(package_json_declares(&fine, "prettier"));
}
#[test]
fn package_json_declares_nothing_else() {
let not = |text: &str| assert!(!package_json_declares(text, "prettier"), "{text}");
not(r#"{"prettier":{"semi":false}}"#);
not(r#"{"devDependencies":{"prettier-plugin-x":"1.0.0"}}"#);
not(r#"{"peerDependencies":{"prettier":"3"}}"#);
not(r#"{"optionalDependencies":{"prettier":"3"}}"#);
not(r#"{"pnpm":{"overrides":{"prettier":"3"}}}"#);
not(r#"{"scripts":{"prettier":"prettier --check ."}}"#);
not(r#"{"metadata":{"devDependencies":{"prettier":"3"}}}"#);
not(r#"{"list":[{"dependencies":{"prettier":"3"}}]}"#);
not(r#"{"description":"say \"devDependencies\": {\"prettier\": 1}"}"#);
not(r#"{"devDependencies":{"prettier":"3.9.10""#);
not(r#"{"devDependencies":{"prettier":"3.9.10"}} trailing"#);
not("");
}
#[test]
fn package_json_declares_past_escapes_and_nesting() {
assert!(package_json_declares(
r#"{"description":"a \"quoted\" {brace}","x":[1,{"y":null}],"devDependencies":{"a":"1","prettier":"^3"}}"#,
"prettier"
));
}
#[test]
fn version_in_skips_warnings_and_strips_v() {
assert_eq!(version_in("3.9.10\n").as_deref(), Some("3.9.10"));
assert_eq!(version_in("v9.14.0").as_deref(), Some("9.14.0"));
assert_eq!(
version_in("npm warn exec The following package was not found\n3.9.10").as_deref(),
Some("3.9.10")
);
assert_eq!(
version_in("(node:1) Warning: x\n3.0.0-beta.1").as_deref(),
Some("3.0.0-beta.1")
);
assert_eq!(version_in("3.9.10\u{1b}[2J").as_deref(), Some("3.9.10"));
assert_eq!(version_in("no version here\n1.2"), None);
assert_eq!(version_in(""), None);
}
}