Skip to main content

veryl_path/
lib.rs

1use directories::ProjectDirs;
2use log::debug;
3#[cfg(not(target_family = "wasm"))]
4use std::fs::File;
5use std::path::{Path, PathBuf};
6use walkdir::WalkDir;
7
8mod path_error;
9pub use path_error::PathError;
10
11#[derive(Clone, Debug)]
12pub struct PathSet {
13    pub prj: String,
14    pub src: PathBuf,
15    pub dst: PathBuf,
16    pub map: PathBuf,
17}
18
19pub fn cache_path() -> PathBuf {
20    let project_dir = ProjectDirs::from("org", "veryl-lang", "veryl").unwrap();
21    project_dir.cache_dir().to_path_buf()
22}
23
24pub fn gather_files_with_extension<T: AsRef<Path>>(
25    base_dir: T,
26    ext: &str,
27    symlink: bool,
28) -> Result<Vec<PathBuf>, PathError> {
29    let mut inner_prj = Vec::new();
30    for entry in WalkDir::new(base_dir.as_ref())
31        .follow_links(symlink)
32        .into_iter()
33        .flatten()
34    {
35        if entry.file_type().is_file()
36            && let Some(x) = entry.path().file_name()
37            && x == "Veryl.toml"
38        {
39            let prj_dir = entry.path().parent().unwrap();
40            if prj_dir != base_dir.as_ref() {
41                debug!("Found inner project ({})", prj_dir.to_string_lossy());
42                inner_prj.push(prj_dir.to_path_buf());
43            }
44        }
45    }
46
47    let mut ret = Vec::new();
48    for entry in WalkDir::new(base_dir.as_ref())
49        .follow_links(symlink)
50        .sort_by_file_name()
51        .into_iter()
52        .flatten()
53    {
54        if entry.file_type().is_file()
55            && let Some(x) = entry.path().extension()
56            && x == ext
57        {
58            let is_inner = inner_prj.iter().any(|x| entry.path().starts_with(x));
59
60            if !is_inner {
61                debug!("Found file ({})", entry.path().to_string_lossy());
62                ret.push(entry.path().to_path_buf());
63            }
64        }
65    }
66    Ok(ret)
67}
68
69#[cfg(not(target_family = "wasm"))]
70pub fn lock_dir<T: AsRef<Path>>(path: T) -> Result<File, PathError> {
71    let base_dir = cache_path().join(path);
72    let lock = base_dir.join("lock");
73    let lock = File::create(lock)?;
74    fs4::FileExt::lock(&lock)?;
75    Ok(lock)
76}
77
78#[cfg(not(target_family = "wasm"))]
79pub fn unlock_dir(lock: File) -> Result<(), PathError> {
80    fs4::FileExt::unlock(&lock)?;
81    Ok(())
82}
83
84#[cfg(target_family = "wasm")]
85pub fn lock_dir<T: AsRef<Path>>(_path: T) -> Result<(), PathError> {
86    Ok(())
87}
88
89#[cfg(target_family = "wasm")]
90pub fn unlock_dir(_lock: ()) -> Result<(), PathError> {
91    Ok(())
92}
93
94/// Write `contents` to `path` atomically (temp file + rename) so a concurrent
95/// reader never observes a truncated/empty file, only the old or new contents.
96#[cfg(not(target_family = "wasm"))]
97pub fn atomic_write<P: AsRef<Path>>(path: P, contents: &[u8]) -> std::io::Result<()> {
98    use std::io::Write;
99    let path = path.as_ref();
100    // The temp must share the target's dir so the rename stays on one filesystem.
101    let dir = path
102        .parent()
103        .filter(|x| !x.as_os_str().is_empty())
104        .unwrap_or(Path::new("."));
105    let mut file = tempfile::NamedTempFile::new_in(dir)?;
106    file.write_all(contents)?;
107    // tempfile creates with 0600; widen to 0644 to match a plain write.
108    #[cfg(unix)]
109    {
110        use std::os::unix::fs::PermissionsExt;
111        file.as_file()
112            .set_permissions(std::fs::Permissions::from_mode(0o644))?;
113    }
114    // On Windows, replacing the target while a reader holds it open transiently
115    // fails with a sharing violation (PermissionDenied); retry a few times.
116    let mut attempts = 0;
117    loop {
118        match file.persist(path) {
119            Ok(_) => return Ok(()),
120            Err(e) => {
121                attempts += 1;
122                if attempts >= 50 || e.error.kind() != std::io::ErrorKind::PermissionDenied {
123                    return Err(e.error);
124                }
125                file = e.file;
126                std::thread::sleep(std::time::Duration::from_millis(10));
127            }
128        }
129    }
130}
131
132// wasm has no real filesystem concurrency; fall back to a plain write.
133#[cfg(target_family = "wasm")]
134pub fn atomic_write<P: AsRef<Path>>(path: P, contents: &[u8]) -> std::io::Result<()> {
135    std::fs::write(path, contents)
136}
137
138pub fn ignore_already_exists(x: Result<(), std::io::Error>) -> Result<(), std::io::Error> {
139    if let Err(x) = x
140        && x.kind() != std::io::ErrorKind::AlreadyExists
141    {
142        return Err(x);
143    }
144    Ok(())
145}
146
147pub fn ignore_directory_not_empty(x: Result<(), std::io::Error>) -> Result<(), std::io::Error> {
148    if let Err(x) = x
149        && x.kind() != std::io::ErrorKind::DirectoryNotEmpty
150    {
151        return Err(x);
152    }
153    Ok(())
154}