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};
22use crate::setup::context::TRUNK_BRANCH;
23
24const RELEASE_LINE_PREFIX: &str = "release/";
26
27pub 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)]
83#[serde(rename_all = "kebab-case")]
84pub enum Classification {
85 Greenfield,
87 Brownfield,
89 NeedsDecision,
91}
92
93impl Classification {
94 #[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#[derive(Debug, Serialize)]
108pub struct Landing {
109 pub recorded: bool,
111 #[serde(skip_serializing_if = "Option::is_none")]
113 pub rk_version: Option<String>,
114}
115
116#[derive(Debug, Serialize)]
118pub struct Evidence {
119 pub landing: Landing,
121 #[serde(skip_serializing_if = "Option::is_none")]
123 pub tech: Option<&'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 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
156pub 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
203fn 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 Ok(serde_json::from_slice::<serde_json::Value>(&bytes)
216 .ok()
217 .and_then(|value| value.get("release").map(|_| ()))
218 .is_some())
219}
220
221fn 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#[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
277enum GitFailure {
279 NotARepository,
281 Other(RkError),
283}
284
285impl GitFailure {
286 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
302fn 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 #[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 #[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}