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
pub use crate::fs::{GetPath, Metadata};

use anyhow::{Context as _, Result};
use fs2::FileExt as _;
use futures_lite::stream::StreamExt;
use std::{
    ffi::OsString,
    io,
    path::{Path, PathBuf},
    pin::{pin, Pin},
    task::{Context, Poll},
};
use tokio::io::{AsyncRead, AsyncSeek, AsyncWrite, ReadBuf};

impl<T> GetPath for tokio::io::BufReader<T>
where
    T: GetPath + AsyncRead,
{
    fn path(&self) -> &Path {
        self.get_ref().path()
    }
}

impl<T> GetPath for tokio::io::BufWriter<T>
where
    T: GetPath + AsyncWrite,
{
    fn path(&self) -> &Path {
        self.get_ref().path()
    }
}

impl<T> GetPath for tokio::io::BufStream<T>
where
    T: GetPath + AsyncRead + AsyncWrite,
{
    fn path(&self) -> &Path {
        self.get_ref().path()
    }
}

pub struct Fs;

impl Fs {
    #[allow(clippy::new_without_default)]
    pub fn new() -> Self {
        Self
    }
}

macro_rules! fs_trampoline {
    ($f:path, $p:ident) => {{
        let path = $p.as_ref();
        $f(path)
            .await
            .with_context(|| format!("{}(\"{}\")", stringify!($f), path.display()))
    }};
    ($f:path, $p1:ident, $p2:ident) => {{
        let path1 = $p1.as_ref();
        let path2 = $p2.as_ref();
        $f(path1, path2).await.with_context(|| {
            format!(
                "{}(\"{}\", \"{}\")",
                stringify!($f),
                path1.display(),
                path2.display()
            )
        })
    }};
}

macro_rules! fs_inner_trampoline {
    ($self:expr, $f:ident, $($args:tt),*) => {{
        $self
            .inner
            .$f($($args),*)
            .await
            .with_context(|| format!("{}(\"{}\")", stringify!($f), $self.path.display()))
    }};
    ($self:expr, $f:ident) => {
        fs_inner_trampoline!($self, $f, )
    };
}

pub struct ReadDir {
    inner: tokio::fs::ReadDir,
    path: PathBuf,
}

impl ReadDir {
    pub async fn next_entry(&mut self) -> Result<Option<DirEntry>> {
        let entry = self
            .inner
            .next_entry()
            .await
            .with_context(|| format!("read_dir(\"{}\")", self.path.display()))?;
        Ok(entry.map(|inner| DirEntry { inner }))
    }

    pub fn poll_next_entry(&mut self, cx: &mut Context<'_>) -> Poll<Result<Option<DirEntry>>> {
        self.inner.poll_next_entry(cx).map(|res| {
            res.with_context(|| format!("read_dir(\"{}\")", self.path.display()))
                .map(|inner_option| inner_option.map(|inner| DirEntry { inner }))
        })
    }
}

impl futures::Stream for ReadDir {
    type Item = Result<DirEntry>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        self.poll_next_entry(cx).map(Result::transpose)
    }
}

pub struct DirEntry {
    inner: tokio::fs::DirEntry,
}

impl DirEntry {
    pub fn path(&self) -> PathBuf {
        self.inner.path()
    }

    pub fn file_name(&self) -> OsString {
        self.inner.file_name()
    }

    pub async fn metadata(&self) -> Result<Metadata> {
        self.inner
            .metadata()
            .await
            .map(|inner| Metadata {
                inner,
                path: self.path(),
            })
            .with_context(|| format!("metadata(\"{}\")", self.path().display()))
    }

    pub async fn file_type(&self) -> Result<std::fs::FileType> {
        self.inner
            .file_type()
            .await
            .with_context(|| format!("file_type(\"{}\")", self.path().display()))
    }
}

fn is_not_found_err(err: &anyhow::Error) -> bool {
    let std_err = err.root_cause().downcast_ref::<std::io::Error>();
    matches!(std_err, Some(e) if e.kind() == std::io::ErrorKind::NotFound)
}

impl Fs {
    pub async fn create_dir<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        fs_trampoline!(tokio::fs::create_dir, path)
    }

    pub async fn create_dir_all<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        fs_trampoline!(tokio::fs::create_dir_all, path)
    }

    pub async fn metadata<P: AsRef<Path>>(&self, path: P) -> Result<Metadata> {
        fs_trampoline!(tokio::fs::metadata, path).map(|inner| Metadata {
            inner,
            path: path.as_ref().into(),
        })
    }

    pub async fn symlink_metadata<P: AsRef<Path>>(&self, path: P) -> Result<Metadata> {
        fs_trampoline!(tokio::fs::symlink_metadata, path).map(|inner| Metadata {
            inner,
            path: path.as_ref().into(),
        })
    }

    pub async fn rename<P: AsRef<Path>, Q: AsRef<Path>>(&self, from: P, to: Q) -> Result<()> {
        fs_trampoline!(tokio::fs::rename, from, to)
    }

    pub async fn copy<P: AsRef<Path>, Q: AsRef<Path>>(&self, from: P, to: Q) -> Result<u64> {
        fs_trampoline!(tokio::fs::copy, from, to)
    }

    pub async fn remove_dir<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        fs_trampoline!(tokio::fs::remove_dir, path)
    }

    pub async fn remove_dir_all<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        fs_trampoline!(tokio::fs::remove_dir_all, path)
    }

    pub async fn remove_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        fs_trampoline!(tokio::fs::remove_file, path)
    }

    pub async fn write<P: AsRef<Path>, C: AsRef<[u8]>>(&self, path: P, contents: C) -> Result<()> {
        let path = path.as_ref();
        tokio::fs::write(path, contents)
            .await
            .with_context(|| format!("write(\"{}\")", path.display()))
    }

    pub async fn read<P: AsRef<Path>>(&self, path: P) -> Result<Vec<u8>> {
        fs_trampoline!(tokio::fs::read, path)
    }

    pub async fn read_to_string<P: AsRef<Path>>(&self, path: P) -> Result<String> {
        fs_trampoline!(tokio::fs::read_to_string, path)
    }

    pub async fn read_to_string_if_exists<P: AsRef<Path>>(
        &self,
        path: P,
    ) -> Result<Option<String>> {
        match fs_trampoline!(tokio::fs::read_to_string, path) {
            Ok(contents) => Ok(Some(contents)),
            Err(err) if is_not_found_err(&err) => Ok(None),
            Err(err) => Err(err),
        }
    }

    pub async fn read_link<P: AsRef<Path>>(&self, path: P) -> Result<PathBuf> {
        fs_trampoline!(tokio::fs::read_link, path)
    }

    pub async fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(
        &self,
        original: P,
        link: Q,
    ) -> Result<()> {
        fs_trampoline!(tokio::fs::hard_link, original, link)
    }

    pub async fn open_file<P: AsRef<Path>>(&self, path: P) -> Result<File> {
        let path = path.as_ref();
        Ok(File {
            inner: tokio::fs::File::open(path)
                .await
                .with_context(|| format!("open(\"{}\")", path.display()))?,
            path: path.into(),
        })
    }

    pub async fn open_or_create_file<P: AsRef<Path>>(&self, path: P) -> Result<File> {
        let path = path.as_ref();
        Ok(File {
            inner: tokio::fs::OpenOptions::new()
                .read(true)
                .write(true)
                .create(true)
                .truncate(false)
                .open(path)
                .await
                .with_context(|| format!("open_or_create_file(\"{}\")", path.display()))?,
            path: path.into(),
        })
    }

    pub async fn open_or_create_file_append<P: AsRef<Path>>(&self, path: P) -> Result<File> {
        let path = path.as_ref();
        Ok(File {
            inner: tokio::fs::OpenOptions::new()
                .append(true)
                .create(true)
                .open(path)
                .await
                .with_context(|| format!("open_or_create_file_append(\"{}\")", path.display()))?,
            path: path.into(),
        })
    }

    pub async fn create_file<P: AsRef<Path>>(&self, path: P) -> Result<File> {
        let path = path.as_ref();
        Ok(File {
            inner: tokio::fs::File::create(path)
                .await
                .with_context(|| format!("create_file(\"{}\")", path.display()))?,
            path: path.into(),
        })
    }

    pub async fn create_file_read_write<P: AsRef<Path>>(&self, path: P) -> Result<File> {
        let path = path.as_ref();
        Ok(File {
            inner: tokio::fs::File::options()
                .create_new(true)
                .read(true)
                .write(true)
                .open(path)
                .await
                .with_context(|| format!("create_file_read_write(\"{}\")", path.display()))?,
            path: path.into(),
        })
    }

    pub async fn open_or_create_file_read_write<P: AsRef<Path>>(&self, path: P) -> Result<File> {
        let path = path.as_ref();
        Ok(File {
            inner: tokio::fs::File::options()
                .create(true)
                .read(true)
                .write(true)
                .truncate(false)
                .open(path)
                .await
                .with_context(|| {
                    format!("open_or_create_file_read_write(\"{}\")", path.display())
                })?,
            path: path.into(),
        })
    }

    pub async fn canonicalize<P: AsRef<Path>>(&self, path: P) -> Result<PathBuf> {
        fs_trampoline!(tokio::fs::canonicalize, path)
    }

    pub async fn exists<P: AsRef<Path>>(&self, path: P) -> bool {
        let path = path.as_ref().to_owned();
        tokio::task::spawn_blocking(move || path.exists())
            .await
            .unwrap()
    }

    pub async fn read_dir<P: AsRef<Path>>(&self, path: P) -> Result<ReadDir> {
        fs_trampoline!(tokio::fs::read_dir, path).map(|inner| ReadDir {
            inner,
            path: path.as_ref().into(),
        })
    }

    pub fn glob_walk<'fs, 'glob, P: AsRef<Path>>(
        &'fs self,
        path: P,
        glob: &'glob globset::GlobSet,
    ) -> GlobWalker<'fs, 'glob> {
        GlobWalker::new(self, path.as_ref(), glob)
    }
}

pub struct GlobWalker<'fs, 'glob> {
    start_path: PathBuf,
    fs_walker: async_walkdir::WalkDir,
    glob: &'glob globset::GlobSet,
    _fs: &'fs Fs,
}

impl<'fs, 'glob> GlobWalker<'fs, 'glob> {
    fn new(fs: &'fs Fs, path: &Path, glob: &'glob globset::GlobSet) -> Self {
        Self {
            start_path: path.to_owned(),
            fs_walker: async_walkdir::WalkDir::new(path),
            glob,
            _fs: fs,
        }
    }

    fn matches(&self, path: &Path) -> bool {
        self.glob.is_match_candidate(&globset::Candidate::new(
            path.strip_prefix(&self.start_path).unwrap(),
        ))
    }

    pub async fn next(&mut self) -> Result<Option<PathBuf>> {
        loop {
            match self.fs_walker.next().await {
                Some(Ok(entry)) if self.matches(&entry.path()) => return Ok(Some(entry.path())),
                Some(Err(e)) => return Err(e.into()),
                None => return Ok(None),
                _ => continue,
            }
        }
    }

    pub fn as_stream<'a>(&'a mut self) -> impl futures::Stream<Item = Result<PathBuf>> + 'a
    where
        'a: 'glob,
        'a: 'fs,
    {
        futures::stream::unfold(self, |self_| async {
            self_.next().await.transpose().map(|v| (v, self_))
        })
    }
}

#[cfg(test)]
async fn glob_walker_test(glob: &str, input: Vec<&str>, expected: Vec<&str>) {
    use globset::{Glob, GlobSet};

    let temp_dir = tempfile::tempdir().unwrap();
    let fs = Fs::new();
    for p in input {
        let path = temp_dir.path().join(p);
        fs.create_dir_all(path.parent().unwrap()).await.unwrap();
        fs.write(path, b"").await.unwrap();
    }

    let mut builder = GlobSet::builder();
    builder.add(Glob::new(glob).unwrap());
    let glob = builder.build().unwrap();

    let mut paths = vec![];
    let mut entries = fs.glob_walk(temp_dir.path(), &glob);
    while let Some(e) = entries.next().await.unwrap() {
        paths.push(e);
    }

    let expected: Vec<_> = expected
        .into_iter()
        .map(|e| temp_dir.path().join(e))
        .collect();
    assert_eq!(paths, expected);
}

#[tokio::test]
async fn glob_walker_basic() {
    glob_walker_test("*.txt", vec!["a.txt", "b.bin"], vec!["a.txt"]).await;
    glob_walker_test("foo/*", vec!["foo/a", "bar/b"], vec!["foo/a"]).await;
    glob_walker_test(
        "foo/**",
        vec!["foo/bar/baz", "bar/b"],
        vec!["foo/bar", "foo/bar/baz"],
    )
    .await;
}

#[cfg(unix)]
impl Fs {
    pub async fn symlink<P: AsRef<Path>, Q: AsRef<Path>>(
        &self,
        original: P,
        link: Q,
    ) -> Result<()> {
        fs_trampoline!(tokio::fs::symlink, original, link)
    }
}

pub struct File {
    inner: tokio::fs::File,
    path: PathBuf,
}

impl GetPath for File {
    fn path(&self) -> &Path {
        self.path()
    }
}

impl File {
    pub fn path(&self) -> &Path {
        &self.path
    }

    pub fn into_inner(self) -> tokio::fs::File {
        self.inner
    }

    pub async fn into_std(self) -> std::fs::File {
        self.inner.into_std().await
    }

    pub async fn try_clone(&self) -> Result<Self> {
        Ok(Self {
            inner: self.inner.try_clone().await?,
            path: self.path.clone(),
        })
    }

    pub async fn set_len(&self, size: u64) -> Result<()> {
        fs_inner_trampoline!(self, set_len, size)
    }

    pub async fn metadata(&self) -> Result<Metadata> {
        fs_inner_trampoline!(self, metadata).map(|inner| Metadata {
            inner,
            path: self.path.clone(),
        })
    }

    pub async fn set_permissions(&self, perm: std::fs::Permissions) -> Result<()> {
        fs_inner_trampoline!(self, set_permissions, perm)
    }

    pub async fn lock_shared(&self) -> Result<()> {
        let f = self.inner.try_clone().await?;
        let std_f = f.into_std().await;
        tokio::task::spawn_blocking(move || std_f.lock_shared())
            .await?
            .with_context(|| format!("lock_shared(\"{}\")", self.path.display()))
    }

    pub async fn lock_exclusive(&self) -> Result<()> {
        let f = self.inner.try_clone().await?;
        let std_f = f.into_std().await;
        tokio::task::spawn_blocking(move || std_f.lock_exclusive())
            .await?
            .with_context(|| format!("lock_exclusive(\"{}\")", self.path.display()))
    }

    pub async fn try_lock_shared(&self) -> Result<()> {
        let f = self.inner.try_clone().await?;
        let std_f = f.into_std().await;
        std_f
            .try_lock_shared()
            .with_context(|| format!("try_lock_shared(\"{}\")", self.path.display()))
    }

    pub async fn try_lock_exclusive(&self) -> Result<()> {
        let f = self.inner.try_clone().await?;
        let std_f = f.into_std().await;
        std_f
            .try_lock_exclusive()
            .with_context(|| format!("try_lock_exclusive(\"{}\")", self.path.display()))
    }

    pub async fn unlock(&self) -> Result<()> {
        let f = self.inner.try_clone().await?;
        let std_f = f.into_std().await;
        tokio::task::spawn_blocking(move || std_f.unlock())
            .await?
            .with_context(|| format!("unlock(\"{}\")", self.path.display()))
    }
}

impl AsyncRead for File {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        dst: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        let me = self.get_mut();
        AsyncRead::poll_read(pin!(&mut me.inner), cx, dst)
    }
}

impl AsyncWrite for File {
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        src: &[u8],
    ) -> Poll<io::Result<usize>> {
        let me = self.get_mut();
        AsyncWrite::poll_write(pin!(&mut me.inner), cx, src)
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
        let me = self.get_mut();
        AsyncWrite::poll_flush(pin!(&mut me.inner), cx)
    }

    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
        let me = self.get_mut();
        AsyncWrite::poll_shutdown(pin!(&mut me.inner), cx)
    }
}

impl AsyncSeek for File {
    fn start_seek(self: Pin<&mut Self>, pos: io::SeekFrom) -> io::Result<()> {
        let me = self.get_mut();
        AsyncSeek::start_seek(pin!(&mut me.inner), pos)
    }

    fn poll_complete(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<u64>> {
        let me = self.get_mut();
        AsyncSeek::poll_complete(pin!(&mut me.inner), cx)
    }
}