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
94pub fn ignore_already_exists(x: Result<(), std::io::Error>) -> Result<(), std::io::Error> {
95 if let Err(x) = x
96 && x.kind() != std::io::ErrorKind::AlreadyExists
97 {
98 return Err(x);
99 }
100 Ok(())
101}
102
103pub fn ignore_directory_not_empty(x: Result<(), std::io::Error>) -> Result<(), std::io::Error> {
104 if let Err(x) = x
105 && x.kind() != std::io::ErrorKind::DirectoryNotEmpty
106 {
107 return Err(x);
108 }
109 Ok(())
110}