1use std::path::Path;
6
7use serde::{Deserialize, Serialize};
8
9use crate::apply::ledger::LedgerEntry;
10use crate::apply::write_atomic;
11use crate::error::{CoreError, ErrorCode};
12use crate::fs::Fs;
13use crate::skills::link::SkillLink;
14
15pub const EJECT_FILE: &str = "eject.json";
17pub(crate) const EJECT_SCHEMA: u32 = 1;
18const KEEP_RUNS: usize = 20;
20
21#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
23pub struct EjectFile {
24 pub schema: u32,
25 #[serde(default)]
26 pub runs: Vec<EjectRun>,
27 #[serde(flatten)]
29 pub extra: serde_json::Map<String, serde_json::Value>,
30}
31
32impl Default for EjectFile {
33 fn default() -> Self {
34 Self {
35 schema: EJECT_SCHEMA,
36 runs: Vec::new(),
37 extra: serde_json::Map::new(),
38 }
39 }
40}
41
42#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
44pub struct EjectRun {
45 pub id: String,
47 pub time: String,
49 #[serde(default, skip_serializing_if = "Option::is_none")]
51 pub clients: Option<Vec<String>>,
52 #[serde(default, skip_serializing_if = "Option::is_none")]
54 pub project_id: Option<String>,
55 #[serde(default)]
58 pub finished: bool,
59 #[serde(default)]
61 pub resumed: bool,
62 #[serde(default)]
63 pub rolled_back: bool,
64 #[serde(default)]
66 pub files: Vec<EjectedFile>,
67 #[serde(default)]
69 pub ledger: Vec<LedgerEntry>,
70 #[serde(default)]
72 pub skill_links: Vec<SkillLink>,
73 #[serde(default)]
75 pub copied: Vec<CopiedSkill>,
76 #[serde(default)]
78 pub unmarked: Vec<String>,
79 #[serde(flatten)]
80 pub extra: serde_json::Map<String, serde_json::Value>,
81}
82
83impl EjectRun {
84 pub fn active(&self) -> bool {
86 !self.resumed && !self.rolled_back
87 }
88}
89
90#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
92pub struct EjectedFile {
93 pub file: String,
95 #[serde(default, skip_serializing_if = "Option::is_none")]
97 pub backup: Option<String>,
98 pub written: String,
100}
101
102#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
104pub struct CopiedSkill {
105 pub path: String,
106 pub hash: String,
108}
109
110impl EjectFile {
111 pub fn load(fs: &dyn Fs, state_dir: &Path) -> Result<Self, CoreError> {
115 let path = state_dir.join(EJECT_FILE);
116 if !fs.exists(&path) {
117 return Ok(Self::default());
118 }
119 let text = fs.read_to_string(&path).map_err(|err| {
120 CoreError::new(
121 ErrorCode::IoError,
122 format!("cannot read the eject record: {err}"),
123 )
124 .with_path(&path)
125 })?;
126 let file: Self = serde_json::from_str(&text).map_err(|err| {
127 CoreError::new(
128 ErrorCode::ParseError,
129 format!("the eject record does not parse: {err}"),
130 )
131 .with_path(&path)
132 })?;
133 if file.schema != EJECT_SCHEMA {
134 return Err(CoreError::new(
135 ErrorCode::UnsupportedSchema,
136 format!(
137 "eject record schema {} is not supported; this build reads schema {EJECT_SCHEMA}",
138 file.schema
139 ),
140 )
141 .with_path(&path));
142 }
143 Ok(file)
144 }
145
146 pub fn save(&mut self, fs: &dyn Fs, state_dir: &Path) -> Result<(), CoreError> {
149 while self.runs.len() > KEEP_RUNS {
150 match self.runs.iter().position(|run| !run.active()) {
151 Some(index) => {
152 self.runs.remove(index);
153 }
154 None => break,
155 }
156 }
157 let mut text = serde_json::to_string_pretty(self).map_err(|err| {
158 CoreError::new(
159 ErrorCode::InvalidValue,
160 format!("cannot serialize the eject record: {err}"),
161 )
162 })?;
163 text.push('\n');
164 fs.create_dir_all(state_dir).map_err(|err| {
165 CoreError::new(
166 ErrorCode::IoError,
167 format!("cannot create directory: {err}"),
168 )
169 .with_path(state_dir)
170 })?;
171 write_atomic(fs, &state_dir.join(EJECT_FILE), text.as_bytes())
172 }
173}
174
175#[derive(Debug, Clone, PartialEq, Eq)]
177pub struct Ejected {
178 pub runs: Vec<ActiveRun>,
179}
180
181#[derive(Debug, Clone, PartialEq, Eq)]
183pub struct ActiveRun {
184 pub id: String,
185 pub time: String,
186 pub clients: Option<Vec<String>>,
187 pub project_id: Option<String>,
188 pub finished: bool,
190}
191
192impl Ejected {
193 pub fn covers(&self, client: &str, project_id: Option<&str>) -> bool {
196 self.runs.iter().any(|run| {
197 run.clients
198 .as_ref()
199 .is_none_or(|clients| clients.iter().any(|id| id == client))
200 && run
201 .project_id
202 .as_deref()
203 .is_none_or(|id| Some(id) == project_id)
204 })
205 }
206
207 pub fn all(&self) -> bool {
209 self.runs
210 .iter()
211 .any(|run| run.clients.is_none() && run.project_id.is_none())
212 }
213
214 pub fn unfinished(&self) -> Option<&ActiveRun> {
217 self.runs.iter().find(|run| !run.finished)
218 }
219}
220
221pub fn status_at(fs: &dyn Fs, state_dir: &Path) -> Result<Option<Ejected>, CoreError> {
224 if !fs.exists(&state_dir.join(EJECT_FILE)) {
225 return Ok(None);
226 }
227 let runs: Vec<ActiveRun> = EjectFile::load(fs, state_dir)?
228 .runs
229 .into_iter()
230 .filter(EjectRun::active)
231 .map(|run| ActiveRun {
232 id: run.id,
233 time: run.time,
234 clients: run.clients,
235 project_id: run.project_id,
236 finished: run.finished,
237 })
238 .collect();
239 Ok((!runs.is_empty()).then_some(Ejected { runs }))
240}