wallr_core/packages/
mod.rs1use crate::animation::AnimationSpec;
2use std::collections::HashSet;
3use std::fs;
4use std::path::{Path, PathBuf};
5
6#[derive(Debug, thiserror::Error)]
7pub enum PackageError {
8 #[error("package not found: {0}")]
9 NotFound(String),
10 #[error("failed to read package: {0}")]
11 ReadError(#[from] std::io::Error),
12 #[error("failed to parse package: {0}")]
13 ParseError(#[from] serde_yaml::Error),
14 #[error("circular extends detected: {0}")]
15 CircularExtends(String),
16 #[error("invalid package reference: {0}")]
17 InvalidReference(String),
18 #[error("animation error: {0}")]
19 AnimationError(#[from] crate::animation::AnimationError),
20 #[error("Failed to download remote package: {0}")]
21 DownloadError(String),
22}
23
24pub struct Package {
25 pub name: String,
26 pub path: PathBuf,
27 pub spec: AnimationSpec,
28}
29
30pub struct PackageRegistry {
31 pub packages_dir: PathBuf,
32}
33
34impl PackageRegistry {
35 pub fn new() -> Result<Self, PackageError> {
36 let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".to_string());
37 let packages_dir = PathBuf::from(home).join(".local/share/wallr/packages");
38 if !packages_dir.exists() {
39 fs::create_dir_all(&packages_dir)?;
40 }
41 Ok(Self { packages_dir })
42 }
43
44 pub fn load_package(&self, name: &str) -> Result<Package, PackageError> {
45 let pkg_path = self.packages_dir.join(name);
46 if !pkg_path.exists() {
47 return Err(PackageError::NotFound(name.to_string()));
48 }
49
50 let yaml_path = ["wallr.yaml", "animation.yaml"]
51 .iter()
52 .map(|file| pkg_path.join(file))
53 .find(|path| path.is_file())
54 .ok_or_else(|| PackageError::NotFound(format!("{name} (missing wallr.yaml)")))?;
55 let content = fs::read_to_string(&yaml_path)?;
56 let spec = crate::animation::parse_animation_yaml(&content)?;
57
58 Ok(Package {
59 name: name.to_string(),
60 path: pkg_path,
61 spec,
62 })
63 }
64
65 pub fn resolve_animation(&self, reference: &str) -> Result<AnimationSpec, PackageError> {
66 let parts: Vec<&str> = reference.split('/').collect();
67 if parts.len() != 2 {
68 return Err(PackageError::InvalidReference(reference.to_string()));
69 }
70
71 let pkg_name = parts[0];
72 let package = self.load_package(pkg_name)?;
73
74 Ok(package.spec)
75 }
76
77 pub fn list_packages(&self) -> Result<Vec<String>, PackageError> {
78 let mut packages = Vec::new();
79 if !self.packages_dir.exists() {
80 return Ok(packages);
81 }
82
83 for entry in fs::read_dir(&self.packages_dir)? {
84 let entry = entry?;
85 if entry.metadata()?.is_dir()
86 && let Some(name) = entry.file_name().to_str()
87 {
88 packages.push(name.to_string());
89 }
90 }
91 Ok(packages)
92 }
93}
94
95pub fn resolve_extends(
96 mut base: AnimationSpec,
97 extends: &[String],
98 registry: &PackageRegistry,
99) -> Result<AnimationSpec, PackageError> {
100 detect_cycles(extends, registry)?;
101
102 for parent_ref in extends {
103 let parent_spec = if parent_ref.starts_with("github:") {
104 fetch_remote_package(parent_ref)?
105 } else {
106 registry.resolve_animation(parent_ref)?
107 };
108
109 if base.duration.is_none() {
110 base.duration = parent_spec.duration;
111 }
112 if base.timeline.is_none() {
113 base.timeline = parent_spec.timeline;
114 }
115 for (key, value) in parent_spec.variables {
116 base.variables.entry(key).or_insert(value);
117 }
118 for (key, value) in parent_spec.custom_effects {
119 base.custom_effects.entry(key).or_insert(value);
120 }
121 for effect in parent_spec.effects {
122 if !base.effects.contains(&effect) {
123 base.effects.push(effect);
124 }
125 }
126 }
127 crate::animation::validate_animation(&base).map_err(|errors| {
128 PackageError::DownloadError(
129 errors
130 .into_iter()
131 .map(|e| e.to_string())
132 .collect::<Vec<_>>()
133 .join("; "),
134 )
135 })?;
136 Ok(base)
137}
138
139pub fn fetch_remote_package(reference: &str) -> Result<AnimationSpec, PackageError> {
140 let stripped = reference.strip_prefix("github:").unwrap_or(reference);
141 let subparts: Vec<&str> = stripped.split('/').collect();
142 if subparts.len() != 2
143 || subparts
144 .iter()
145 .any(|part| part.is_empty() || part.contains('@'))
146 {
147 return Err(PackageError::InvalidReference(reference.to_string()));
148 }
149
150 let owner = subparts[0];
151 let repo = subparts[1];
152 let tag = "main";
153
154 let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".to_string());
155 let cache_dir = PathBuf::from(home).join(".cache/wallr/packages");
156 if !cache_dir.exists() {
157 let _ = fs::create_dir_all(&cache_dir);
158 }
159
160 let cache_file = cache_dir.join(format!("{}_{}.yaml", owner, repo));
161
162 if cache_file.exists() {
163 let cached_content = fs::read_to_string(&cache_file)?;
164 let spec = crate::animation::parse_animation_yaml(&cached_content)?;
165 return Ok(spec);
166 }
167
168 let candidates = vec!["wallr.yaml".to_string(), format!("{repo}.yaml")];
169 let mut output = None;
170 for file_path in candidates {
171 let url = format!("https://raw.githubusercontent.com/{owner}/{repo}/{tag}/{file_path}");
172 let candidate = std::process::Command::new("curl")
173 .arg("-fsSL")
174 .arg(&url)
175 .output();
176 if let Ok(out) = candidate
177 && out.status.success()
178 && !out.stdout.is_empty()
179 {
180 output = Some(out);
181 break;
182 }
183 }
184
185 match output {
186 Some(out) => {
187 let content = String::from_utf8_lossy(&out.stdout).to_string();
188 let spec = crate::animation::parse_animation_yaml(&content)?;
189 crate::animation::validate_animation(&spec).map_err(|errors| {
190 PackageError::DownloadError(
191 errors
192 .into_iter()
193 .map(|e| e.to_string())
194 .collect::<Vec<_>>()
195 .join("; "),
196 )
197 })?;
198 let _ = fs::write(&cache_file, &content);
199 Ok(spec)
200 }
201 None => Err(PackageError::DownloadError(format!(
202 "unable to fetch {owner}/{repo} from GitHub"
203 ))),
204 }
205}
206
207pub fn detect_cycles(extends: &[String], _registry: &PackageRegistry) -> Result<(), PackageError> {
208 let mut visited = HashSet::new();
209 let mut active = HashSet::new();
210 if extends.len() != extends.iter().collect::<HashSet<_>>().len() {
211 let duplicate = extends
212 .iter()
213 .find(|reference| {
214 extends
215 .iter()
216 .filter(|candidate| *candidate == *reference)
217 .count()
218 > 1
219 })
220 .cloned()
221 .unwrap_or_default();
222 return Err(PackageError::CircularExtends(duplicate));
223 }
224 fn visit(
225 reference: &str,
226 registry: &PackageRegistry,
227 visited: &mut HashSet<String>,
228 active: &mut HashSet<String>,
229 ) -> Result<(), PackageError> {
230 if active.contains(reference) {
231 return Err(PackageError::CircularExtends(reference.to_string()));
232 }
233 if !visited.insert(reference.to_string()) {
234 return Ok(());
235 }
236 active.insert(reference.to_string());
237 if !reference.starts_with("github:") {
238 let package_name = reference.split('/').next().unwrap_or(reference);
239 if let Ok(package) = registry.load_package(package_name) {
240 for parent in &package.spec.extends {
241 visit(parent, registry, visited, active)?;
242 }
243 }
244 }
245 active.remove(reference);
246 Ok(())
247 }
248 for ext in extends {
249 visit(ext, _registry, &mut visited, &mut active)?;
250 }
251 Ok(())
252}
253
254pub fn load_local_animation(path: &Path) -> Result<AnimationSpec, PackageError> {
255 let content = fs::read_to_string(path)?;
256 let spec = crate::animation::parse_animation_yaml(&content)?;
257 Ok(spec)
258}
259
260#[cfg(test)]
261mod tests {
262 use super::*;
263
264 #[test]
265 fn test_detect_no_cycles() {
266 let registry = PackageRegistry {
267 packages_dir: PathBuf::from("/tmp"),
268 };
269 assert!(detect_cycles(&["base".to_string(), "common".to_string()], ®istry).is_ok());
270 }
271
272 #[test]
273 fn test_detect_cycles() {
274 let registry = PackageRegistry {
275 packages_dir: PathBuf::from("/tmp"),
276 };
277 assert!(detect_cycles(&["base".to_string(), "base".to_string()], ®istry).is_err());
278 }
279
280 #[test]
281 fn test_list_packages_empty() {
282 let registry = PackageRegistry {
283 packages_dir: PathBuf::from("/does/not/exist"),
284 };
285 let pkgs = registry.list_packages().unwrap();
286 assert!(pkgs.is_empty());
287 }
288}