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 pub example: bool,
19}
20
21pub fn cache_path() -> PathBuf {
22 let project_dir = ProjectDirs::from("org", "veryl-lang", "veryl").unwrap();
23 project_dir.cache_dir().to_path_buf()
24}
25
26pub fn gather_files_with_extension<T: AsRef<Path>>(
27 base_dir: T,
28 ext: &str,
29 symlink: bool,
30) -> Result<Vec<PathBuf>, PathError> {
31 let mut inner_prj = Vec::new();
32 for entry in WalkDir::new(base_dir.as_ref())
33 .follow_links(symlink)
34 .into_iter()
35 .flatten()
36 {
37 if entry.file_type().is_file()
38 && let Some(x) = entry.path().file_name()
39 && x == "Veryl.toml"
40 {
41 let prj_dir = entry.path().parent().unwrap();
42 if prj_dir != base_dir.as_ref() {
43 debug!("Found inner project ({})", prj_dir.to_string_lossy());
44 inner_prj.push(prj_dir.to_path_buf());
45 }
46 }
47 }
48
49 let mut ret = Vec::new();
50 for entry in WalkDir::new(base_dir.as_ref())
51 .follow_links(symlink)
52 .sort_by_file_name()
53 .into_iter()
54 .flatten()
55 {
56 if entry.file_type().is_file()
57 && let Some(x) = entry.path().extension()
58 && x == ext
59 {
60 let is_inner = inner_prj.iter().any(|x| entry.path().starts_with(x));
61
62 if !is_inner {
63 debug!("Found file ({})", entry.path().to_string_lossy());
64 ret.push(entry.path().to_path_buf());
65 }
66 }
67 }
68 Ok(ret)
69}
70
71#[cfg(not(target_family = "wasm"))]
72pub fn lock_dir<T: AsRef<Path>>(path: T) -> Result<File, PathError> {
73 let base_dir = cache_path().join(path);
74 let lock = base_dir.join("lock");
75 let lock = File::create(lock)?;
76 fs4::FileExt::lock(&lock)?;
77 Ok(lock)
78}
79
80#[cfg(not(target_family = "wasm"))]
81pub fn unlock_dir(lock: File) -> Result<(), PathError> {
82 fs4::FileExt::unlock(&lock)?;
83 Ok(())
84}
85
86#[cfg(target_family = "wasm")]
87pub fn lock_dir<T: AsRef<Path>>(_path: T) -> Result<(), PathError> {
88 Ok(())
89}
90
91#[cfg(target_family = "wasm")]
92pub fn unlock_dir(_lock: ()) -> Result<(), PathError> {
93 Ok(())
94}
95
96#[cfg(not(target_family = "wasm"))]
99pub fn atomic_write<P: AsRef<Path>>(path: P, contents: &[u8]) -> std::io::Result<()> {
100 use std::io::Write;
101 let path = path.as_ref();
102 let dir = path
104 .parent()
105 .filter(|x| !x.as_os_str().is_empty())
106 .unwrap_or(Path::new("."));
107 let mut file = tempfile::NamedTempFile::new_in(dir)?;
108 file.write_all(contents)?;
109 #[cfg(unix)]
111 {
112 use std::os::unix::fs::PermissionsExt;
113 file.as_file()
114 .set_permissions(std::fs::Permissions::from_mode(0o644))?;
115 }
116 let mut attempts = 0;
119 loop {
120 match file.persist(path) {
121 Ok(_) => return Ok(()),
122 Err(e) => {
123 attempts += 1;
124 if attempts >= 50 || e.error.kind() != std::io::ErrorKind::PermissionDenied {
125 return Err(e.error);
126 }
127 file = e.file;
128 std::thread::sleep(std::time::Duration::from_millis(10));
129 }
130 }
131 }
132}
133
134#[cfg(target_family = "wasm")]
136pub fn atomic_write<P: AsRef<Path>>(path: P, contents: &[u8]) -> std::io::Result<()> {
137 std::fs::write(path, contents)
138}
139
140pub fn ignore_already_exists(x: Result<(), std::io::Error>) -> Result<(), std::io::Error> {
141 if let Err(x) = x
142 && x.kind() != std::io::ErrorKind::AlreadyExists
143 {
144 return Err(x);
145 }
146 Ok(())
147}
148
149pub fn ignore_directory_not_empty(x: Result<(), std::io::Error>) -> Result<(), std::io::Error> {
150 if let Err(x) = x
151 && x.kind() != std::io::ErrorKind::DirectoryNotEmpty
152 {
153 return Err(x);
154 }
155 Ok(())
156}