e_utils/fs/
_fs.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
use async_trait::async_trait;

use crate::{regex::regex2, AnyRes as _, AnyResult, Error};
use std::{
  borrow::Cow,
  fs,
  io::{self, Write as _},
  path::{Path, PathBuf},
};
/// 同步树形目录,返回完整路径的字符串数组
pub fn tree_from(src: impl AsRef<str>, is_next: bool) -> crate::AnyResult<Vec<PathBuf>> {
  let path = PathBuf::from(src.as_ref());

  // 处理文件情况
  if path.is_file() {
    return Ok(vec![path]);
  }

  // 获取目标目录和匹配模式
  let (target_dir, pattern) = if path.is_dir() {
    (path, None)
  } else if let Some(parent) = path.parent() {
    if !parent.is_dir() {
      return Err(format!("{} 不是一个有效的路径", parent.display()).into());
    }
    (parent.to_path_buf(), path.file_name().map(|f| f.to_string_lossy().to_string()))
  } else {
    return Err(format!("{} 不是一个有效的路径", src.as_ref()).into());
  };

  // 读取目录内容
  let files = if is_next {
    tree_folder(&target_dir)?
  } else {
    let mut list = Vec::new();
    for entry in std::fs::read_dir(&target_dir)? {
      list.push(entry?.path());
    }
    list
  };

  // 根据pattern过滤结果
  Ok(match pattern {
    Some(pat) => files.into_iter().filter(|v| regex2(&v.display().to_string(), &pat).0).collect(),
    None => files,
  })
}

/// 树形目录,返回完整路径的字符串数组
pub fn tree_folder<P>(dir_path: P) -> AnyResult<Vec<PathBuf>>
where
  P: AsRef<Path>,
{
  let path = dir_path.as_ref();
  if !path.exists() {
    return Err(format!("Path does not exist: {}", path.display()).into());
  }
  let mut result = Vec::new();
  if path.is_dir() {
    result.extend(fs::read_dir(path)?.filter_map(|entry| entry.ok()).flat_map(|entry| {
      let path = entry.path();
      if path.is_dir() {
        tree_folder(path).unwrap_or_default()
      } else {
        vec![path]
      }
    }));
  } else {
    result.push(path.to_path_buf());
  }

  Ok(result)
}

/// 解析字符串中的,
pub fn tree_from_str(src: impl AsRef<str>) -> Vec<String> {
  src.as_ref().split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect()
}
/// 正则匹配文件夹中的文件
pub fn regex_read_dir(src: impl AsRef<Path>, pat: &str) -> crate::Result<Vec<String>> {
  Ok(
    fs::read_dir(src.as_ref())
      .any()?
      .filter_map(Result::ok)
      .filter_map(|entry| {
        let path = entry.path();
        path
          .is_file()
          .then(|| {
            let path_str = path.to_string_lossy().to_string();
            let (is_success, res) = regex2(&path_str, pat);
            if is_success {
              res.map(|v| v.to_string())
            } else {
              Some(path_str)
            }
          })
          .flatten()
      })
      .collect(),
  )
}
/// 重命名
pub fn rename_file<P, P2>(src: P, dst: P2) -> AnyResult<()>
where
  P: AsRef<Path>,
  P2: AsRef<Path>,
{
  let src = src.as_ref();
  let dst = dst.as_ref();
  if src.exists() && src.is_file() {
    if dst.exists() && !dst.is_file() {
      Err(format!("目标已存在,并非文件格式 {}", dst.display()).into())
    } else {
      fs::rename(src, dst)?;
      if dst.exists() && dst.is_file() {
        Ok(())
      } else {
        Err(format!("源{} 目标移动失败 {}", src.display(), dst.display()).into())
      }
    }
  } else {
    Err(format!("原始缓存文件不存在 {}", src.display()).into())
  }
}
/// 自动化转换路径
pub fn convert_path(path_str: &str) -> String {
  if cfg!(target_os = "windows") {
    path_str.replace('/', "\\")
  } else {
    String::from(path_str)
  }
}

/// 复制目录
pub fn auto_copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> AnyResult<()> {
  let from_path = from.as_ref();
  let to_path = to.as_ref();

  if from_path.is_file() {
    // 如果是文件,直接复制
    fs::copy(from_path, to_path)?;
  } else if from_path.is_dir() {
    // to_path.auto_create_dir()?;
    // 遍历目录中的所有条目
    for entry in fs::read_dir(from_path)? {
      let entry = entry?;
      let from_entry_path = entry.path();
      let to_entry_path = to_path.join(from_entry_path.file_name().ok_or(Error::Str("无法解析文件名".into()))?);
      // 递归复制每个条目
      auto_copy(from_entry_path, to_entry_path)?;
    }
  } else {
    // 如果既不是文件也不是目录,返回错误
    return Err("Path is neither a file nor a directory".into());
  }
  Ok(())
}

/// 写入
fn write<'a>(path: &PathBuf, bytes: Cow<'a, [u8]>, is_sync: bool, is_append: bool) -> AnyResult<()> {
  if !is_append && path.exists() {
    // path.auto_remove_file()?;
  }
  let mut f = fs::OpenOptions::new().read(true).write(true).create(true).append(is_append).open(path)?;
  f.write_all(&bytes)?;
  if is_sync {
    f.sync_data()?;
  }
  Ok(())
}
/// 写入GBK格式
#[cfg(feature = "encode")]
pub fn write_gbk<'a>(path: &PathBuf, content: &'a str, is_sync: bool, is_append: bool) -> AnyResult<()> {
  let (bytes, _encode, had_errors) = encoding_rs::GBK.encode(content);
  if had_errors {
    return Err("写入GBK失败".into());
  } else {
    write(path, bytes, is_sync, is_append)
  }
}
/// 写入UTF-8格式
#[cfg(feature = "encode")]
pub fn write_utf8<'a>(path: &PathBuf, content: &'a str, is_sync: bool, is_append: bool) -> AnyResult<()> {
  let (bytes, _encode, had_errors) = encoding_rs::UTF_8.encode(content);
  if had_errors {
    return Err("写入UTF-8失败".into());
  } else {
    write(path, bytes, is_sync, is_append)
  }
}
/// 异步写入
#[cfg(feature = "tokio")]
pub mod a_sync {
  use crate::{regex::regex2, AnyRes as _, AnyResult};
  use std::{
    borrow::Cow,
    path::{Path, PathBuf},
  };
  use tokio::{fs, io::AsyncWriteExt as _};

  /// 异步树形目录,返回完整路径的字符串数组
  pub async fn a_tree_from(src: impl AsRef<str>, is_next: bool) -> crate::AnyResult<Vec<PathBuf>> {
    let path = PathBuf::from(src.as_ref());
    // 处理文件情况
    if path.is_file() {
      return Ok(vec![path]);
    }
    // 获取目标目录和匹配模式
    let (target_dir, pattern) = if path.is_dir() {
      (path, None)
    } else if let Some(parent) = path.parent() {
      if !parent.is_dir() {
        return Err(format!("{} 不是一个有效的路径", parent.display()).into());
      }
      (parent.to_path_buf(), path.file_name().map(|f| f.to_string_lossy().to_string()))
    } else {
      return Err(format!("{} 不是一个有效的路径", src.as_ref()).into());
    };

    // 读取目录内容
    let files = if is_next {
      a_tree_folder(&target_dir).await?
    } else {
      let mut list = Vec::new();
      let mut dir = tokio::fs::read_dir(&target_dir).await?;
      while let Some(entry) = dir.next_entry().await? {
        list.push(entry.path());
      }
      list
    };

    // 根据pattern过滤结果
    Ok(match pattern {
      Some(pat) => files.into_iter().filter(|v| regex2(&v.display().to_string(), &pat).0).collect(),
      None => files,
    })
  }

  /// 异步树形目录,返回完整路径的字符串数组
  pub async fn a_tree_folder<P>(dir_path: P) -> AnyResult<Vec<PathBuf>>
  where
    P: AsRef<Path>,
  {
    Box::pin(async move {
      let path = dir_path.as_ref();
      if !path.exists() {
        return Err(format!("Path does not exist: {}", path.display()).into());
      }
      let mut result = Vec::new();
      if path.is_dir() {
        let mut read_dir = tokio::fs::read_dir(path).await?;
        while let Some(entry) = read_dir.next_entry().await? {
          let path = entry.path();
          if path.is_dir() {
            let sub_files = a_tree_folder(&path).await?;
            result.extend(sub_files);
          } else {
            result.push(path);
          }
        }
      } else {
        result.push(path.to_path_buf());
      }
      Ok(result)
    })
    .await
  }

  /// 异步正则匹配文件夹中的文件
  pub async fn a_regex_read_dir(src: impl AsRef<Path>, pat: &str) -> crate::Result<Vec<String>> {
    let mut entries = tokio::fs::read_dir(src.as_ref()).await.any()?;
    let mut results = Vec::new();
    while let Some(entry) = entries.next_entry().await.any()? {
      let path = entry.path();
      if path.is_file() {
        let path_str = path.to_string_lossy().to_string();
        let (is_success, res) = regex2(&path_str, pat);
        if is_success {
          if let Some(v) = res {
            results.push(v.to_string());
          }
        } else {
          results.push(path_str);
        }
      }
    }

    Ok(results)
  }

  /// 异步写入
  async fn write<'a>(path: &PathBuf, bytes: Cow<'a, [u8]>, is_sync: bool, is_append: bool) -> AnyResult<()> {
    if !is_append && path.exists() {
      fs::remove_file(path).await?
    }
    let mut f = fs::OpenOptions::new().read(true).write(true).create(true).append(is_append).open(path).await?;
    f.write_all(&bytes).await?;
    if is_sync {
      f.sync_data().await?;
    }
    Ok(())
  }
  /// 异步写入GBK格式
  #[cfg(feature = "encode")]
  pub async fn write_gbk<'a>(path: &PathBuf, content: &'a str, is_sync: bool, is_append: bool) -> AnyResult<()> {
    let (bytes, _encode, had_errors) = encoding_rs::GBK.encode(content);
    if had_errors {
      return Err("异步写入GBK失败".into());
    } else {
      write(path, bytes, is_sync, is_append).await
    }
  }
  /// 异步写入UTF-8格式
  #[cfg(feature = "encode")]
  pub async fn write_utf8<'a>(path: &PathBuf, content: &'a str, is_sync: bool, is_append: bool) -> AnyResult<()> {
    let (bytes, _encode, had_errors) = encoding_rs::UTF_8.encode(content);
    if had_errors {
      return Err("异步写入UTF-8失败".into());
    } else {
      write(path, bytes, is_sync, is_append).await
    }
  }
}

/// 自动检查和操作文件系统路径
#[async_trait]
pub trait AutoPath {
  /// 自动创建目录
  ///
  /// # Example
  ///
  /// ```
  /// use std::path::Path;
  /// use e_utils::fs::AutoPath;
  ///
  /// let path = Path::new("test_dir");
  /// path.auto_create_dir().unwrap();
  /// assert!(path.exists() && path.is_dir());
  ///
  /// // 清理
  /// std::fs::remove_dir(path).unwrap();
  /// ```
  fn auto_create_dir(&self) -> AnyResult<()>;

  /// 自动移除目录
  ///
  /// # Example
  ///
  /// ```
  /// use std::path::Path;
  /// use e_utils::fs::AutoPath;
  ///
  /// let path = Path::new("test_remove_dir");
  /// std::fs::create_dir(path).unwrap();
  /// assert!(path.exists());
  ///
  /// path.auto_remove_dir().unwrap();
  /// assert!(!path.exists());
  /// ```
  fn auto_remove_dir(&self) -> AnyResult<()>;

  /// 自动创建文件
  ///
  /// # Example
  ///
  /// ```
  /// use std::path::Path;
  /// use e_utils::fs::AutoPath;
  ///
  /// let path = Path::new("test_file.txt");
  /// path.auto_create_file("Hello, World!").unwrap();
  /// assert!(path.exists() && path.is_file());
  ///
  /// let content = std::fs::read_to_string(path).unwrap();
  /// assert_eq!(content, "Hello, World!");
  ///
  /// // 清理
  /// std::fs::remove_file(path).unwrap();
  /// ```
  fn auto_create_file<S: AsRef<str>>(&self, content: S) -> AnyResult<()>;

  /// 自动移除文件
  ///
  /// # Example
  ///
  /// ```
  /// use std::path::Path;
  /// use e_utils::fs::AutoPath;
  ///
  /// let path = Path::new("test_remove_file.txt");
  /// std::fs::write(path, "Test content").unwrap();
  /// assert!(path.exists());
  ///
  /// path.auto_remove_file().unwrap();
  /// assert!(!path.exists());
  /// ```
  fn auto_remove_file(&self) -> AnyResult<()>;

  /// Asynchronously creates a directory.
  ///
  /// # Example
  ///
  /// ```
  /// use std::path::Path;
  /// use e_utils::fs::AutoPath;
  ///
  /// #[tokio::main]
  /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
  ///     let path = Path::new("test_async_dir");
  ///     path.a_auto_create_dir().await?;
  ///     assert!(path.exists() && path.is_dir());
  ///
  ///     // Clean up
  ///     tokio::fs::remove_dir(path).await?;
  ///     Ok(())
  /// }
  /// ```
  #[cfg(feature = "tokio")]
  async fn a_auto_create_dir(&self) -> AnyResult<()>;

  /// Asynchronously removes a directory.
  ///
  /// # Example
  ///
  /// ```
  /// use std::path::Path;
  /// use e_utils::fs::AutoPath;
  ///
  /// #[tokio::main]
  /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
  ///     let path = Path::new("test_async_remove_dir");
  ///     tokio::fs::create_dir(path).await?;
  ///     assert!(path.exists());
  ///
  ///     path.a_auto_remove_dir().await?;
  ///     assert!(!path.exists());
  ///     Ok(())
  /// }
  /// ```
  #[cfg(feature = "tokio")]
  async fn a_auto_remove_dir(&self) -> AnyResult<()>;

  /// Asynchronously creates a file with the given content.
  ///
  /// # Example
  ///
  /// ```
  /// use std::path::Path;
  /// use e_utils::fs::AutoPath;
  ///
  /// #[tokio::main]
  /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
  ///     let path = Path::new("test_async_file.txt");
  ///     path.a_auto_create_file("Hello, World!").await?;
  ///     assert!(path.exists() && path.is_file());
  ///
  ///     let content = tokio::fs::read_to_string(path).await?;
  ///     assert_eq!(content, "Hello, World!");
  ///
  ///     // Clean up
  ///     tokio::fs::remove_file(path).await?;
  ///     Ok(())
  /// }
  /// ```
  #[cfg(feature = "tokio")]
  async fn a_auto_create_file(&self, content: impl AsRef<[u8]> + Send) -> AnyResult<()>;

  /// Asynchronously removes a file.
  ///
  /// # Example
  ///
  /// ```
  /// use std::path::Path;
  /// use e_utils::fs::AutoPath;
  ///
  /// #[tokio::main]
  /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
  ///     let path = Path::new("test_async_remove_file.txt");
  ///     tokio::fs::write(path, "Test content").await?;
  ///     assert!(path.exists());
  ///
  ///     path.a_auto_remove_file().await?;
  ///     assert!(!path.exists());
  ///     Ok(())
  /// }
  /// ```
  #[cfg(feature = "tokio")]
  async fn a_auto_remove_file(&self) -> AnyResult<()>;
}

#[async_trait]
impl<T: AsRef<str> + Send + Sync> AutoPath for T {
  fn auto_create_dir(&self) -> AnyResult<()> {
    Path::new(self.as_ref()).auto_create_dir()
  }

  fn auto_remove_dir(&self) -> AnyResult<()> {
    Path::new(self.as_ref()).auto_remove_dir()
  }

  fn auto_create_file<S>(&self, content: S) -> AnyResult<()>
  where
    S: AsRef<str>,
  {
    Path::new(self.as_ref()).auto_create_file(content)
  }

  fn auto_remove_file(&self) -> AnyResult<()> {
    Path::new(self.as_ref()).auto_remove_file()
  }
  #[cfg(feature = "tokio")]
  async fn a_auto_create_dir(&self) -> AnyResult<()> {
    Path::new(self.as_ref()).a_auto_create_dir().await
  }
  #[cfg(feature = "tokio")]
  async fn a_auto_remove_dir(&self) -> AnyResult<()> {
    Path::new(self.as_ref()).a_auto_remove_dir().await
  }
  #[cfg(feature = "tokio")]
  async fn a_auto_create_file(&self, content: impl AsRef<[u8]> + Send) -> AnyResult<()> {
    Path::new(self.as_ref()).a_auto_create_file(content).await
  }
  #[cfg(feature = "tokio")]
  async fn a_auto_remove_file(&self) -> AnyResult<()> {
    Path::new(self.as_ref()).a_auto_remove_file().await
  }
}
#[async_trait]
impl AutoPath for Path {
  fn auto_create_dir(&self) -> AnyResult<()> {
    if !self.exists() {
      fs::create_dir_all(self)?;
      if !self.exists() {
        return Err(format!("{} -> {}", self.display(), io::ErrorKind::NotFound).into());
      }
    }
    return Ok(());
  }
  fn auto_remove_dir(&self) -> AnyResult<()> {
    if self.is_dir() {
      fs::remove_dir_all(self)?;
      if self.exists() {
        return Err(format!("{} -> {}", self.display(), io::ErrorKind::AlreadyExists).into());
      }
    } else if self.exists() {
      return Err(format!("{} is not a directory", self.display()).into());
    }
    Ok(())
  }

  fn auto_create_file<S: AsRef<str>>(&self, data: S) -> AnyResult<()> {
    if !self.exists() {
      fs::write(self, data.as_ref())?;
    } else if !self.is_file() {
      return Err(format!("{} -> {}", self.display(), io::ErrorKind::AlreadyExists).into());
    }
    Ok(())
  }

  fn auto_remove_file(&self) -> AnyResult<()> {
    if self.exists() {
      if self.is_file() {
        fs::remove_file(self)?;
      } else {
        return Err(format!("{} -> {}", self.display(), io::ErrorKind::AlreadyExists).into());
      }
    }
    Ok(())
  }
  #[cfg(feature = "tokio")]
  async fn a_auto_create_dir(&self) -> AnyResult<()> {
    if !self.exists() {
      tokio::fs::create_dir_all(self).await?;
      if !self.exists() {
        return Err(format!("{} -> {}", self.display(), io::ErrorKind::NotFound).into());
      }
    }
    return Ok(());
  }

  #[cfg(feature = "tokio")]
  async fn a_auto_remove_dir(&self) -> AnyResult<()> {
    if self.is_dir() {
      tokio::fs::remove_dir_all(self).await?;
      if self.exists() {
        return Err(format!("{} -> {}", self.display(), io::ErrorKind::AlreadyExists).into());
      }
    } else if self.exists() {
      return Err(format!("{} is not a directory", self.display()).into());
    }
    Ok(())
  }

  #[cfg(feature = "tokio")]
  async fn a_auto_create_file(&self, content: impl AsRef<[u8]> + Send) -> AnyResult<()> {
    if !self.exists() {
      tokio::fs::write(self, content.as_ref()).await?;
    } else if !self.is_file() {
      return Err(format!("{} -> {}", self.display(), io::ErrorKind::AlreadyExists).into());
    }
    Ok(())
  }

  #[cfg(feature = "tokio")]
  async fn a_auto_remove_file(&self) -> AnyResult<()> {
    if self.exists() {
      if self.is_file() {
        tokio::fs::remove_file(self).await?;
      } else {
        return Err(format!("{} -> {}", self.display(), io::ErrorKind::AlreadyExists).into());
      }
    }
    Ok(())
  }
}
/// 创建临时文件
pub fn temp_file(folder: impl AsRef<str>, fname: impl AsRef<str>, content: impl AsRef<str>) -> crate::AnyResult<PathBuf> {
  let path = std::env::temp_dir().join(folder.as_ref());
  path.auto_create_dir()?;
  let target = path.join(fname.as_ref());
  target.auto_create_file(content.as_ref())?;
  Ok(target)
}
/// 创建临时文件
#[cfg(feature = "tokio")]
pub async fn a_temp_file(folder: impl AsRef<str>, fname: impl AsRef<str>, content: impl AsRef<str>) -> crate::AnyResult<PathBuf> {
  let path = std::env::temp_dir().join(folder.as_ref());
  path.a_auto_create_dir().await?;
  let target = path.join(fname.as_ref());
  target.a_auto_create_file(content.as_ref()).await?;
  Ok(target)
}

#[cfg(test)]
mod auto_path_tests {
  use super::*;
  use std::fs;

  #[test]
  fn test_auto_create_dir() {
    let path = temp_file("test", "test_file.txt", "Hello, World!").unwrap();
    assert!(path.exists() && path.parent().unwrap().is_dir());
  }

  #[test]
  fn test_auto_remove_dir() {
    let path = temp_file("test", "test_remove_dir", "Hello, World!").unwrap();
    let parent = path.parent().unwrap();
    parent.auto_remove_dir().unwrap();
    assert!(!parent.exists());
  }

  #[test]
  fn test_auto_create_file() {
    let path = temp_file("test", "test_file.txt", "Hello, World!").unwrap();
    assert!(path.exists() && path.is_file());
    assert_eq!(fs::read_to_string(&path).unwrap(), "Hello, World!");
  }

  #[test]
  fn test_auto_remove_file() {
    let path = temp_file("test", "test_remove_file.txt", "Test content").unwrap();
    let parent = path.parent().unwrap();
    parent.auto_remove_dir().unwrap();
    assert!(!parent.exists());
  }

  #[cfg(feature = "tokio")]
  #[tokio::test]
  async fn test_a_auto_create_dir() {
    let path = temp_file("test", "test_async_dir", "Test content").unwrap();
    path.a_auto_create_dir().await.unwrap();
    assert!(path.exists() && path.is_dir());
  }

  #[cfg(feature = "tokio")]
  #[tokio::test]
  async fn test_a_auto_remove_dir() {
    let path = temp_file("test", "test_async_remove_dir", "Test content").unwrap();
    let parent = path.parent().unwrap();
    parent.a_auto_remove_dir().await.unwrap();
    assert!(!parent.exists());
  }

  #[cfg(feature = "tokio")]
  #[tokio::test]
  async fn test_a_auto_create_file() {
    let path = temp_file("test", "test_async_file.txt", "Hello, Async World!").unwrap();
    assert!(path.exists() && path.is_file());
    assert_eq!(tokio::fs::read_to_string(&path).await.unwrap(), "Hello, Async World!");
  }

  #[cfg(feature = "tokio")]
  #[tokio::test]
  async fn test_a_auto_remove_file() {
    let path = temp_file("test", "test_async_remove_file.txt", "Test async content").unwrap();
    let parent = path.parent().unwrap();
    parent.a_auto_remove_dir().await.unwrap();
    assert!(!parent.exists());
  }
}