path.rs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. use std::path::PathBuf;
  2. use mlua::{UserData, Variadic};
  3. pub struct PluginPath;
  4. impl UserData for PluginPath {
  5. fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) {
  6. // join function
  7. methods.add_function("join", |_, args: Variadic<String>| {
  8. let mut path = PathBuf::new();
  9. for i in args {
  10. path = path.join(i);
  11. }
  12. Ok(path.to_str().unwrap().to_string())
  13. });
  14. // parent function
  15. methods.add_function("parent", |_, path: String| {
  16. let current_path = PathBuf::from(&path);
  17. let parent = current_path.parent();
  18. if parent.is_none() {
  19. return Ok(path);
  20. } else {
  21. return Ok(parent.unwrap().to_str().unwrap().to_string());
  22. }
  23. });
  24. methods.add_function("exists", |_, path: String| {
  25. let path = PathBuf::from(path);
  26. Ok(path.exists())
  27. });
  28. methods.add_function("is_dir", |_, path: String| {
  29. let path = PathBuf::from(path);
  30. Ok(path.is_dir())
  31. });
  32. methods.add_function("is_file", |_, path: String| {
  33. let path = PathBuf::from(path);
  34. Ok(path.is_file())
  35. });
  36. }
  37. }