1use 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
23pub 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
61pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
84#[serde(rename_all = "kebab-case")]
85pub enum Classification {
86 Greenfield,
88 Brownfield,
90 NeedsDecision,
92}
93
94impl Classification {
95 #[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#[derive(Debug, Serialize)]
109pub struct Landing {
110 pub recorded: bool,
112 #[serde(skip_serializing_if = "Option::is_none")]
114 pub rk_version: Option<String>,
115}
116
117#[derive(Debug, Serialize)]
119pub struct Evidence {
120 pub landing: Landing,
122 pub technologies: Vec<&'static str>,
124 #[serde(skip_serializing_if = "Option::is_none")]
126 pub forge: Option<&'static str>,
127 #[serde(skip_serializing_if = "Option::is_none")]
129 pub repo: Option<String>,
130 pub release_markers: Vec<String>,
132 pub collisions: Vec<String>,
135 pub git: bool,
137 pub tags: usize,
139 pub long_lived_branches: Vec<String>,
141}
142
143#[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#[derive(Debug)]
159pub struct Facts {
160 pub technologies: Vec<&'static str>,
162 pub forge: Option<&'static str>,
164 pub repo: Option<String>,
166 pub release_markers: Vec<String>,
168 pub collisions: Vec<String>,
170 pub git: bool,
172 pub tags: usize,
174 pub long_lived_branches: Vec<String>,
176}
177
178pub 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
208pub 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
246fn 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 Ok(serde_json::from_slice::<serde_json::Value>(&bytes)
259 .ok()
260 .and_then(|value| value.get("release").map(|_| ()))
261 .is_some())
262}
263
264fn 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#[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
327enum GitFailure {
329 NotARepository,
331 Other(RkError),
333}
334
335impl GitFailure {
336 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
352fn 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 #[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 #[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}