use camino::{Utf8Path, Utf8PathBuf};
use serde::Serialize;
use crate::self_depend::manager::Detected;
use crate::self_depend::{CHECK_LINE, ENVRC, OLD_SYNC_LINE};
pub const CATALOG: &[&str] = &[];
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Leftover {
pub file: Utf8PathBuf,
pub reason: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Kept {
pub file: Utf8PathBuf,
pub line: Option<String>,
pub reason: String,
}
#[must_use]
pub fn find(target: &Utf8Path, also: &[Utf8PathBuf]) -> Vec<Leftover> {
let mut found = Vec::new();
for file in CATALOG {
if target.join(file).is_file() {
found.push(Leftover {
file: Utf8PathBuf::from(*file),
reason: "left by a predecessor bump mechanism".to_string(),
});
}
}
for file in also {
if target.join(file).is_file() && !found.iter().any(|held| &held.file == file) {
found.push(Leftover {
file: file.clone(),
reason: "named by the operator as a predecessor's file".to_string(),
});
}
}
found
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum Action {
Swap,
Remove,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Swap {
pub file: Utf8PathBuf,
pub action: Action,
pub from: String,
pub to: Option<String>,
}
#[must_use]
pub fn is_line(line: &str, wanted: &str) -> bool {
line.trim() == wanted
}
#[must_use]
pub fn carries(text: &str, wanted: &str) -> bool {
text.lines().any(|line| is_line(line, wanted))
}
#[must_use]
pub fn carries_old_line(text: &str) -> bool {
carries(text, OLD_SYNC_LINE)
}
#[must_use]
pub fn carries_check_line(text: &str) -> bool {
carries(text, CHECK_LINE)
}
#[must_use]
pub fn envrc_swaps(target: &Utf8Path) -> Vec<Swap> {
std::fs::read_to_string(target.join(ENVRC))
.ok()
.and_then(|text| swapped(&text))
.map(|(_, swaps)| swaps)
.unwrap_or_default()
}
#[must_use]
pub fn swapped(text: &str) -> Option<(String, Vec<Swap>)> {
if !carries_old_line(text) {
return None;
}
let mut has_check = carries_check_line(text);
let mut swaps = Vec::new();
let mut out = String::with_capacity(text.len());
for line in text.split_inclusive('\n') {
let body = line.trim_end_matches(['\n', '\r']);
if !is_line(body, OLD_SYNC_LINE) {
out.push_str(line);
continue;
}
if has_check {
swaps.push(Swap {
file: Utf8PathBuf::from(ENVRC),
action: Action::Remove,
from: OLD_SYNC_LINE.to_string(),
to: None,
});
continue;
}
let indent = &body[..body.len() - body.trim_start().len()];
out.push_str(indent);
out.push_str(CHECK_LINE);
out.push_str(&line[body.len()..]);
has_check = true;
swaps.push(Swap {
file: Utf8PathBuf::from(ENVRC),
action: Action::Swap,
from: OLD_SYNC_LINE.to_string(),
to: Some(CHECK_LINE.to_string()),
});
}
Some((out, swaps))
}
#[must_use]
pub fn kept(target: &Utf8Path, wired: &[&Detected]) -> Vec<Kept> {
let mut held = Vec::new();
for detected in wired {
if let Some(file) = detected.file.as_ref() {
held.push(Kept {
file: file.clone(),
line: detected
.pin
.as_ref()
.map(|pin| format!("line {}", pin.line)),
reason: "the manager file the project owns; the pin moves in place".to_string(),
});
}
if let Some(lock) = detected.manager.lock_file()
&& target.join(lock).is_file()
{
held.push(Kept {
file: Utf8PathBuf::from(lock),
line: None,
reason: "the lock the manager owns; it moves with the pin".to_string(),
});
}
}
if std::fs::read_to_string(target.join(ENVRC)).is_ok_and(|text| carries_check_line(&text)) {
held.push(Kept {
file: Utf8PathBuf::from(ENVRC),
line: Some(CHECK_LINE.to_string()),
reason: "the version check; a scan for a predecessor must not match it".to_string(),
});
}
held
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, reason = "a test panics as its failure signal")]
use super::*;
#[test]
fn a_named_file_is_a_leftover_only_where_it_exists() {
let dir = tempfile::tempdir().unwrap();
let root = Utf8Path::from_path(dir.path()).unwrap();
std::fs::write(root.join("bump.sh"), "#!/bin/sh\n").unwrap();
let found = find(
root,
&[Utf8PathBuf::from("bump.sh"), Utf8PathBuf::from("absent.sh")],
);
assert_eq!(found.len(), 1);
assert_eq!(found[0].file, "bump.sh");
}
#[test]
fn the_check_line_is_named_as_kept() {
let dir = tempfile::tempdir().unwrap();
let root = Utf8Path::from_path(dir.path()).unwrap();
std::fs::write(root.join(ENVRC), format!("use flake\n{CHECK_LINE}\n")).unwrap();
let held = kept(root, &[]);
assert_eq!(held.len(), 1);
assert_eq!(held[0].line.as_deref(), Some(CHECK_LINE));
}
#[test]
fn the_swap_keeps_indentation_endings_and_every_other_line() {
let text = format!("use flake\r\n {OLD_SYNC_LINE}\r\nexport A=1");
let (next, swaps) = swapped(&text).unwrap();
assert_eq!(next, format!("use flake\r\n {CHECK_LINE}\r\nexport A=1"));
assert_eq!(swaps.len(), 1);
assert_eq!(swaps[0].action, Action::Swap);
let both = format!(" {CHECK_LINE}\r\n{OLD_SYNC_LINE}\n");
let (next, swaps) = swapped(&both).unwrap();
assert_eq!(next, format!(" {CHECK_LINE}\r\n"));
assert_eq!(swaps[0].action, Action::Remove);
assert_eq!(swaps[0].to, None);
assert!(swapped(&format!("{CHECK_LINE}\n")).is_none());
assert!(swapped(&format!("# {OLD_SYNC_LINE}\n")).is_none());
}
}