1use std::path::{Path, PathBuf};
12
13use gitpoulpi_config::Integration;
14use serde::{Deserialize, Serialize};
15
16use crate::HostedProject;
17
18pub const VERSION: u32 = 1;
20pub const MAX_PROJECTS: usize = 5000;
22pub const MAX_DESCRIPTION: usize = 200;
24pub const MAX_FILES: usize = 32;
26
27#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
29pub struct ListKey {
30 pub integration_id: String,
31 pub host: String,
32 pub login: String,
34}
35
36impl ListKey {
37 pub fn of(integration: &Integration, login: Option<&str>) -> Option<Self> {
40 Some(Self {
41 integration_id: integration.id.clone(),
42 host: integration.host()?,
43 login: login.unwrap_or("").to_string(),
44 })
45 }
46
47 fn file_name(&self) -> String {
48 let clean = |s: &str| -> String {
49 s.chars()
50 .map(|c| {
51 if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {
52 c
53 } else {
54 '_'
55 }
56 })
57 .collect()
58 };
59 format!(
60 "{}@{}@{}.json",
61 clean(&self.integration_id),
62 clean(&self.host),
63 clean(&self.login)
64 )
65 }
66}
67
68#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
70pub struct CachedList {
71 pub version: u32,
72 pub key: ListKey,
73 pub fetched_at: u64,
75 pub projects: Vec<HostedProject>,
76}
77
78impl CachedList {
79 pub fn new(key: ListKey, fetched_at: u64, projects: Vec<HostedProject>) -> Self {
80 Self {
81 version: VERSION,
82 key,
83 fetched_at,
84 projects,
85 }
86 }
87}
88
89fn path_of(dir: &Path, key: &ListKey) -> PathBuf {
90 dir.join(key.file_name())
91}
92
93pub fn load(dir: &Path, key: &ListKey) -> Option<CachedList> {
95 let raw = std::fs::read_to_string(path_of(dir, key)).ok()?;
96 let list: CachedList = serde_json::from_str(&raw).ok()?;
97 (list.version == VERSION && list.key == *key).then_some(list)
98}
99
100fn strip_userinfo(url: &str) -> String {
102 let Some(rest) = url
103 .strip_prefix("https://")
104 .or_else(|| url.strip_prefix("http://"))
105 else {
106 return url.to_string();
107 };
108 let scheme_len = url.len() - rest.len();
109 let end = rest.find('/').unwrap_or(rest.len());
110 match rest[..end].rfind('@') {
111 Some(at) => format!("{}{}", &url[..scheme_len], &rest[at + 1..]),
112 None => url.to_string(),
113 }
114}
115
116pub fn store(dir: &Path, list: &CachedList) -> std::io::Result<()> {
118 gitpoulpi_config::secure_fs::create_private_dir_all(dir)?;
119 let mut list = list.clone();
120 list.projects.truncate(MAX_PROJECTS);
121 for p in &mut list.projects {
122 if let Some(d) = &mut p.description {
123 if d.chars().count() > MAX_DESCRIPTION {
124 *d = d.chars().take(MAX_DESCRIPTION).collect();
125 }
126 }
127 p.https_url = p.https_url.as_deref().map(strip_userinfo);
128 }
129 let path = path_of(dir, &list.key);
130 let text = serde_json::to_string(&list).map_err(std::io::Error::other)?;
131 gitpoulpi_config::secure_fs::write_private(&path, text.as_bytes())
132}
133
134pub fn remove(dir: &Path, key: &ListKey) {
136 let _ = std::fs::remove_file(path_of(dir, key));
137}
138
139pub fn remove_integration(dir: &Path, id: &str) -> usize {
143 let Ok(entries) = std::fs::read_dir(dir) else {
144 return 0;
145 };
146 let mut removed = 0;
147 for entry in entries.flatten() {
148 let path = entry.path();
149 if path.extension().and_then(|e| e.to_str()) != Some("json") {
150 continue;
151 }
152 let owned = std::fs::read_to_string(&path)
153 .ok()
154 .and_then(|raw| serde_json::from_str::<CachedList>(&raw).ok())
155 .is_some_and(|l| l.key.integration_id == id);
156 if owned && std::fs::remove_file(&path).is_ok() {
157 removed += 1;
158 }
159 }
160 removed
161}
162
163pub fn prune(dir: &Path, live: &[ListKey]) {
167 let Ok(entries) = std::fs::read_dir(dir) else {
168 return;
169 };
170 let mut kept: Vec<(u64, PathBuf)> = Vec::new();
171 for entry in entries.flatten() {
172 let path = entry.path();
173 if path.extension().and_then(|e| e.to_str()) != Some("json") {
174 continue;
175 }
176 let parsed = std::fs::read_to_string(&path)
177 .ok()
178 .and_then(|raw| serde_json::from_str::<CachedList>(&raw).ok())
179 .filter(|l| l.version == VERSION && live.contains(&l.key));
180 match parsed {
181 Some(l) => kept.push((l.fetched_at, path)),
182 None => {
183 let _ = std::fs::remove_file(&path);
184 }
185 }
186 }
187 kept.sort_by_key(|(at, _)| std::cmp::Reverse(*at));
188 for (_, path) in kept.into_iter().skip(MAX_FILES) {
189 let _ = std::fs::remove_file(path);
190 }
191}
192
193#[cfg(test)]
194mod tests {
195 use super::*;
196
197 fn key(id: &str, login: &str) -> ListKey {
198 ListKey {
199 integration_id: id.into(),
200 host: "github.com".into(),
201 login: login.into(),
202 }
203 }
204
205 fn project(full: &str) -> HostedProject {
206 HostedProject {
207 integration_id: "gh".into(),
208 id: full.into(),
209 name: full.rsplit('/').next().unwrap().into(),
210 full_name: full.into(),
211 description: None,
212 default_branch: None,
213 ssh_url: None,
214 https_url: None,
215 web_url: None,
216 private: false,
217 }
218 }
219
220 #[test]
221 fn round_trip() {
222 let dir = tempfile::tempdir().unwrap();
223 let list = CachedList::new(
224 key("gh", "ann"),
225 5,
226 vec![project("ann/a"), project("org/b")],
227 );
228 store(dir.path(), &list).unwrap();
229 assert_eq!(load(dir.path(), &key("gh", "ann")), Some(list));
230 assert_eq!(load(dir.path(), &key("gh", "bob")), None);
231 }
232
233 #[test]
234 fn corrupt_wrong_version_and_collision_read_as_none() {
235 let dir = tempfile::tempdir().unwrap();
236 let k = key("gh", "ann");
237 std::fs::write(path_of(dir.path(), &k), "{ not json").unwrap();
238 assert_eq!(load(dir.path(), &k), None);
239
240 let mut list = CachedList::new(k.clone(), 1, vec![]);
241 list.version = 99;
242 std::fs::write(
243 path_of(dir.path(), &k),
244 serde_json::to_string(&list).unwrap(),
245 )
246 .unwrap();
247 assert_eq!(load(dir.path(), &k), None);
248
249 let (k1, k2) = (key("a b", "x"), key("a_b", "x"));
251 store(dir.path(), &CachedList::new(k1.clone(), 1, vec![])).unwrap();
252 assert_eq!(path_of(dir.path(), &k1), path_of(dir.path(), &k2));
253 assert_eq!(load(dir.path(), &k2), None);
254 assert!(load(dir.path(), &k1).is_some());
255 }
256
257 #[test]
258 fn store_caps_and_strips_user_info() {
259 let dir = tempfile::tempdir().unwrap();
260 let mut many: Vec<HostedProject> = (0..MAX_PROJECTS + 3)
261 .map(|i| project(&format!("o/r{i}")))
262 .collect();
263 many[0].description = Some("x".repeat(MAX_DESCRIPTION + 50));
264 many[0].https_url = Some("https://user:secret@host.example/o/r0.git".into());
265 many[1].https_url = Some("https://host.example/o/r1.git".into());
266 let k = key("gh", "ann");
267 store(dir.path(), &CachedList::new(k.clone(), 1, many)).unwrap();
268 let back = load(dir.path(), &k).unwrap();
269 assert_eq!(back.projects.len(), MAX_PROJECTS);
270 assert_eq!(
271 back.projects[0].description.as_ref().unwrap().len(),
272 MAX_DESCRIPTION
273 );
274 assert_eq!(
275 back.projects[0].https_url.as_deref(),
276 Some("https://host.example/o/r0.git")
277 );
278 assert_eq!(
279 back.projects[1].https_url.as_deref(),
280 Some("https://host.example/o/r1.git")
281 );
282 let raw = std::fs::read_to_string(path_of(dir.path(), &k)).unwrap();
283 assert!(!raw.contains("secret"));
284 }
285
286 #[test]
287 fn prune_drops_unknown_ids_and_changed_login() {
288 let dir = tempfile::tempdir().unwrap();
289 for k in [key("gh", "ann"), key("gh", "bob"), key("gone", "ann")] {
290 store(dir.path(), &CachedList::new(k, 1, vec![])).unwrap();
291 }
292 prune(dir.path(), &[key("gh", "bob")]);
293 assert_eq!(load(dir.path(), &key("gh", "ann")), None);
294 assert_eq!(load(dir.path(), &key("gone", "ann")), None);
295 assert!(load(dir.path(), &key("gh", "bob")).is_some());
296 }
297
298 #[test]
299 fn prune_keeps_the_newest_files() {
300 let dir = tempfile::tempdir().unwrap();
301 let keys: Vec<ListKey> = (0..MAX_FILES + 3)
302 .map(|i| key(&format!("p{i}"), ""))
303 .collect();
304 for (i, k) in keys.iter().enumerate() {
305 store(dir.path(), &CachedList::new(k.clone(), i as u64, vec![])).unwrap();
306 }
307 prune(dir.path(), &keys);
308 assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), MAX_FILES);
309 assert!(load(dir.path(), &keys[0]).is_none());
310 assert!(load(dir.path(), keys.last().unwrap()).is_some());
311 }
312}