forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBbcb4dc5Tahinli21 days ago1034 commits

versions.rs174 lines, 7.0 KiBHistoryRawDownload
1//! Versions of a project: named full copies kept beside it, in
2//! `<project dir>/checkpoints/<project stem>/<name>.edith`. The MCP server's
3//! `checkpoint` / `restore` / `checkpoints` and the window's File > Save version and
4//! Versions share these functions, so a version made by one shows in the other.
5//!
6//! A version is a whole project file, so it is not limited by the undo history, it
7//! survives a restart, and each one costs a save of the project.
8
9use std::path::{Path, PathBuf};
10use std::time::SystemTime;
11
12use crate::project::LaneKind;
13use crate::PlaybackSession;
14
15/// One version on disk.
16#[derive(Clone, Debug, PartialEq, Eq)]
17pub struct Version {
18 pub name: String,
19 pub saved: SystemTime,
20 /// Clips placed in the version, captions included; 0 when the file would not read.
21 pub clips: usize,
22}
23
24/// What a save of a version did.
25#[derive(Clone, Copy, Debug)]
26pub struct Saved {
27 /// When the version of the same name this replaced was written, if there was one.
28 pub replaced: Option<SystemTime>,
29 pub clips: usize,
30}
31
32/// Where the versions of `project` are kept: beside it, so they outlive the process.
33pub fn dir_beside(project: &Path) -> PathBuf {
34 let stem = project.file_stem().map_or_else(|| "untitled".to_string(), |f| f.to_string_lossy().into_owned());
35 let parent = project.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new("."));
36 parent.join("checkpoints").join(stem)
37}
38
39/// A version name: 1 to 40 letters, digits, `-` or `_`, so it is a safe file name.
40pub fn valid_name(name: &str) -> bool {
41 !name.is_empty()
42 && name.len() <= 40
43 && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
44}
45
46/// What `typed` becomes as a name: trimmed, anything but letters, digits and `_` turned into `-`
47/// (so `Before intro` is `Before-intro`), cut to 40.
48/// `None` when nothing is left.
49pub fn clean_name(typed: &str) -> Option<String> {
50 let name: String = typed
51 .trim()
52 .chars()
53 .map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '-' })
54 .take(40)
55 .collect();
56 let name = name.trim().to_string();
57 (!name.is_empty()).then_some(name)
58}
59
60pub fn file(dir: &Path, name: &str) -> PathBuf {
61 dir.join(format!("{name}.edith"))
62}
63
64/// The clips placed in the session, captions included.
65pub fn clip_count(s: &PlaybackSession) -> usize {
66 s.lanes()
67 .into_iter()
68 .map(|l| if l.kind == LaneKind::Subtitle { s.sub_lane(l).len() } else { s.lane_clips(l).len() })
69 .sum()
70}
71
72/// Saves the open project as version `name` in `dir` (made when missing); a version of the
73/// same name is replaced. The project file itself is not touched.
74pub fn save(s: &PlaybackSession, dir: &Path, name: &str) -> crate::Result<Saved> {
75 if !valid_name(name) {
76 return Err(format!("version name `{name}` is not usable: 1 to 40 letters, digits, - or _").into());
77 }
78 std::fs::create_dir_all(dir).map_err(|e| format!("cannot make {}: {e}", dir.display()))?;
79 let path = file(dir, name);
80 let replaced = std::fs::metadata(&path).and_then(|m| m.modified()).ok();
81 s.save_project(&path)?;
82 Ok(Saved { replaced, clips: clip_count(s) })
83}
84
85/// Saves the open state as `before-restore-<name>` (a numeric suffix when taken, cut to the 40
86/// characters a name may hold), so a restore never discards unsaved edits. Returns the name.
87pub fn save_before_restore(s: &PlaybackSession, dir: &Path, name: &str) -> crate::Result<String> {
88 let base = format!("before-restore-{name}");
89 let cut = |n: usize| base[..base.len().min(n)].trim_end().to_string();
90 let mut auto = cut(40);
91 let mut n = 2;
92 while file(dir, &auto).exists() {
93 let suffix = format!("-{n}");
94 auto = format!("{}{suffix}", cut(40 - suffix.len()));
95 n += 1;
96 }
97 std::fs::create_dir_all(dir).map_err(|e| format!("cannot make {}: {e}", dir.display()))?;
98 s.save_project(&file(dir, &auto))?;
99 Ok(auto)
100}
101
102/// The versions in `dir`, newest first. A missing folder is no versions.
103pub fn list(dir: &Path) -> Vec<Version> {
104 let Ok(rd) = std::fs::read_dir(dir) else {
105 return Vec::new();
106 };
107 let mut found: Vec<Version> = rd
108 .filter_map(|e| e.ok().map(|e| e.path()))
109 .filter(|p| p.extension().is_some_and(|x| x == "edith"))
110 .filter_map(|p| {
111 let name = p.file_stem()?.to_string_lossy().into_owned();
112 let saved = std::fs::metadata(&p).and_then(|m| m.modified()).unwrap_or(SystemTime::UNIX_EPOCH);
113 let clips = crate::edith::load(&p)
114 .map(|d| d.lanes.iter().map(|(_, c)| c.len()).sum::<usize>() + d.subs.iter().map(Vec::len).sum::<usize>())
115 .unwrap_or(0);
116 Some(Version { name, saved, clips })
117 })
118 .collect();
119 found.sort_by(|a, b| b.saved.cmp(&a.saved).then_with(|| a.name.cmp(&b.name)));
120 found
121}
122
123/// How long ago `t` was, as a short phrase: `40 s ago`, `3 min ago`.
124pub fn age_text(t: SystemTime) -> String {
125 let secs = SystemTime::now().duration_since(t).map_or(0, |d| d.as_secs());
126 match secs {
127 0..=59 => format!("{secs} s ago"),
128 60..=3599 => format!("{} min ago", secs / 60),
129 3600..=86_399 => format!("{} h ago", secs / 3600),
130 _ => format!("{} d ago", secs / 86_400),
131 }
132}
133
134#[cfg(test)]
135mod tests {
136 use super::*;
137
138 #[test]
139 fn names_are_file_safe() {
140 assert!(valid_name("before-intro-2_x"));
141 for bad in ["", " a", "a b", "a/b", "a.b", &"x".repeat(41)] {
142 assert!(!valid_name(bad), "{bad:?}");
143 }
144 assert_eq!(clean_name(" my v1/final? ").as_deref(), Some("my-v1-final-"));
145 assert_eq!(clean_name(" "), None);
146 assert_eq!(clean_name(&"y".repeat(60)).unwrap().len(), 40);
147 }
148
149 #[test]
150 fn the_folder_sits_beside_the_project() {
151 assert_eq!(dir_beside(Path::new("/a/b/film.edith")), Path::new("/a/b/checkpoints/film"));
152 assert_eq!(dir_beside(Path::new("film.edith")), Path::new("./checkpoints/film"));
153 }
154
155 #[test]
156 fn save_list_and_before_restore_round_trip() {
157 let dir = crate::scratch::Scratch::dir("ve_versions");
158 let media = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_av.mp4");
159 let s = PlaybackSession::open(media).expect("open test asset");
160 let vdir = dir.join("checkpoints");
161 let saved = save(&s, &vdir, "first-take").expect("saves");
162 assert!(saved.replaced.is_none());
163 let again = save(&s, &vdir, "first-take").expect("saves again");
164 assert!(again.replaced.is_some());
165 assert!(save(&s, &vdir, "no/slash").is_err());
166 let auto = save_before_restore(&s, &vdir, "first-take").expect("auto");
167 assert_eq!(auto, "before-restore-first-take");
168 assert_eq!(save_before_restore(&s, &vdir, "first-take").unwrap(), "before-restore-first-take-2");
169 let all = list(&vdir);
170 assert_eq!(all.len(), 3);
171 assert!(all.iter().any(|v| v.name == "first-take" && v.clips == saved.clips));
172 assert!(list(&dir.join("nothing")).is_empty());
173 }
174}