1use directories::ProjectDirs;
2#[cfg(not(target_family = "wasm"))]
3use fs4::fs_std::FileExt;
4use log::debug;
5#[cfg(not(target_family = "wasm"))]
6use std::fs::File;
7use std::path::{Path, PathBuf};
8use walkdir::WalkDir;
9
10mod path_error;
11pub use path_error::PathError;
12
13#[derive(Clone, Debug)]
14pub struct PathSet {
15 pub prj: String,
16 pub src: PathBuf,
17 pub dst: PathBuf,
18 pub map: PathBuf,
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 lock.lock_exclusive()?;
77 Ok(lock)
78}
79
80#[cfg(not(target_family = "wasm"))]
81pub fn unlock_dir(lock: File) -> Result<(), PathError> {
82 fs4::fs_std::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
96pub fn ignore_already_exists(x: Result<(), std::io::Error>) -> Result<(), std::io::Error> {
97 if let Err(x) = x
98 && x.kind() != std::io::ErrorKind::AlreadyExists
99 {
100 return Err(x);
101 }
102 Ok(())
103}
104
105pub fn ignore_directory_not_empty(x: Result<(), std::io::Error>) -> Result<(), std::io::Error> {
106 if let Err(x) = x
107 && x.kind() != std::io::ErrorKind::DirectoryNotEmpty
108 {
109 return Err(x);
110 }
111 Ok(())
112}