use std::ops::Range;
use std::path::Path;
pub const START: &str = crate::names::AGENTS_START;
pub const END: &str = crate::names::AGENTS_END;
const OLD_START: &str = crate::names::old::AGENTS_START;
const OLD_END: &str = crate::names::old::AGENTS_END;
pub fn has_markers(text: &str) -> bool {
text.contains(START) || text.contains(OLD_START)
}
pub fn generate_block(settings: &crate::config::Settings) -> String {
let clocks = |secs: u64| match secs {
0 => "no limit".to_string(),
s => crate::hooks::common::human_secs(s),
};
let idle = clocks(crate::hooks::common::idle_timeout(settings));
let ceiling = clocks(crate::hooks::common::check_timeout(settings));
let prefixes = crate::vocabulary::BRANCH_PREFIXES
.iter()
.map(|p| p.name)
.collect::<Vec<_>>()
.join(", ");
format!(
"{START}\n\
\n\
## Git hooks (greengate)\n\
\n\
This repository enforces pre-commit / pre-push checks. Ask the registry\n\
rather than guessing before assuming a change is safe:\n\
\n\
```sh\n\
greengate list --json\n\
greengate list --json --stage pre-push --pushed # exactly what pushing next gates\n\
```\n\
\n\
Each check reports its _effective_ severity (`block`/`warn`, including any\n\
`greengate.severity.*` override) and whether it fires here. The same output\n\
carries `commit_style`: the subject and description limits `commit-msg`\n\
enforces, and where the type's gitmoji is placed. It also carries\n\
`branch_style`: name a branch `<prefix>/<name>` BEFORE creating it —\n\
prefixes are {prefixes} — because `pre-push` refuses a\n\
new branch that breaks the pattern, at the end of the work instead of the\n\
start.\n\
\n\
`git commit` and `git push` both run their checks first, and neither is\n\
instant: pre-commit can invoke formatters, linters or clippy (a workspace\n\
build), and pre-push gates include the test suite. Push with `greengate land`:\n\
it runs every push gate the push owes on a snapshot of the exact commit,\n\
with no connection open, then pushes, and the push itself skips them (git\n\
connects before pre-push runs, and a remote may drop the idle session while a\n\
suite runs). A bare `git push` whose push gates have not run on its tree is\n\
refused at once (`greengate.pushGates refuse`, the default): run `greengate land`, or\n\
`greengate rehearse --wait` (or `greengate run --stamp`) first and push again. Push a\n\
release tag with `greengate land --tag <name>`: it runs the release audits on the\n\
tagged commit first, which a branch rehearsal never does. Where\n\
`greengate.rehearseOnCommit` is on, every commit already starts that rehearsal in\n\
the background and `--wait` only follows it. Give these commands the\n\
longest timeout your tooling allows, never its default: here a check is\n\
killed only after {idle} of silence or {ceiling} in total\n\
(`greengate.idleTimeout` / `greengate.timeout`) — and on Linux and macOS a silent\n\
check whose processes are busy on CPU is not \"silent\": it can run to the\n\
{ceiling} ceiling. A check waiting on a cargo or uv lock answers to\n\
`greengate.lockWait` instead, the silence budget stretches with the machine's\n\
load (`greengate.idleLoadScale`), and a heavy check (clippy, a test suite) may\n\
first queue for a host slot (`greengate.hostSlots`) while other worktrees run\n\
theirs. A test suite may legitimately run for most of that. If your tooling caps a foreground command below it,\n\
run the command in the background and read its result when it exits —\n\
while it runs, a line a minute on stderr says which check is alive and\n\
when it last printed. A push killed mid-suite pushed nothing; a commit\n\
killed mid-check committed nothing, and your unstaged work stays parked\n\
until the next run says how to recover it. Neither is the checks failing —\n\
it is the timeout. Run both bare and check the effect (`git log --oneline\n\
-1`, `git ls-remote origin <branch>`): trimming their output with `| tail`\n\
reports the pipe's exit status, so a killed or rejected run reads as\n\
success.\n\
\n\
Never bypass with `--no-verify`. To change enforcement, downgrade it\n\
intentionally instead:\n\
\n\
```sh\n\
git config greengate.severity.<check-id> warn\n\
```\n\
\n\
`commit-msg` takes neither `hook.skip` nor a severity override. Write the\n\
message it asks for, or change what it asks for — `greengate setup`, or\n\
`greengate.commit.*` directly.\n\
\n\
{END}\n"
)
}
pub fn generate_pointer() -> String {
format!(
"{START}\n\
\n\
## Git hooks (greengate)\n\
\n\
This repository enforces pre-commit / pre-push checks that can REJECT a\n\
commit or a push. What runs, the branch-name rule, and why `git commit`\n\
and `git push` both need a long timeout — or a background run — are in\n\
[AGENTS.md](AGENTS.md) — read it before committing. Both files are\n\
generated: run `greengate agents-md` after changing either.\n\
\n\
{END}\n"
)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MarkerState {
Malformed,
}
fn marker_range(text: &str) -> Result<Option<(Range<usize>, Pair)>, MarkerState> {
if let Some(range) = pair_range(text, START, END)? {
return Ok(Some((range, Pair::New)));
}
Ok(pair_range(text, OLD_START, OLD_END)?.map(|range| (range, Pair::Old)))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Pair {
New,
Old,
}
fn in_pair(block: &str, pair: Pair) -> std::borrow::Cow<'_, str> {
if pair == Pair::Old {
block
.replacen(START, OLD_START, 1)
.replacen(END, OLD_END, 1)
.into()
} else {
block.into()
}
}
fn pair_range(
text: &str,
start_marker: &str,
end_marker: &str,
) -> Result<Option<Range<usize>>, MarkerState> {
let start = text.find(start_marker);
let end = text.find(end_marker);
match (start, end) {
(None, None) => Ok(None),
(Some(s), Some(e)) if e >= s + start_marker.len() => {
let mut range_end = e + end_marker.len();
if text[range_end..].starts_with('\n') {
range_end += 1; }
Ok(Some(s..range_end))
}
_ => Err(MarkerState::Malformed),
}
}
pub fn desired_file_content(
settings: &crate::config::Settings,
existing: &str,
) -> Result<String, MarkerState> {
desired_with(existing, &generate_block(settings))
}
pub fn desired_pointer_content(existing: &str) -> Result<String, MarkerState> {
desired_with(existing, &generate_pointer())
}
fn desired_with(existing: &str, block: &str) -> Result<String, MarkerState> {
match marker_range(existing)? {
Some((range, pair)) => Ok(format!(
"{}{}{}",
&existing[..range.start],
in_pair(block, pair),
&existing[range.end..]
)),
None if existing.is_empty() => Ok(block.to_string()),
None => {
let sep = if existing.ends_with("\n\n") {
""
} else if existing.ends_with('\n') {
"\n"
} else {
"\n\n"
};
Ok(format!("{existing}{sep}{block}"))
}
}
}
pub fn write(settings: &crate::config::Settings, path: &Path) -> Result<(), String> {
write_with(path, &generate_block(settings))
}
pub fn write_pointer(path: &Path) -> Result<(), String> {
write_with(path, &generate_pointer())
}
fn write_with(path: &Path, block: &str) -> Result<(), String> {
let existing = std::fs::read_to_string(path).unwrap_or_default();
let content = desired_with(&existing, block).map_err(|_| {
format!(
"{}: has an unpaired greengate marker — fix or remove it by hand, \
then re-run `greengate agents-md`",
path.display()
)
})?;
if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
std::fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
}
std::fs::write(path, content).map_err(|e| format!("{}: {e}", path.display()))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CheckResult {
NotPresent,
MatchesGenerated,
Drifted,
}
pub fn check(settings: &crate::config::Settings, path: &Path) -> Result<CheckResult, String> {
check_with(path, &generate_block(settings))
}
pub fn check_pointer(path: &Path) -> Result<CheckResult, String> {
check_with(path, &generate_pointer())
}
fn check_with(path: &Path, block: &str) -> Result<CheckResult, String> {
let existing = std::fs::read_to_string(path).unwrap_or_default();
match marker_range(&existing) {
Err(_) => Err(format!(
"{}: has an unpaired greengate marker — fix or remove it by hand",
path.display()
)),
Ok(None) => Ok(CheckResult::NotPresent),
Ok(Some((range, pair))) => {
if existing[range] == *in_pair(block, pair) {
Ok(CheckResult::MatchesGenerated)
} else {
Ok(CheckResult::Drifted)
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn test_settings() -> crate::config::Settings {
crate::config::Settings::default()
}
#[test]
fn no_file_produces_just_the_block() {
assert_eq!(
desired_file_content(&test_settings(), "").unwrap(),
generate_block(&test_settings())
);
}
#[test]
fn the_generated_markdown_satisfies_prettier() {
for (what, text) in [
("block", generate_block(&test_settings())),
("pointer", generate_pointer()),
] {
assert!(
text.starts_with(&format!("{START}\n\n")),
"{what}: prettier wants a blank line after the opening comment"
);
assert!(
text.ends_with(&format!("\n\n{END}\n")),
"{what}: prettier wants a blank line before the closing comment"
);
let opener = text
.as_bytes()
.windows(2)
.any(|w| w[0] == b'*' && w[1].is_ascii_alphanumeric());
assert!(
!opener,
"{what}: prettier rewrites *emphasis* into _emphasis_, and a \
formatted file then reads as drift — emit underscores"
);
}
}
#[test]
fn the_pointer_is_generated_and_therefore_checkable() {
let p = generate_pointer();
assert!(p.starts_with(START) && p.ends_with(&format!("{END}\n")));
assert!(p.contains("AGENTS.md"), "it has to name where to look");
assert_ne!(
p,
generate_block(&test_settings()),
"a signpost, not a second copy"
);
assert!(
!p.contains("greengate list --json"),
"the registry command lives in ONE place; duplicating it here is \
the drift this design avoids"
);
let existing = "# Notes\n\nsomething the repo wrote\n";
let once = desired_pointer_content(existing).unwrap();
assert!(once.starts_with(existing), "never touches what was there");
assert!(once.ends_with(&p));
assert_eq!(
desired_pointer_content(&once).unwrap(),
once,
"re-running is a no-op, so `--check` can be trusted"
);
}
#[test]
fn no_markers_appends_with_one_blank_line() {
let got = desired_file_content(&test_settings(), "# My Project\n\nSome docs.\n").unwrap();
assert!(got.starts_with("# My Project\n\nSome docs.\n\n"));
assert!(got.ends_with(&generate_block(&test_settings())));
}
#[test]
fn no_markers_and_no_trailing_newline_still_gets_a_blank_line() {
let got = desired_file_content(&test_settings(), "# My Project").unwrap();
assert!(got.starts_with("# My Project\n\n"));
}
#[test]
fn existing_markers_are_replaced_and_everything_else_survives() {
let before = format!("before\n\n{START}\nstale\n{END}\n\nafter\n");
let got = desired_file_content(&test_settings(), &before).unwrap();
assert!(got.starts_with("before\n\n"));
assert!(got.ends_with("\n\nafter\n"));
assert!(got.contains(&generate_block(&test_settings())));
assert!(!got.contains("stale"));
}
#[test]
fn an_old_marker_block_is_regenerated_under_its_own_pair() {
let before = format!("before\n\n{OLD_START}\nstale\n{OLD_END}\n\nafter\n");
let got = desired_file_content(&test_settings(), &before).unwrap();
let block = generate_block(&test_settings());
assert_eq!(
got,
format!("before\n\n{}\nafter\n", in_pair(&block, Pair::Old))
);
assert!(!got.contains(START), "{got}");
assert!(has_markers(&before) && has_markers(&got));
assert!(!has_markers("no block here\n"));
let dir = std::env::temp_dir().join(format!("agents-md-old-pair-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("AGENTS.md");
std::fs::write(&file, &got).unwrap();
assert_eq!(
check(&test_settings(), &file).unwrap(),
CheckResult::MatchesGenerated,
"an unswept file is not drifted for its markers"
);
let _ = std::fs::remove_dir_all(&dir); }
#[test]
fn an_unpaired_old_marker_is_refused() {
assert_eq!(
desired_file_content(&test_settings(), &format!("{OLD_START}\nno end\n")),
Err(MarkerState::Malformed)
);
}
#[test]
fn applying_twice_is_idempotent() {
let once = desired_file_content(&test_settings(), "preamble\n").unwrap();
let twice = desired_file_content(&test_settings(), &once).unwrap();
assert_eq!(once, twice);
}
#[test]
fn an_unpaired_marker_is_refused_not_guessed_at() {
assert_eq!(
desired_file_content(&test_settings(), &format!("{START}\nno end here\n")),
Err(MarkerState::Malformed)
);
assert_eq!(
desired_file_content(&test_settings(), &format!("no start\n{END}\n")),
Err(MarkerState::Malformed)
);
}
#[test]
fn end_appearing_before_start_is_malformed_not_reordered() {
assert_eq!(
desired_file_content(&test_settings(), &format!("{END}\n...\n{START}\n...\n")),
Err(MarkerState::Malformed)
);
}
#[test]
fn check_reports_not_present_for_a_missing_file() {
let missing_file = std::env::temp_dir().join("greengate-agents-md-test-nonexistent-xyz");
let _ = std::fs::remove_file(&missing_file); assert_eq!(
check(&test_settings(), &missing_file).unwrap(),
CheckResult::NotPresent
);
}
#[test]
fn check_reports_matches_generated_after_a_write() {
let scratch_file = std::env::temp_dir().join(format!(
"greengate-agents-md-test-{}-match",
std::process::id()
));
std::fs::write(&scratch_file, generate_block(&test_settings())).unwrap();
assert_eq!(
check(&test_settings(), &scratch_file).unwrap(),
CheckResult::MatchesGenerated
);
let _ = std::fs::remove_file(&scratch_file); }
#[test]
fn check_reports_drifted_for_a_stale_block() {
let scratch_file = std::env::temp_dir().join(format!(
"greengate-agents-md-test-{}-drift",
std::process::id()
));
std::fs::write(&scratch_file, format!("{START}\nstale\n{END}\n")).unwrap();
assert_eq!(
check(&test_settings(), &scratch_file).unwrap(),
CheckResult::Drifted
);
let _ = std::fs::remove_file(&scratch_file); }
}