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 payload
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};
22use crate::setup::context::TRUNK_BRANCH;
23
24/// The prefix of the convention's own long-lived branch form.
25const RELEASE_LINE_PREFIX: &str = "release/";
26
27/// Files that mark a release mechanism, whichever tool owns it.
28///
29/// The payload'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.
82#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
83#[serde(rename_all = "kebab-case")]
84pub enum Classification {
85    /// No release mechanism and no release history: land the workflow.
86    Greenfield,
87    /// A release mechanism is in place: migrate, never land beside it.
88    Brownfield,
89    /// Release activity no mechanism explains: the operator decides.
90    NeedsDecision,
91}
92
93impl Classification {
94    /// The kebab-case verdict word, as the JSON serializes it.
95    #[must_use]
96    pub const fn as_str(self) -> &'static str {
97        match self {
98            Self::Greenfield => "greenfield",
99            Self::Brownfield => "brownfield",
100            Self::NeedsDecision => "needs-decision",
101        }
102    }
103}
104
105/// The landing record's presence, the one fact `rk status` owns that the
106/// routing needs before it reads the full report.
107#[derive(Debug, Serialize)]
108pub struct Landing {
109    /// Whether `.release-kit/manifest.json` exists and reads.
110    pub recorded: bool,
111    /// The release-kit version the record names, where one exists.
112    #[serde(skip_serializing_if = "Option::is_none")]
113    pub rk_version: Option<String>,
114}
115
116/// The evidence the classification is computed from.
117#[derive(Debug, Serialize)]
118pub struct Evidence {
119    /// The landing record, present or not.
120    pub landing: Landing,
121    /// The technology the version file names, where one is found.
122    #[serde(skip_serializing_if = "Option::is_none")]
123    pub tech: Option<&'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    /// Payload 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 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/// Gather the evidence at `target`, reading and never writing.
157///
158/// # Errors
159///
160/// Returns the record's own failure taxonomy for an unreadable or unknown
161/// landing record — a broken record must not silently classify —
162/// [`RkError::Io`] for a disk read that fails for a reason other than
163/// absence, and [`RkError::Subprocess`] where git runs but cannot answer
164/// for a repository, because an observation that cannot be read is not a
165/// pass and must never read as an absent release history.
166pub fn gather(target: &Utf8Path) -> Result<Evidence, RkError> {
167    let record = manifest::load(target)?;
168    let landing = Landing {
169        recorded: record.is_some(),
170        rk_version: record.map(|manifest| manifest.rk_version),
171    };
172    let detected = crate::detect::detect(target.as_std_path());
173    let mut release_markers: Vec<String> = RELEASE_MARKERS
174        .iter()
175        .filter(|marker| target.join(marker).is_file())
176        .map(|marker| (*marker).to_owned())
177        .collect();
178    if package_json_names_a_release(target)? {
179        release_markers.push("package.json".to_owned());
180    }
181    release_markers.sort();
182    let mut collisions = Vec::new();
183    for destination in landing::destinations() {
184        if landing::read_recorded(target, destination)?.is_some() {
185            collisions.push(destination.to_owned());
186        }
187    }
188    collisions.sort();
189    let (git, tags, long_lived_branches) = git_evidence(target)?;
190    Ok(Evidence {
191        landing,
192        tech: crate::detect::tech_of(target.as_std_path()),
193        forge: detected.forge.map(crate::detect::Forge::as_str),
194        repo: detected.repo,
195        release_markers,
196        collisions,
197        git,
198        tags,
199        long_lived_branches,
200    })
201}
202
203/// Whether `package.json` carries the top-level `release` key
204/// semantic-release reads its configuration from. An ordinary Node
205/// project's manifest is not a release marker; only that key is.
206fn package_json_names_a_release(target: &Utf8Path) -> Result<bool, RkError> {
207    let path = target.join("package.json");
208    let bytes = match std::fs::read(&path) {
209        Ok(bytes) => bytes,
210        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
211        Err(e) => return Err(RkError::Io(e)),
212    };
213    // A manifest that does not parse is not evidence of a release
214    // mechanism; the tool that would read it fails on it too.
215    Ok(serde_json::from_slice::<serde_json::Value>(&bytes)
216        .ok()
217        .and_then(|value| value.get("release").map(|_| ()))
218        .is_some())
219}
220
221/// The git-borne evidence: whether the target is a repository, how many
222/// tags it holds, and which long-lived branches stand beside the trunk.
223///
224/// A directory git positively reports as no repository answers `false`
225/// and empty — an observation, never a failure, because a plain
226/// directory is a legitimate greenfield. Every other refusal — a
227/// corrupt repository, an ownership refusal, a git that does not run —
228/// is an error, because an unreadable history must not read as none.
229fn git_evidence(target: &Utf8Path) -> Result<(bool, usize, Vec<String>), RkError> {
230    match git_lines(target, &["rev-parse", "--git-dir"]) {
231        Ok(_) => {}
232        Err(GitFailure::NotARepository) => return Ok((false, 0, Vec::new())),
233        Err(GitFailure::Other(error)) => return Err(error),
234    }
235    let tags = git_lines(target, &["tag", "--list"]).map_err(GitFailure::into_error)?;
236    let refs = git_lines(
237        target,
238        &[
239            "for-each-ref",
240            "--format=%(refname)",
241            "refs/heads",
242            "refs/remotes",
243        ],
244    )
245    .map_err(GitFailure::into_error)?;
246    Ok((true, tags.len(), long_lived_among(&refs)))
247}
248
249/// The long-lived branch names among `refs`, given as full ref names.
250///
251/// `refs/heads/<name>` keeps its whole name, `refs/remotes/<remote>/<name>`
252/// drops the remote alone, and a remote `HEAD` pointer is skipped. A
253/// name is long-lived when it is a catalog entry other than the trunk or
254/// carries the release-line prefix; each appears once, sorted.
255#[must_use]
256pub fn long_lived_among(refs: &[String]) -> Vec<String> {
257    let mut names = std::collections::BTreeSet::new();
258    for reference in refs {
259        let name = if let Some(local) = reference.strip_prefix("refs/heads/") {
260            local
261        } else if let Some(remote) = reference.strip_prefix("refs/remotes/") {
262            match remote.split_once('/') {
263                Some((_, "HEAD")) | None => continue,
264                Some((_, name)) => name,
265            }
266        } else {
267            continue;
268        };
269        let catalogued = name != TRUNK_BRANCH && LONG_LIVED_BRANCHES.contains(&name);
270        if catalogued || name.starts_with(RELEASE_LINE_PREFIX) {
271            names.insert(name.to_owned());
272        }
273    }
274    names.into_iter().collect()
275}
276
277/// Why one git call gave no answer.
278enum GitFailure {
279    /// Git ran and said the target is not a repository.
280    NotARepository,
281    /// Git did not run, or ran and refused for another reason.
282    Other(RkError),
283}
284
285impl GitFailure {
286    /// After the target is known to be a repository, every failure is
287    /// the same kind: a history that cannot be read.
288    fn into_error(self) -> RkError {
289        match self {
290            Self::NotARepository => RkError::subprocess(
291                Diagnostic::new(
292                    Reason::SubprocessFailed,
293                    "git stopped answering for a repository it had just recognized",
294                )
295                .expected("a readable repository"),
296            ),
297            Self::Other(error) => error,
298        }
299    }
300}
301
302/// The non-empty stdout lines of one git call.
303///
304/// The call answers for the `-C` target alone: the variables a running
305/// hook exports are scrubbed, so an inherited `GIT_DIR` cannot redirect
306/// the probe at another repository, and the locale is pinned to `C`, so
307/// the one diagnostic this module reads — git's own "not a git
308/// repository" — arrives untranslated.
309fn git_lines(target: &Utf8Path, args: &[&str]) -> Result<Vec<String>, GitFailure> {
310    let mut command = Command::new(crate::probes::git_bin());
311    for var in crate::maintenance::GIT_HOOK_VARS {
312        command.env_remove(var);
313    }
314    let out = command
315        .env("LC_ALL", "C")
316        .env_remove("LANGUAGE")
317        .arg("-C")
318        .arg(target)
319        .args(args)
320        .output()
321        .map_err(|error| {
322            GitFailure::Other(RkError::subprocess(
323                Diagnostic::new(
324                    Reason::SubprocessSpawn,
325                    format!("git could not be spawned: {error}"),
326                )
327                .expected("git on PATH, or RK_GIT_BIN naming it"),
328            ))
329        })?;
330    if !out.status.success() {
331        let stderr = String::from_utf8_lossy(&out.stderr);
332        if stderr.contains("not a git repository") {
333            return Err(GitFailure::NotARepository);
334        }
335        return Err(GitFailure::Other(RkError::subprocess(
336            Diagnostic::new(
337                Reason::SubprocessFailed,
338                format!(
339                    "git {} failed at {target}: {}",
340                    args.join(" "),
341                    stderr.trim()
342                ),
343            )
344            .expected("git answering for the target, or a target that is not a repository")
345            .action("an unreadable history is not an absent one; repair the repository or its ownership before classifying"),
346        )));
347    }
348    Ok(String::from_utf8_lossy(&out.stdout)
349        .lines()
350        .map(str::trim)
351        .filter(|line| !line.is_empty())
352        .map(str::to_owned)
353        .collect())
354}
355
356#[cfg(test)]
357mod tests {
358    use super::{Classification, Evidence, Landing, classify, long_lived_among};
359
360    fn evidence() -> Evidence {
361        Evidence {
362            landing: Landing {
363                recorded: false,
364                rk_version: None,
365            },
366            tech: Some("rust"),
367            forge: Some("github"),
368            repo: Some("acme/widget".into()),
369            release_markers: Vec::new(),
370            collisions: Vec::new(),
371            git: true,
372            tags: 0,
373            long_lived_branches: Vec::new(),
374        }
375    }
376
377    #[test]
378    fn nothing_is_greenfield() {
379        assert_eq!(classify(&evidence()), Classification::Greenfield);
380    }
381
382    #[test]
383    fn a_release_marker_or_a_collision_is_brownfield() {
384        let mut with_marker = evidence();
385        with_marker.release_markers.push("CHANGELOG.md".into());
386        assert_eq!(classify(&with_marker), Classification::Brownfield);
387        let mut with_collision = evidence();
388        with_collision.collisions.push("release-plz.toml".into());
389        assert_eq!(classify(&with_collision), Classification::Brownfield);
390    }
391
392    /// A mechanism outranks unexplained activity: tags beside a marker
393    /// are a history the mechanism made, not a question.
394    #[test]
395    fn a_mechanism_beside_activity_is_still_brownfield() {
396        let mut both = evidence();
397        both.release_markers.push("CHANGELOG.md".into());
398        both.tags = 7;
399        both.long_lived_branches.push("develop".into());
400        assert_eq!(classify(&both), Classification::Brownfield);
401    }
402
403    #[test]
404    fn activity_with_no_mechanism_needs_a_decision() {
405        let mut tagged = evidence();
406        tagged.tags = 1;
407        assert_eq!(classify(&tagged), Classification::NeedsDecision);
408        let mut branched = evidence();
409        branched.long_lived_branches.push("develop".into());
410        assert_eq!(classify(&branched), Classification::NeedsDecision);
411    }
412
413    /// The trunk is never evidence against itself; only the remote
414    /// segment is stripped, so a topic branch whose last segment is a
415    /// catalog name stays a topic branch; a release line is recognized
416    /// by its prefix; a remote HEAD pointer is skipped; each name once.
417    #[test]
418    fn long_lived_branches_are_read_from_the_full_ref_names() {
419        let refs: Vec<String> = [
420            "refs/heads/master",
421            "refs/remotes/origin/master",
422            "refs/remotes/origin/HEAD",
423            "refs/heads/develop",
424            "refs/remotes/origin/develop",
425            "refs/heads/feat/x",
426            "refs/heads/feat/develop",
427            "refs/remotes/origin/main",
428            "refs/heads/release/1.2",
429            "refs/remotes/upstream/release/1.2",
430        ]
431        .iter()
432        .map(|name| (*name).to_owned())
433        .collect();
434        assert_eq!(
435            long_lived_among(&refs),
436            vec!["develop", "main", "release/1.2"]
437        );
438        assert!(long_lived_among(&["refs/heads/master".to_owned()]).is_empty());
439        assert!(long_lived_among(&["refs/heads/feat/develop".to_owned()]).is_empty());
440    }
441
442    #[test]
443    fn the_verdict_words_are_the_wire_form() {
444        assert_eq!(Classification::Greenfield.as_str(), "greenfield");
445        assert_eq!(Classification::Brownfield.as_str(), "brownfield");
446        assert_eq!(Classification::NeedsDecision.as_str(), "needs-decision");
447    }
448}