fs.rs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. use std::{
  2. fs::{create_dir, create_dir_all, remove_dir_all, File},
  3. io::{Read, Write},
  4. path::PathBuf,
  5. };
  6. use crate::tools::extract_zip;
  7. use flate2::read::GzDecoder;
  8. use mlua::UserData;
  9. use tar::Archive;
  10. pub struct PluginFileSystem;
  11. impl UserData for PluginFileSystem {
  12. fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) {
  13. methods.add_function("create_dir", |_, args: (String, bool)| {
  14. let path = args.0;
  15. let recursive = args.1;
  16. let path = PathBuf::from(path);
  17. if !path.exists() {
  18. let v = if recursive {
  19. create_dir_all(path)
  20. } else {
  21. create_dir(path)
  22. };
  23. return Ok(v.is_ok());
  24. }
  25. Ok(true)
  26. });
  27. methods.add_function("remove_dir", |_, path: String| {
  28. let path = PathBuf::from(path);
  29. let r = remove_dir_all(path);
  30. Ok(r.is_ok())
  31. });
  32. methods.add_function("file_get_content", |_, path: String| {
  33. let path = PathBuf::from(path);
  34. let mut file = std::fs::File::open(path)?;
  35. let mut buffer = String::new();
  36. file.read_to_string(&mut buffer)?;
  37. Ok(buffer)
  38. });
  39. methods.add_function("file_set_content", |_, args: (String, String)| {
  40. let path = args.0;
  41. let content = args.1;
  42. let path = PathBuf::from(path);
  43. let file = std::fs::File::create(path);
  44. if file.is_err() {
  45. return Ok(false);
  46. }
  47. if file.unwrap().write_all(content.as_bytes()).is_err() {
  48. return Ok(false);
  49. }
  50. Ok(true)
  51. });
  52. methods.add_function("unzip_file", |_, args: (String, String)| {
  53. let file = PathBuf::from(args.0);
  54. let target = PathBuf::from(args.1);
  55. let res = extract_zip(&file, &target);
  56. if let Err(_) = res {
  57. return Ok(false);
  58. }
  59. Ok(true)
  60. });
  61. methods.add_function("untar_gz_file", |_, args: (String, String)| {
  62. let file = PathBuf::from(args.0);
  63. let target = PathBuf::from(args.1);
  64. let tar_gz = if let Ok(v) = File::open(file) {
  65. v
  66. } else {
  67. return Ok(false);
  68. };
  69. let tar = GzDecoder::new(tar_gz);
  70. let mut archive = Archive::new(tar);
  71. if archive.unpack(&target).is_err() {
  72. return Ok(false);
  73. }
  74. Ok(true)
  75. });
  76. }
  77. }