Skip to main content

release_kit/
assess.rs

1//! Classify a target repository before anything lands.
2//!
3//! The assessment is read-only evidence plus one classification computed
4//! from it by an explicit rule: `greenfield` when the target carries no
5//! release mechanism and no release history, `brownfield` when a release
6//! mechanism is already in place — a tool's configuration, a landed
7//! destination, a landed block — and `needs-decision` when the target
8//! shows release activity that no recognized mechanism explains: tags
9//! with no tool behind them, or a second long-lived branch. The rule
10//! lives here so a routing skill reads a verdict it can cite instead of
11//! judging "some release setup" by feel. The gathering spawns git and
12//! reads the disk; the rule itself is pure and unit-tested.
13
14use std::process::Command;
15
16use camino::Utf8Path;
17use serde::Serialize;
18
19use crate::diagnostic::{Diagnostic, Reason};
20use crate::error::RkError;
21use crate::landing::{self, manifest};
22
23// The trunk and the release-line prefix come from the target's own
24// committed configuration; a target that states neither keeps the
25// compiled defaults in `crate::config`.
26
27/// Files that mark a release mechanism, whichever tool owns it.
28///
29/// release-kit's own destinations are judged separately, as collisions;
30/// this list is what other tools leave behind: every configuration name
31/// semantic-release and `GoReleaser` document, release-plz's dotted form,
32/// the workflow names a hand-rolled publish commonly takes, and a
33/// changelog. `package.json` joins the list only when it carries the
34/// top-level `release` key semantic-release reads, judged in [`gather`].
35pub const RELEASE_MARKERS: [&str; 23] = [
36    ".release-plz.toml",
37    ".releaserc",
38    ".releaserc.cjs",
39    ".releaserc.js",
40    ".releaserc.json",
41    ".releaserc.mjs",
42    ".releaserc.yaml",
43    ".releaserc.yml",
44    "release.config.cjs",
45    "release.config.js",
46    "release.config.mjs",
47    ".config/goreleaser.yaml",
48    ".config/goreleaser.yml",
49    ".goreleaser.yaml",
50    ".goreleaser.yml",
51    "goreleaser.yaml",
52    "goreleaser.yml",
53    ".github/workflows/publish.yml",
54    ".github/workflows/publish.yaml",
55    ".github/workflows/release.yaml",
56    ".github/workflows/release-drafter.yml",
57    "CHANGELOG.md",
58    "CHANGES.md",
59];
60
61/// Branch names that conventionally outlive a topic.
62///
63/// A second one beside the trunk is the retired two-branch flow, or a
64/// trunk under another name, and either is a migration step. A
65/// `release/<line>` branch — the convention's own long-lived form — is
66/// recognized by its prefix.
67pub const LONG_LIVED_BRANCHES: [&str; 11] = [
68    "master",
69    "main",
70    "trunk",
71    "develop",
72    "development",
73    "dev",
74    "staging",
75    "next",
76    "release",
77    "production",
78    "prod",
79];
80
81/// What the target is, for routing: the corpus verdict, computed from the
82/// repository's evidence alone.
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
84#[serde(rename_all = "kebab-case")]
85pub enum Classification {
86    /// No release mechanism and no release history: land the workflow.
87    Greenfield,
88    /// A release mechanism is in place: migrate, never land beside it.
89    Brownfield,
90    /// Release activity no mechanism explains: the operator decides.
91    NeedsDecision,
92}
93
94impl Classification {
95    /// The kebab-case verdict word, as the JSON serializes it.
96    #[must_use]
97    pub const fn as_str(self) -> &'static str {
98        match self {
99            Self::Greenfield => "greenfield",
100            Self::Brownfield => "brownfield",
101            Self::NeedsDecision => "needs-decision",
102        }
103    }
104}
105
106/// The landing record's presence, the one fact `rk status` owns that the
107/// routing needs before it reads the full report.
108#[derive(Debug, Serialize)]
109pub struct Landing {
110    /// Whether `.release-kit/manifest.json` exists and reads.
111    pub recorded: bool,
112    /// The release-kit version the record names, where one exists.
113    #[serde(skip_serializing_if = "Option::is_none")]
114    pub rk_version: Option<String>,
115}
116
117/// The evidence the classification is computed from.
118#[derive(Debug, Serialize)]
119pub struct Evidence {
120    /// The landing record, present or not.
121    pub landing: Landing,
122    /// The technologies the version files name, zero or many.
123    pub technologies: Vec<&'static str>,
124    /// The forge the origin remote maps to, where one is recognized.
125    #[serde(skip_serializing_if = "Option::is_none")]
126    pub forge: Option<&'static str>,
127    /// The project path from the origin remote, where one exists.
128    #[serde(skip_serializing_if = "Option::is_none")]
129    pub repo: Option<String>,
130    /// Release-mechanism files of other tools found at the target.
131    pub release_markers: Vec<String>,
132    /// Landable destinations already present: a whole file that exists, or
133    /// a block destination whose marked block is present.
134    pub collisions: Vec<String>,
135    /// Whether the target is a git repository the evidence below reads.
136    pub git: bool,
137    /// How many tags the repository holds.
138    pub tags: usize,
139    /// Long-lived branches found besides the trunk, local or remote.
140    pub long_lived_branches: Vec<String>,
141}
142
143/// Compute the verdict from the evidence. Pure, so the rule is testable
144/// without a repository.
145#[must_use]
146pub const fn classify(evidence: &Evidence) -> Classification {
147    if !evidence.release_markers.is_empty() || !evidence.collisions.is_empty() {
148        return Classification::Brownfield;
149    }
150    if evidence.tags > 0 || !evidence.long_lived_branches.is_empty() {
151        return Classification::NeedsDecision;
152    }
153    Classification::Greenfield
154}
155
156/// The repository's facts alone, with no record read: what the planner
157/// gathers beside its own read of the record.
158#[derive(Debug)]
159pub struct Facts {
160    /// The technologies the version files name, zero or many.
161    pub technologies: Vec<&'static str>,
162    /// The forge the origin remote maps to, where one is recognized.
163    pub forge: Option<&'static str>,
164    /// The project path from the origin remote, where one exists.
165    pub repo: Option<String>,
166    /// Release-mechanism files of other tools found at the target.
167    pub release_markers: Vec<String>,
168    /// Landable destinations already present.
169    pub collisions: Vec<String>,
170    /// Whether the target is a git repository.
171    pub git: bool,
172    /// How many tags the repository holds.
173    pub tags: usize,
174    /// Long-lived branches found besides the trunk.
175    pub long_lived_branches: Vec<String>,
176}
177
178/// Gather the evidence at `target`, reading and never writing.
179///
180/// # Errors
181///
182/// Returns the record's own failure taxonomy for an unreadable or unknown
183/// landing record — a broken record must not silently classify —
184/// [`RkError::Io`] for a disk read that fails for a reason other than
185/// absence, and [`RkError::Subprocess`] where git runs but cannot answer
186/// for a repository, because an observation that cannot be read is not a
187/// pass and must never read as an absent release history.
188pub fn gather(target: &Utf8Path) -> Result<Evidence, RkError> {
189    let record = manifest::load(target)?;
190    let landing = Landing {
191        recorded: record.is_some(),
192        rk_version: record.map(|manifest| manifest.rk_version),
193    };
194    let facts = gather_facts(target)?;
195    Ok(Evidence {
196        landing,
197        technologies: facts.technologies,
198        forge: facts.forge,
199        repo: facts.repo,
200        release_markers: facts.release_markers,
201        collisions: facts.collisions,
202        git: facts.git,
203        tags: facts.tags,
204        long_lived_branches: facts.long_lived_branches,
205    })
206}
207
208/// Gather the repository's facts at `target`, the record aside.
209///
210/// # Errors
211///
212/// [`RkError::Io`] for a disk read that fails for a reason other than
213/// absence, and [`RkError::Subprocess`] where git runs but cannot answer
214/// for a repository.
215pub fn gather_facts(target: &Utf8Path) -> Result<Facts, RkError> {
216    let detected = crate::detect::detect(target.as_std_path());
217    let mut release_markers: Vec<String> = RELEASE_MARKERS
218        .iter()
219        .filter(|marker| target.join(marker).is_file())
220        .map(|marker| (*marker).to_owned())
221        .collect();
222    if package_json_names_a_release(target)? {
223        release_markers.push("package.json".to_owned());
224    }
225    release_markers.sort();
226    let mut collisions = Vec::new();
227    for destination in landing::destinations() {
228        if landing::read_recorded(target, destination)?.is_some() {
229            collisions.push(destination.to_owned());
230        }
231    }
232    collisions.sort();
233    let (git, tags, long_lived_branches) = git_evidence(target)?;
234    Ok(Facts {
235        technologies: crate::detect::technologies_of(target.as_std_path()),
236        forge: detected.forge.map(crate::detect::Forge::as_str),
237        repo: detected.repo,
238        release_markers,
239        collisions,
240        git,
241        tags,
242        long_lived_branches,
243    })
244}
245
246/// Whether `package.json` carries the top-level `release` key
247/// semantic-release reads its configuration from. An ordinary Node
248/// project's manifest is not a release marker; only that key is.
249fn package_json_names_a_release(target: &Utf8Path) -> Result<bool, RkError> {
250    let path = target.join("package.json");
251    let bytes = match std::fs::read(&path) {
252        Ok(bytes) => bytes,
253        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
254        Err(e) => return Err(RkError::Io(e)),
255    };
256    // A manifest that does not parse is not evidence of a release
257    // mechanism; the tool that would read it fails on it too.
258    Ok(serde_json::from_slice::<serde_json::Value>(&bytes)
259        .ok()
260        .and_then(|value| value.get("release").map(|_| ()))
261        .is_some())
262}
263
264/// The git-borne evidence: whether the target is a repository, how many
265/// tags it holds, and which long-lived branches stand beside the trunk.
266///
267/// A directory git positively reports as no repository answers `false`
268/// and empty — an observation, never a failure, because a plain
269/// directory is a legitimate greenfield. Every other refusal — a
270/// corrupt repository, an ownership refusal, a git that does not run —
271/// is an error, because an unreadable history must not read as none.
272fn git_evidence(target: &Utf8Path) -> Result<(bool, usize, Vec<String>), RkError> {
273    let trunk = crate::config::trunk_of(target.as_std_path())?;
274    let line_prefix = crate::config::line_prefix_of(target.as_std_path())?;
275    let (trunk, line_prefix) = (trunk.as_str(), line_prefix.as_str());
276    match git_lines(target, &["rev-parse", "--git-dir"]) {
277        Ok(_) => {}
278        Err(GitFailure::NotARepository) => return Ok((false, 0, Vec::new())),
279        Err(GitFailure::Other(error)) => return Err(error),
280    }
281    let tags = git_lines(target, &["tag", "--list"]).map_err(GitFailure::into_error)?;
282    let refs = git_lines(
283        target,
284        &[
285            "for-each-ref",
286            "--format=%(refname)",
287            "refs/heads",
288            "refs/remotes",
289        ],
290    )
291    .map_err(GitFailure::into_error)?;
292    Ok((
293        true,
294        tags.len(),
295        long_lived_among(&refs, trunk, line_prefix),
296    ))
297}
298
299/// The long-lived branch names among `refs`, given as full ref names.
300///
301/// `refs/heads/<name>` keeps its whole name, `refs/remotes/<remote>/<name>`
302/// drops the remote alone, and a remote `HEAD` pointer is skipped. A
303/// name is long-lived when it is a catalog entry other than the trunk or
304/// carries the release-line prefix; each appears once, sorted.
305#[must_use]
306pub fn long_lived_among(refs: &[String], trunk: &str, line_prefix: &str) -> Vec<String> {
307    let mut names = std::collections::BTreeSet::new();
308    for reference in refs {
309        let name = if let Some(local) = reference.strip_prefix("refs/heads/") {
310            local
311        } else if let Some(remote) = reference.strip_prefix("refs/remotes/") {
312            match remote.split_once('/') {
313                Some((_, "HEAD")) | None => continue,
314                Some((_, name)) => name,
315            }
316        } else {
317            continue;
318        };
319        let catalogued = name != trunk && LONG_LIVED_BRANCHES.contains(&name);
320        if catalogued || name.starts_with(line_prefix) {
321            names.insert(name.to_owned());
322        }
323    }
324    names.into_iter().collect()
325}
326
327/// Why one git call gave no answer.
328enum GitFailure {
329    /// Git ran and said the target is not a repository.
330    NotARepository,
331    /// Git did not run, or ran and refused for another reason.
332    Other(RkError),
333}
334
335impl GitFailure {
336    /// After the target is known to be a repository, every failure is
337    /// the same kind: a history that cannot be read.
338    fn into_error(self) -> RkError {
339        match self {
340            Self::NotARepository => RkError::subprocess(
341                Diagnostic::new(
342                    Reason::SubprocessFailed,
343                    "git stopped answering for a repository it had just recognized",
344                )
345                .expected("a readable repository"),
346            ),
347            Self::Other(error) => error,
348        }
349    }
350}
351
352/// The non-empty stdout lines of one git call.
353///
354/// The call answers for the `-C` target alone: the variables a running
355/// hook exports are scrubbed, so an inherited `GIT_DIR` cannot redirect
356/// the probe at another repository, and the locale is pinned to `C`, so
357/// the one diagnostic this module reads — git's own "not a git
358/// repository" — arrives untranslated.
359fn git_lines(target: &Utf8Path, args: &[&str]) -> Result<Vec<String>, GitFailure> {
360    let mut command = Command::new(crate::probes::git_bin());
361    for var in crate::maintenance::GIT_HOOK_VARS {
362        command.env_remove(var);
363    }
364    let out = command
365        .env("LC_ALL", "C")
366        .env_remove("LANGUAGE")
367        .arg("-C")
368        .arg(target)
369        .args(args)
370        .output()
371        .map_err(|error| {
372            GitFailure::Other(RkError::subprocess(
373                Diagnostic::new(
374                    Reason::SubprocessSpawn,
375                    format!("git could not be spawned: {error}"),
376                )
377                .expected("git on PATH, or RK_GIT_BIN naming it"),
378            ))
379        })?;
380    if !out.status.success() {
381        let stderr = String::from_utf8_lossy(&out.stderr);
382        if stderr.contains("not a git repository") {
383            return Err(GitFailure::NotARepository);
384        }
385        return Err(GitFailure::Other(RkError::subprocess(
386            Diagnostic::new(
387                Reason::SubprocessFailed,
388                format!(
389                    "git {} failed at {target}: {}",
390                    args.join(" "),
391                    stderr.trim()
392                ),
393            )
394            .expected("git answering for the target, or a target that is not a repository")
395            .action("an unreadable history is not an absent one; repair the repository or its ownership before classifying"),
396        )));
397    }
398    Ok(String::from_utf8_lossy(&out.stdout)
399        .lines()
400        .map(str::trim)
401        .filter(|line| !line.is_empty())
402        .map(str::to_owned)
403        .collect())
404}
405
406#[cfg(test)]
407mod tests {
408    use super::{Classification, Evidence, Landing, classify, long_lived_among};
409
410    /// The trunk is never evidence against itself; only the remote
411    /// segment is stripped, so a topic branch whose last segment is a
412    /// catalog name stays a topic branch; a release line is recognized
413    /// by its prefix; a remote HEAD pointer is skipped; each name once.
414    #[test]
415    fn long_lived_branches_are_read_from_the_full_ref_names() {
416        let refs: Vec<String> = [
417            "refs/heads/master",
418            "refs/remotes/origin/master",
419            "refs/remotes/origin/HEAD",
420            "refs/heads/develop",
421            "refs/remotes/origin/develop",
422            "refs/heads/feat/x",
423            "refs/heads/feat/develop",
424            "refs/remotes/origin/main",
425            "refs/heads/release/1.2",
426            "refs/remotes/upstream/release/1.2",
427        ]
428        .iter()
429        .map(|name| (*name).to_owned())
430        .collect();
431        assert_eq!(
432            long_lived_among(&refs, "master", "release/"),
433            vec!["develop", "main", "release/1.2"]
434        );
435        assert!(
436            long_lived_among(&["refs/heads/master".to_owned()], "master", "release/").is_empty()
437        );
438        assert!(
439            long_lived_among(
440                &["refs/heads/feat/develop".to_owned()],
441                "master",
442                "release/"
443            )
444            .is_empty()
445        );
446    }
447
448    #[test]
449    fn the_verdict_words_are_the_wire_form() {
450        for (classification, word) in [
451            (Classification::Greenfield, "greenfield"),
452            (Classification::Brownfield, "brownfield"),
453            (Classification::NeedsDecision, "needs-decision"),
454        ] {
455            assert_eq!(classification.as_str(), word);
456            assert_eq!(
457                serde_json::to_string(&classification).expect("serializes"),
458                format!("\"{word}\"")
459            );
460        }
461    }
462
463    fn evidence() -> Evidence {
464        Evidence {
465            landing: Landing {
466                recorded: false,
467                rk_version: None,
468            },
469            technologies: Vec::new(),
470            forge: None,
471            repo: None,
472            release_markers: Vec::new(),
473            collisions: Vec::new(),
474            git: true,
475            tags: 0,
476            long_lived_branches: Vec::new(),
477        }
478    }
479
480    #[test]
481    fn nothing_is_greenfield() {
482        assert_eq!(classify(&evidence()), Classification::Greenfield);
483    }
484
485    #[test]
486    fn a_release_marker_or_a_collision_is_brownfield() {
487        let with_marker = Evidence {
488            release_markers: vec!["CHANGELOG.md".into()],
489            ..evidence()
490        };
491        assert_eq!(classify(&with_marker), Classification::Brownfield);
492        let with_collision = Evidence {
493            collisions: vec!["release-plz.toml".into()],
494            ..evidence()
495        };
496        assert_eq!(classify(&with_collision), Classification::Brownfield);
497    }
498
499    /// A mechanism outranks unexplained activity: tags beside a marker
500    /// are a history the mechanism made, not a question.
501    #[test]
502    fn a_mechanism_beside_activity_is_still_brownfield() {
503        let both = Evidence {
504            release_markers: vec!["CHANGELOG.md".into()],
505            tags: 7,
506            long_lived_branches: vec!["develop".into()],
507            ..evidence()
508        };
509        assert_eq!(classify(&both), Classification::Brownfield);
510    }
511
512    #[test]
513    fn activity_with_no_mechanism_needs_a_decision() {
514        let tagged = Evidence {
515            tags: 1,
516            ..evidence()
517        };
518        assert_eq!(classify(&tagged), Classification::NeedsDecision);
519        let branched = Evidence {
520            long_lived_branches: vec!["develop".into()],
521            ..evidence()
522        };
523        assert_eq!(classify(&branched), Classification::NeedsDecision);
524    }
525}