helpers.rs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. use anyhow::Context;
  2. use std::{fs, path::Path};
  3. pub fn find_unique_file(dir_path: &str, suffix: &str) -> anyhow::Result<String> {
  4. let mut matching_files = Vec::new();
  5. for entry in
  6. fs::read_dir(dir_path).with_context(|| format!("Failed to read directory: {}", dir_path))?
  7. {
  8. let entry = entry.with_context(|| "Failed to read directory entry")?;
  9. let path = entry.path();
  10. if path.is_file()
  11. && path
  12. .file_name()
  13. .and_then(|name| name.to_str())
  14. .map(|name| name.ends_with(suffix))
  15. .unwrap_or(false)
  16. {
  17. matching_files.push(path);
  18. }
  19. }
  20. match matching_files.len() {
  21. 0 => Err(anyhow::anyhow!("No file found ending with '{}'", suffix))
  22. .with_context(|| format!("In directory: {}", dir_path)),
  23. 1 => Ok(matching_files[0].to_string_lossy().into_owned()),
  24. _ => Err(anyhow::anyhow!(
  25. "Multiple files found ending with '{}'",
  26. suffix
  27. ))
  28. .with_context(|| format!("In directory: {}", dir_path)),
  29. }
  30. }
  31. pub fn path_prefix(out: &str) -> anyhow::Result<String> {
  32. let out_path = Path::new(&out);
  33. let out_dir = out_path
  34. .parent()
  35. .ok_or_else(|| anyhow::anyhow!("Can't parse the dir of {}", out_path.display()))?;
  36. let name = out_path
  37. .file_name()
  38. .and_then(|name| name.to_str())
  39. .ok_or_else(|| anyhow::anyhow!("Can't parse the file name of {}", out_path.display()))?;
  40. let stem = name
  41. .split_once('.')
  42. .map(|(stem, _)| stem)
  43. .ok_or_else(|| anyhow::anyhow!("Can't parse the file stem of {}", name))?;
  44. Ok(format!("{}/{stem}", out_dir.display()))
  45. }
  46. pub fn force_or_not(path: &str, force: bool) -> anyhow::Result<()> {
  47. let path = Path::new(path);
  48. let mut output_exists = path.exists();
  49. if force && output_exists {
  50. fs::remove_dir_all(
  51. path.parent()
  52. .context(format!("Can't parse the parent dir of {}", path.display()))?,
  53. )?;
  54. output_exists = false;
  55. }
  56. if output_exists {
  57. anyhow::bail!("{} already exists.", path.display())
  58. }
  59. Ok(())
  60. }