pathkit 1.2.0

Similar to the Path structure provided by python's pathlib, it provides various async/sync versions of file manipulation methods in addition to some of the std::Path built-in methods.
Documentation
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
703
704
//! Asynchronous file system operations module
//!
//! This module provides the `AsyncFsOps` trait for asynchronous file system operations.
//! Requires the `async-fs-ops` feature to be enabled.
//!
//! # Example
//!
//! ```rust,ignore
//! use pathkit::{Path, AsyncFsOps};
//!
//! let path = Path::new("/tmp/test.txt");
//! path.write(b"Hello!").await?;
//! let content = path.read().await?;
//! ```

use std::fs::{
    Metadata,
    Permissions,
};

use anyhow::Result;
use serde::{
    de::DeserializeOwned,
    Serialize,
};
use serde_json::{
    from_slice,
    to_vec_pretty,
};
use tokio::fs::{
    self,
    OpenOptions,
    ReadDir,
};

use super::core::Path;

/// Trait for asynchronous file system operations.
///
/// This trait provides non-blocking file system operations similar to Python's pathlib.
/// It is implemented for `Path` but can be implemented for other types as well.
///
/// Requires the `async-fs-ops` feature to be enabled.
///
/// # Example
///
/// ```rust,ignore
/// use pathkit::{Path, AsyncFsOps};
///
/// let path = Path::new("/tmp/test.txt");
///
/// // Check if file exists
/// if path.exists().await? {
///     // Read file contents
///     let content = path.read().await?;
/// }
///
/// // Write to file
/// path.write(b"Hello, world!").await?;
///
/// // Get file size
/// let size = path.get_file_size().await?;
/// ```
#[async_trait::async_trait]
pub trait AsyncFsOps {
    #[cfg(unix)]
    async fn chmod(&self, mode: u32) -> Result<()>;
    #[cfg(unix)]
    async fn chown(&self, uid: Option<u32>, gid: Option<u32>) -> Result<()>;
    async fn copy_file(&self, dest: impl AsRef<Path> + Send) -> Result<u64>;
    async fn create_dir_all(&self) -> Result<()>;
    async fn create_dir(&self) -> Result<()>;
    async fn create_parent_dir_all(&self) -> Result<bool>;
    async fn create_parent_dir(&self) -> Result<bool>;
    async fn empty_dir(&self) -> Result<()>;
    async fn exists(&self) -> Result<bool>;
    async fn get_file_size(&self) -> Result<u64>;
    #[cfg(unix)]
    async fn is_block_device(&self) -> Result<bool>;
    #[cfg(unix)]
    async fn is_char_device(&self) -> Result<bool>;
    async fn is_dir(&self) -> Result<bool>;
    #[cfg(unix)]
    async fn is_fifo(&self) -> Result<bool>;
    async fn is_file(&self) -> Result<bool>;
    #[cfg(unix)]
    async fn is_socket(&self) -> Result<bool>;
    async fn is_symlink(&self) -> Result<bool>;
    async fn metadata(&self) -> Result<Metadata>;
    async fn read_dir(&self) -> Result<ReadDir>;
    async fn read_json<T: DeserializeOwned>(&self) -> Result<T>;
    async fn read(&self) -> Result<Vec<u8>>;
    async fn read_to_string(&self) -> Result<String>;
    async fn remove_dir_all(&self) -> Result<()>;
    async fn remove_dir(&self) -> Result<()>;
    async fn remove_file(&self) -> Result<()>;
    async fn set_permissions(&self, permissions: Permissions) -> Result<()>;
    async fn truncate(&self, len: Option<u64>) -> Result<()>;
    async fn write_json<T: Serialize + Send>(&self, data: T) -> Result<()>;
    async fn write(&self, contents: impl AsRef<[u8]> + Send) -> Result<()>;
}

#[async_trait::async_trait]
impl AsyncFsOps for Path {
    #[cfg(unix)]
    async fn chmod(&self, mode: u32) -> Result<()> {
        use std::os::unix::fs::PermissionsExt;

        Ok(fs::set_permissions(self, Permissions::from_mode(mode)).await?)
    }

    #[cfg(unix)]
    async fn chown(&self, uid: Option<u32>, gid: Option<u32>) -> Result<()> {
        use tokio::task::spawn_blocking;

        let path = self.clone();
        Ok(spawn_blocking(move || std::os::unix::fs::chown(path, uid, gid)).await??)
    }

    async fn copy_file(&self, dest: impl AsRef<Path> + Send) -> Result<u64> {
        Ok(fs::copy(self, dest.as_ref()).await?)
    }

    async fn create_dir(&self) -> Result<()> {
        Ok(fs::create_dir(self).await?)
    }

    async fn create_dir_all(&self) -> Result<()> {
        Ok(fs::create_dir_all(self).await?)
    }

    async fn create_parent_dir_all(&self) -> Result<bool> {
        if let Some(parent) = self.parent() {
            parent.create_dir_all().await?;
            return Ok(true);
        }

        Ok(false)
    }

    async fn create_parent_dir(&self) -> Result<bool> {
        if let Some(parent) = self.parent() {
            parent.create_dir().await?;
            return Ok(true);
        }

        Ok(false)
    }

    async fn empty_dir(&self) -> Result<()> {
        if !self.exists().await? {
            self.create_dir_all().await?;
        }

        let mut entries = fs::read_dir(self).await?;
        while let Some(entry) = entries.next_entry().await? {
            let entry_path = entry.path();
            if entry_path.is_dir() {
                fs::remove_dir_all(entry_path).await?;
            } else {
                fs::remove_file(entry_path).await?;
            }
        }

        Ok(())
    }

    async fn exists(&self) -> Result<bool> {
        Ok(fs::try_exists(self).await?)
    }

    async fn get_file_size(&self) -> Result<u64> {
        Ok(self.metadata().await?.len())
    }

    #[cfg(unix)]
    async fn is_block_device(&self) -> Result<bool> {
        use std::os::unix::fs::FileTypeExt;

        Ok(self.metadata().await?.file_type().is_block_device())
    }

    #[cfg(unix)]
    async fn is_char_device(&self) -> Result<bool> {
        use std::os::unix::fs::FileTypeExt;

        Ok(self.metadata().await?.file_type().is_char_device())
    }

    async fn is_dir(&self) -> Result<bool> {
        Ok(self.metadata().await?.is_dir())
    }

    #[cfg(unix)]
    async fn is_fifo(&self) -> Result<bool> {
        use std::os::unix::fs::FileTypeExt;

        Ok(self.metadata().await?.file_type().is_fifo())
    }

    async fn is_file(&self) -> Result<bool> {
        Ok(self.metadata().await?.is_file())
    }

    #[cfg(unix)]
    async fn is_socket(&self) -> Result<bool> {
        use std::os::unix::fs::FileTypeExt;

        Ok(self.metadata().await?.file_type().is_socket())
    }

    async fn is_symlink(&self) -> Result<bool> {
        Ok(fs::symlink_metadata(self).await?.file_type().is_symlink())
    }

    async fn metadata(&self) -> Result<Metadata> {
        Ok(fs::metadata(self).await?)
    }

    async fn read(&self) -> Result<Vec<u8>> {
        Ok(fs::read(self).await?)
    }

    async fn read_dir(&self) -> Result<ReadDir> {
        Ok(fs::read_dir(self).await?)
    }

    async fn read_json<T: DeserializeOwned>(&self) -> Result<T> {
        Ok(from_slice::<T>(&self.read().await?)?)
    }

    async fn read_to_string(&self) -> Result<String> {
        Ok(fs::read_to_string(self).await?)
    }

    async fn remove_dir(&self) -> Result<()> {
        Ok(fs::remove_dir(self).await?)
    }

    async fn remove_file(&self) -> Result<()> {
        Ok(fs::remove_file(self).await?)
    }

    async fn remove_dir_all(&self) -> Result<()> {
        Ok(fs::remove_dir_all(self).await?)
    }

    async fn set_permissions(&self, permissions: Permissions) -> Result<()> {
        Ok(fs::set_permissions(self, permissions).await?)
    }

    async fn truncate(&self, len: Option<u64>) -> Result<()> {
        Ok(OpenOptions::new()
            .write(true)
            .open(self)
            .await?
            .set_len(len.unwrap_or(0))
            .await?)
    }

    async fn write_json<T: Serialize + Send>(&self, data: T) -> Result<()> {
        self.write(to_vec_pretty(&data)?).await
    }

    async fn write(&self, contents: impl AsRef<[u8]> + Send) -> Result<()> {
        Ok(fs::write(self, contents).await?)
    }
}

#[cfg(test)]
mod tests {
    use serde::Deserialize;
    use tempfile::{
        tempdir,
        NamedTempFile,
    };
    use tokio::fs as async_fs;

    use super::*;

    // Test exists
    #[tokio::test]
    async fn test_exists() -> Result<()> {
        let temp_file = NamedTempFile::new()?;
        let file_path = Path::new(temp_file.path());

        assert!(file_path.exists().await?);
        Ok(())
    }

    #[tokio::test]
    async fn test_exists_false() -> Result<()> {
        let temp_dir = tempdir()?;
        let non_existent = temp_dir.path().join("non_existent_file.txt");
        let path = Path::new(&non_existent);

        assert!(!path.exists().await?);
        Ok(())
    }

    // Test is_file
    #[tokio::test]
    async fn test_is_file() -> Result<()> {
        let temp_file = NamedTempFile::new()?;
        let file_path = Path::new(temp_file.path());

        assert!(file_path.is_file().await?);
        Ok(())
    }

    #[tokio::test]
    async fn test_is_file_false() -> Result<()> {
        let temp_dir = tempdir()?;
        let dir_path = Path::new(temp_dir.path());

        assert!(!dir_path.is_file().await?);
        Ok(())
    }

    // Test is_dir
    #[tokio::test]
    async fn test_is_dir() -> Result<()> {
        let temp_dir = tempdir()?;
        let dir_path = Path::new(temp_dir.path());

        assert!(dir_path.is_dir().await?);
        Ok(())
    }

    #[tokio::test]
    async fn test_is_dir_false() -> Result<()> {
        let temp_file = NamedTempFile::new()?;
        let file_path = Path::new(temp_file.path());

        assert!(!file_path.is_dir().await?);
        Ok(())
    }

    // Test is_symlink
    #[cfg(unix)]
    #[tokio::test]
    async fn test_is_symlink() -> Result<()> {
        let temp_dir = tempdir()?;
        let target = temp_dir.path().join("target.txt");
        async_fs::write(&target, "test").await?;

        let link = temp_dir.path().join("link.txt");
        std::os::unix::fs::symlink(&target, &link)?;

        let link_path = Path::new(&link);
        assert!(link_path.is_symlink().await?);
        Ok(())
    }

    // Test metadata
    #[tokio::test]
    async fn test_metadata() -> Result<()> {
        let temp_file = NamedTempFile::new()?;
        let file_path = Path::new(temp_file.path());

        let metadata = file_path.metadata().await?;
        assert!(metadata.is_file());
        Ok(())
    }

    // Test read and write
    #[tokio::test]
    async fn test_read_write() -> Result<()> {
        let temp_file = NamedTempFile::new()?;
        let file_path = Path::new(temp_file.path());

        let test_content = b"Hello, World!";
        file_path.write(test_content).await?;

        let read_content = file_path.read().await?;
        assert_eq!(read_content, test_content);
        Ok(())
    }

    // Test read_to_string
    #[tokio::test]
    async fn test_read_to_string() -> Result<()> {
        let temp_file = NamedTempFile::new()?;
        let file_path = Path::new(temp_file.path());

        let test_content = "Hello, World!";
        file_path.write(test_content).await?;

        let read_content = file_path.read_to_string().await?;
        assert_eq!(read_content, test_content);
        Ok(())
    }

    // Test create_dir
    #[tokio::test]
    async fn test_create_dir() -> Result<()> {
        let temp_dir = tempdir()?;
        let new_dir = temp_dir.path().join("new_dir");
        let dir_path = Path::new(&new_dir);

        dir_path.create_dir().await?;

        assert!(dir_path.is_dir().await?);
        Ok(())
    }

    // Test create_dir_all
    #[tokio::test]
    async fn test_create_dir_all() -> Result<()> {
        let temp_dir = tempdir()?;
        let new_dir = temp_dir.path().join("parent/child/grandchild");
        let dir_path = Path::new(&new_dir);

        dir_path.create_dir_all().await?;

        assert!(dir_path.is_dir().await?);
        Ok(())
    }

    // Test remove_dir
    #[tokio::test]
    async fn test_remove_dir() -> Result<()> {
        let temp_dir = tempdir()?;
        let new_dir = temp_dir.path().join("to_remove");
        async_fs::create_dir(&new_dir).await?;
        let dir_path = Path::new(&new_dir);

        assert!(dir_path.exists().await?);
        dir_path.remove_dir().await?;
        assert!(!dir_path.exists().await?);
        Ok(())
    }

    // Test remove_file
    #[tokio::test]
    async fn test_remove_file() -> Result<()> {
        let temp_file = NamedTempFile::new()?;
        let file_path = Path::new(temp_file.path());

        assert!(file_path.exists().await?);
        file_path.remove_file().await?;
        assert!(!file_path.exists().await?);
        Ok(())
    }

    // Test remove_dir_all
    #[tokio::test]
    async fn test_remove_dir_all() -> Result<()> {
        let temp_dir = tempdir()?;
        let parent = temp_dir.path().join("parent");
        async_fs::create_dir(&parent).await?;
        async_fs::write(parent.join("file1.txt"), "content1").await?;
        async_fs::write(parent.join("file2.txt"), "content2").await?;

        let dir_path = Path::new(&parent);
        assert!(dir_path.exists().await?);
        dir_path.remove_dir_all().await?;
        assert!(!dir_path.exists().await?);
        Ok(())
    }

    // Test get_file_size
    #[tokio::test]
    async fn test_get_file_size() -> Result<()> {
        let temp_file = NamedTempFile::new()?;
        let file_path = Path::new(temp_file.path());

        let test_content = b"Hello, World!";
        file_path.write(test_content).await?;

        let size = file_path.get_file_size().await?;
        assert_eq!(size, test_content.len() as u64);
        Ok(())
    }

    // Test truncate
    #[tokio::test]
    async fn test_truncate() -> Result<()> {
        let temp_file = NamedTempFile::new()?;
        let file_path = Path::new(temp_file.path());

        let test_content = b"Hello, World!";
        file_path.write(test_content).await?;

        // Truncate to 5 bytes
        file_path.truncate(Some(5)).await?;

        let size = file_path.get_file_size().await?;
        assert_eq!(size, 5);
        Ok(())
    }

    // Test read_json and write_json
    #[tokio::test]
    async fn test_read_write_json() -> Result<()> {
        #[derive(Debug, Serialize, Deserialize, PartialEq)]
        struct TestData {
            name: String,
            value: i32,
        }

        let temp_file = NamedTempFile::new()?;
        let file_path = Path::new(temp_file.path());

        let original = TestData {
            name: "test".to_string(),
            value: 42,
        };

        file_path.write_json(&original).await?;

        let loaded: TestData = file_path.read_json().await?;
        assert_eq!(loaded, original);
        Ok(())
    }

    // Test read_dir
    #[tokio::test]
    async fn test_read_dir() -> Result<()> {
        let temp_dir = tempdir()?;
        async_fs::write(temp_dir.path().join("file1.txt"), "content1").await?;
        async_fs::write(temp_dir.path().join("file2.txt"), "content2").await?;
        async_fs::create_dir(temp_dir.path().join("subdir")).await?;

        let dir_path = Path::new(temp_dir.path());
        let mut entries = dir_path.read_dir().await?;
        let mut count = 0;
        while entries.next_entry().await?.is_some() {
            count += 1;
        }

        // Should have 3 entries: 2 files + 1 directory
        assert_eq!(count, 3);
        Ok(())
    }

    // Test empty_dir
    #[tokio::test]
    async fn test_empty_dir() -> Result<()> {
        let temp_dir = tempdir()?;
        async_fs::write(temp_dir.path().join("file1.txt"), "content1").await?;
        async_fs::write(temp_dir.path().join("file2.txt"), "content2").await?;
        async_fs::create_dir(temp_dir.path().join("subdir")).await?;

        let dir_path = Path::new(temp_dir.path());
        dir_path.empty_dir().await?;

        // Directory should be empty now
        let mut entries = dir_path.read_dir().await?;
        let mut count = 0;
        while entries.next_entry().await?.is_some() {
            count += 1;
        }

        assert_eq!(count, 0);
        Ok(())
    }

    // Test set_permissions
    #[cfg(unix)]
    #[tokio::test]
    async fn test_set_permissions() -> Result<()> {
        use std::{
            fs,
            os::unix::fs::PermissionsExt,
        };

        let temp_file = NamedTempFile::new()?;
        let file_path = Path::new(temp_file.path());

        // Read current permissions
        let metadata = fs::metadata(temp_file.path())?;
        let original_mode = metadata.permissions().mode();

        // Set new permissions
        file_path.set_permissions(fs::Permissions::from_mode(0o644)).await?;

        let new_metadata = fs::metadata(temp_file.path())?;
        assert_eq!(new_metadata.permissions().mode() & 0o777, 0o644);

        // Restore original
        file_path
            .set_permissions(fs::Permissions::from_mode(original_mode))
            .await?;
        Ok(())
    }

    // Test chmod
    #[cfg(unix)]
    #[tokio::test]
    async fn test_chmod() -> Result<()> {
        use std::{
            fs,
            os::unix::fs::PermissionsExt,
        };

        let temp_file = NamedTempFile::new()?;
        let file_path = Path::new(temp_file.path());

        file_path.chmod(0o744).await?;
        let metadata = fs::metadata(temp_file.path())?;
        assert_eq!(metadata.permissions().mode() & 0o777, 0o744);

        file_path.chmod(0o700).await?;
        let metadata = fs::metadata(temp_file.path())?;
        assert_eq!(metadata.permissions().mode() & 0o777, 0o700);

        Ok(())
    }

    // Test chown - requires root, skip if not root
    #[cfg(unix)]
    #[tokio::test]
    async fn test_chown() -> Result<()> {
        use std::{
            fs,
            os::unix::fs::PermissionsExt,
        };

        // Skip if not root (chown requires root privileges)
        if unsafe { libc::geteuid() } != 0 {
            return Ok(());
        }

        let temp_file = NamedTempFile::new()?;
        let file_path = Path::new(temp_file.path());

        // Get current uid/gid
        let metadata = fs::metadata(temp_file.path())?;
        let original_mode = metadata.permissions().mode();

        // chown to same uid/gid (no-op but should work)
        file_path.chown(Some(0), Some(0)).await?;

        // Restore permissions
        file_path
            .set_permissions(fs::Permissions::from_mode(original_mode))
            .await?;
        Ok(())
    }

    #[cfg(unix)]
    // Test is_block_device
    #[tokio::test]
    async fn test_is_block_device() -> Result<()> {
        let path = Path::new("/dev/sda"); // Common block device
        if path.exists().await? {
            // May fail if not root or device doesn't exist
            let _ = path.is_block_device().await;
        }
        Ok(())
    }

    #[cfg(unix)]
    // Test is_char_device
    #[tokio::test]
    async fn test_is_char_device() -> Result<()> {
        let path = Path::new("/dev/zero"); // Common char device
        if path.exists().await? {
            assert!(path.is_char_device().await?);
        }
        Ok(())
    }

    #[cfg(unix)]
    // Test is_fifo - simplified, skip creation
    #[tokio::test]
    async fn test_is_fifo() -> Result<()> {
        // FIFOs require special permissions to create
        // Just test that non-fifo returns false
        let path = Path::new("/tmp"); // This is not a fifo
        assert!(!path.is_fifo().await?);
        Ok(())
    }

    #[cfg(unix)]
    // Test is_socket - simplified
    #[tokio::test]
    async fn test_is_socket() -> Result<()> {
        // Unix socket files are tricky to create and test
        // Just test that non-socket returns false
        let path = Path::new("/tmp"); // This is not a socket
        assert!(!path.is_socket().await?);
        Ok(())
    }

    // Test copy_file
    #[tokio::test]
    async fn test_copy_file() -> Result<()> {
        let temp_src = NamedTempFile::new()?;
        let temp_dst = NamedTempFile::new()?;
        let src = Path::new(temp_src.path());
        let dst = Path::new(temp_dst.path());

        src.write(b"hello world").await?;

        let bytes = src.copy_file(&dst).await?;
        assert_eq!(bytes, 11);

        let content = dst.read().await?;
        assert_eq!(content, b"hello world");
        Ok(())
    }
}