use std::path::Path;
use serde::{Deserialize, Serialize};
use crate::apply::ledger::LedgerEntry;
use crate::apply::write_atomic;
use crate::error::{CoreError, ErrorCode};
use crate::fs::Fs;
use crate::skills::link::SkillLink;
pub const EJECT_FILE: &str = "eject.json";
pub(crate) const EJECT_SCHEMA: u32 = 1;
const KEEP_RUNS: usize = 20;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EjectFile {
pub schema: u32,
#[serde(default)]
pub runs: Vec<EjectRun>,
#[serde(flatten)]
pub extra: serde_json::Map<String, serde_json::Value>,
}
impl Default for EjectFile {
fn default() -> Self {
Self {
schema: EJECT_SCHEMA,
runs: Vec::new(),
extra: serde_json::Map::new(),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EjectRun {
pub id: String,
pub time: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub clients: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub project_id: Option<String>,
#[serde(default)]
pub finished: bool,
#[serde(default)]
pub resumed: bool,
#[serde(default)]
pub rolled_back: bool,
#[serde(default)]
pub files: Vec<EjectedFile>,
#[serde(default)]
pub ledger: Vec<LedgerEntry>,
#[serde(default)]
pub skill_links: Vec<SkillLink>,
#[serde(default)]
pub copied: Vec<CopiedSkill>,
#[serde(default)]
pub unmarked: Vec<String>,
#[serde(flatten)]
pub extra: serde_json::Map<String, serde_json::Value>,
}
impl EjectRun {
pub fn active(&self) -> bool {
!self.resumed && !self.rolled_back
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EjectedFile {
pub file: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub backup: Option<String>,
pub written: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CopiedSkill {
pub path: String,
pub hash: String,
}
impl EjectFile {
pub fn load(fs: &dyn Fs, state_dir: &Path) -> Result<Self, CoreError> {
let path = state_dir.join(EJECT_FILE);
if !fs.exists(&path) {
return Ok(Self::default());
}
let text = fs.read_to_string(&path).map_err(|err| {
CoreError::new(
ErrorCode::IoError,
format!("cannot read the eject record: {err}"),
)
.with_path(&path)
})?;
let file: Self = serde_json::from_str(&text).map_err(|err| {
CoreError::new(
ErrorCode::ParseError,
format!("the eject record does not parse: {err}"),
)
.with_path(&path)
})?;
if file.schema != EJECT_SCHEMA {
return Err(CoreError::new(
ErrorCode::UnsupportedSchema,
format!(
"eject record schema {} is not supported; this build reads schema {EJECT_SCHEMA}",
file.schema
),
)
.with_path(&path));
}
Ok(file)
}
pub fn save(&mut self, fs: &dyn Fs, state_dir: &Path) -> Result<(), CoreError> {
while self.runs.len() > KEEP_RUNS {
match self.runs.iter().position(|run| !run.active()) {
Some(index) => {
self.runs.remove(index);
}
None => break,
}
}
let mut text = serde_json::to_string_pretty(self).map_err(|err| {
CoreError::new(
ErrorCode::InvalidValue,
format!("cannot serialize the eject record: {err}"),
)
})?;
text.push('\n');
fs.create_dir_all(state_dir).map_err(|err| {
CoreError::new(
ErrorCode::IoError,
format!("cannot create directory: {err}"),
)
.with_path(state_dir)
})?;
write_atomic(fs, &state_dir.join(EJECT_FILE), text.as_bytes())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Ejected {
pub runs: Vec<ActiveRun>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ActiveRun {
pub id: String,
pub time: String,
pub clients: Option<Vec<String>>,
pub project_id: Option<String>,
pub finished: bool,
}
impl Ejected {
pub fn covers(&self, client: &str, project_id: Option<&str>) -> bool {
self.runs.iter().any(|run| {
run.clients
.as_ref()
.is_none_or(|clients| clients.iter().any(|id| id == client))
&& run
.project_id
.as_deref()
.is_none_or(|id| Some(id) == project_id)
})
}
pub fn all(&self) -> bool {
self.runs
.iter()
.any(|run| run.clients.is_none() && run.project_id.is_none())
}
pub fn unfinished(&self) -> Option<&ActiveRun> {
self.runs.iter().find(|run| !run.finished)
}
}
pub fn status_at(fs: &dyn Fs, state_dir: &Path) -> Result<Option<Ejected>, CoreError> {
if !fs.exists(&state_dir.join(EJECT_FILE)) {
return Ok(None);
}
let runs: Vec<ActiveRun> = EjectFile::load(fs, state_dir)?
.runs
.into_iter()
.filter(EjectRun::active)
.map(|run| ActiveRun {
id: run.id,
time: run.time,
clients: run.clients,
project_id: run.project_id,
finished: run.finished,
})
.collect();
Ok((!runs.is_empty()).then_some(Ejected { runs }))
}