leejunyoung5819 handmade-dataset-creator
공개고품질 LLM 데이터셋 수제작을 위한 생산성 도구
| 1 | //! 최근에 연 파일 목록. `~/.config/handmade-dataset-creator/recent.json` 에 저장된다. |
| 2 | |
| 3 | use std::path::{Path, PathBuf}; |
| 4 | |
| 5 | pub const MAX_RECENT: usize = 10; |
| 6 | |
| 7 | #[derive(Debug, Default)] |
| 8 | pub struct RecentFiles { |
| 9 | pub paths: Vec<PathBuf>, |
| 10 | /// 저장 위치. None이면 저장하지 않는다(테스트 등). |
| 11 | store: Option<PathBuf>, |
| 12 | } |
| 13 | |
| 14 | impl RecentFiles { |
| 15 | /// `$XDG_CONFIG_HOME/handmade-dataset-creator/recent.json` (없으면 `~/.config/...`) |
| 16 | pub fn default_store() -> Option<PathBuf> { |
| 17 | let base = std::env::var_os("XDG_CONFIG_HOME") |
| 18 | .map(PathBuf::from) |
| 19 | .filter(|p| p.is_absolute()) |
| 20 | .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))?; |
| 21 | Some(base.join("handmade-dataset-creator").join("recent.json")) |
| 22 | } |
| 23 | |
| 24 | /// 저장 위치에서 읽는다. 파일이 없거나 깨져 있으면 빈 목록. |
| 25 | pub fn load(store: Option<PathBuf>) -> Self { |
| 26 | let paths = store |
| 27 | .as_deref() |
| 28 | .and_then(|p| std::fs::read_to_string(p).ok()) |
| 29 | .and_then(|t| serde_json::from_str::<Vec<PathBuf>>(&t).ok()) |
| 30 | .unwrap_or_default(); |
| 31 | let mut r = RecentFiles { paths, store }; |
| 32 | r.paths.truncate(MAX_RECENT); |
| 33 | r |
| 34 | } |
| 35 | |
| 36 | /// 맨 앞에 추가(이미 있으면 앞으로 이동)하고 저장. |
| 37 | pub fn add(&mut self, path: &Path) { |
| 38 | let path = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()); |
| 39 | self.paths.retain(|p| p != &path); |
| 40 | self.paths.insert(0, path); |
| 41 | self.paths.truncate(MAX_RECENT); |
| 42 | self.save(); |
| 43 | } |
| 44 | |
| 45 | pub fn remove(&mut self, path: &Path) { |
| 46 | self.paths.retain(|p| p != path); |
| 47 | self.save(); |
| 48 | } |
| 49 | |
| 50 | pub fn clear(&mut self) { |
| 51 | self.paths.clear(); |
| 52 | self.save(); |
| 53 | } |
| 54 | |
| 55 | fn save(&self) { |
| 56 | let Some(store) = &self.store else { return }; |
| 57 | if let Some(dir) = store.parent() { |
| 58 | let _ = std::fs::create_dir_all(dir); |
| 59 | } |
| 60 | // 최근 파일 목록은 부가 기능이라, 저장 실패는 조용히 무시한다. |
| 61 | if let Ok(text) = serde_json::to_string_pretty(&self.paths) { |
| 62 | let _ = std::fs::write(store, text); |
| 63 | } |
| 64 | } |
| 65 | } |