dir-structure 0.3.0

Model directory structures as plain Rust structs.
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
//! Tokio file system virtual file system implementation.

use std::fs as std_fs;
use std::io;
use std::io::SeekFrom;
use std::path::Path;
use std::path::PathBuf;
use std::pin::Pin;
use std::task::Context;
use std::task::Poll;

use futures::AsyncBufRead as FuturesBufRead;
use futures::Stream;
use futures::io::AsyncRead as FuturesAsyncRead;
use futures::io::AsyncSeek as FuturesAsyncSeek;
use futures::io::AsyncWrite as FuturesAsyncWrite;
use pin_project::pin_project;
use tokio::fs;
use tokio::io::AsyncBufRead;
use tokio::io::AsyncRead;
use tokio::io::AsyncSeek;
use tokio::io::AsyncWrite;
use tokio::io::BufReader;
use tokio::io::BufWriter;
use tokio::io::ReadBuf;

use crate::traits::async_vfs::CreateParentDirDefaultFuture;
use crate::traits::async_vfs::IoErrorWrapperFuture;
use crate::traits::async_vfs::VfsAsync;
use crate::traits::async_vfs::WriteSupportingVfsAsync;
use crate::traits::vfs::PathType;
use crate::traits::vfs::VfsCore;

/// A [`VfsAsync`] and [`WriteSupportingVfsAsync`] implementation using [`tokio::fs`].
pub struct TokioFsVfs;

/// Adapter to convert a type implementing [`tokio::io`] traits to one implementing
/// [`futures::io`] traits.
#[pin_project]
pub struct TokioAsyncAdapter<T>(#[pin] T, Option<SeekFrom>);

impl<R: AsyncRead> FuturesAsyncRead for TokioAsyncAdapter<R> {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut [u8],
    ) -> Poll<io::Result<usize>> {
        let mut rbuf = ReadBuf::new(buf);
        let this = self.project();
        *this.1 = None;
        match this.0.poll_read(cx, &mut rbuf) {
            Poll::Ready(Ok(())) => Poll::Ready(Ok(rbuf.filled().len())),
            Poll::Ready(Err(e)) => Poll::Ready(Err(e)),
            Poll::Pending => Poll::Pending,
        }
    }
}

impl<R: AsyncBufRead> FuturesBufRead for TokioAsyncAdapter<R> {
    fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<&[u8]>> {
        let this = self.project();
        *this.1 = None;
        this.0.poll_fill_buf(cx)
    }

    fn consume(self: Pin<&mut Self>, amt: usize) {
        let this = self.project();
        *this.1 = None;
        this.0.consume(amt)
    }
}

impl<T: AsyncSeek> FuturesAsyncSeek for TokioAsyncAdapter<T> {
    fn poll_seek(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        pos: io::SeekFrom,
    ) -> Poll<io::Result<u64>> {
        let mut this = self.project();
        if *this.1 != Some(pos) {
            *this.1 = Some(pos);
            match this.0.as_mut().start_seek(pos) {
                Ok(()) => {}
                Err(e) => {
                    *this.1 = None;
                    return Poll::Ready(Err(e));
                }
            }
        }

        match this.0.poll_complete(cx) {
            Poll::Ready(Ok(v)) => {
                *this.1 = None;
                Poll::Ready(Ok(v))
            }
            Poll::Ready(Err(e)) => {
                *this.1 = None;
                Poll::Ready(Err(e))
            }
            Poll::Pending => Poll::Pending,
        }
    }
}

impl<T: AsyncWrite> FuturesAsyncWrite for TokioAsyncAdapter<T> {
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        let this = self.project();
        *this.1 = None;
        this.0.poll_write(cx, buf)
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        let this = self.project();
        *this.1 = None;
        this.0.poll_flush(cx)
    }

    fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        let this = self.project();
        *this.1 = None;
        this.0.poll_shutdown(cx)
    }
}

impl VfsCore for TokioFsVfs {
    type Path = Path;
}

impl VfsAsync for TokioFsVfs {
    type RFile = TokioAsyncAdapter<BufReader<fs::File>>;
    type OpenReadFuture = IoErrorWrapperFuture<
        Self::RFile,
        Pin<Box<dyn Future<Output = io::Result<Self::RFile>> + Send>>,
        <<Self as VfsCore>::Path as PathType>::OwnedPath,
    >;

    fn open_read(self: Pin<&Self>, path: PathBuf) -> Self::OpenReadFuture {
        IoErrorWrapperFuture::new(
            path.clone(),
            Box::pin(async move {
                fs::File::open(path)
                    .await
                    .map(|f| TokioAsyncAdapter(BufReader::new(f), None))
            }),
        )
    }

    type ReadFuture<'a>
        = IoErrorWrapperFuture<
        Vec<u8>,
        Pin<Box<dyn Future<Output = io::Result<Vec<u8>>> + Send + 'a>>,
        <<Self as VfsCore>::Path as PathType>::OwnedPath,
    >
    where
        Self: 'a;

    fn read<'a>(self: Pin<&'a Self>, path: PathBuf) -> Self::ReadFuture<'a> {
        IoErrorWrapperFuture::new(path.clone(), Box::pin(fs::read(path)))
    }

    type ReadStringFuture<'a>
        = IoErrorWrapperFuture<
        String,
        Pin<Box<dyn Future<Output = io::Result<String>> + Send + 'a>>,
        <<Self as VfsCore>::Path as PathType>::OwnedPath,
    >
    where
        Self: 'a;

    fn read_string<'a>(
        self: Pin<&'a Self>,
        path: <<Self as VfsCore>::Path as PathType>::OwnedPath,
    ) -> Self::ReadStringFuture<'a> {
        IoErrorWrapperFuture::new(path.clone(), Box::pin(fs::read_to_string(path)))
    }

    type ExistsFuture<'a>
        = IoErrorWrapperFuture<
        bool,
        Pin<Box<dyn Future<Output = io::Result<bool>> + Send + 'a>>,
        <<Self as VfsCore>::Path as PathType>::OwnedPath,
    >
    where
        Self: 'a;

    fn exists<'a>(
        self: Pin<&'a Self>,
        path: <<Self as VfsCore>::Path as PathType>::OwnedPath,
    ) -> Self::ExistsFuture<'a> {
        IoErrorWrapperFuture::new(path.clone(), Box::pin(fs::try_exists(path)))
    }

    type IsDirFuture<'a>
        = IoErrorWrapperFuture<
        bool,
        Pin<Box<dyn Future<Output = io::Result<bool>> + Send + 'a>>,
        <<Self as VfsCore>::Path as PathType>::OwnedPath,
    >
    where
        Self: 'a;

    fn is_dir<'a>(
        self: Pin<&'a Self>,
        path: <<Self as VfsCore>::Path as PathType>::OwnedPath,
    ) -> Self::IsDirFuture<'a> {
        IoErrorWrapperFuture::new(
            path.clone(),
            Box::pin(async move { fs::metadata(path).await.map(|m| m.is_dir()) }),
        )
    }

    type DirWalk<'a>
        = imp::DirWalker
    where
        Self: 'a;

    type DirWalkFuture<'a>
        = IoErrorWrapperFuture<
        Self::DirWalk<'a>,
        Pin<Box<dyn Future<Output = io::Result<Self::DirWalk<'a>>> + Send + 'a>>,
        <<Self as VfsCore>::Path as PathType>::OwnedPath,
    >
    where
        Self: 'a;

    fn walk_dir<'a>(self: Pin<&'a Self>, path: PathBuf) -> Self::DirWalkFuture<'a> {
        IoErrorWrapperFuture::new(
            path.clone(),
            Box::pin(async move {
                fs::read_dir(path.clone())
                    .await
                    .map(|inner| imp::DirWalker {
                        inner,
                        path,
                        current_kind_future: None,
                    })
            }),
        )
    }
}

impl WriteSupportingVfsAsync for TokioFsVfs {
    type WFile = TokioAsyncAdapter<BufWriter<fs::File>>;
    type OpenWriteFuture = IoErrorWrapperFuture<
        Self::WFile,
        Pin<Box<dyn Future<Output = io::Result<Self::WFile>> + Send>>,
        <<Self as VfsCore>::Path as PathType>::OwnedPath,
    >;
    fn open_write(
        self: Pin<&Self>,
        path: <<Self as VfsCore>::Path as PathType>::OwnedPath,
    ) -> Self::OpenWriteFuture {
        IoErrorWrapperFuture::new(
            path.clone(),
            Box::pin(async move {
                fs::File::create(path)
                    .await
                    .map(|f| TokioAsyncAdapter(BufWriter::new(f), None))
            }),
        )
    }

    type WriteFuture<'a>
        = IoErrorWrapperFuture<
        (),
        Pin<Box<dyn Future<Output = io::Result<()>> + Send + 'a>>,
        <<Self as VfsCore>::Path as PathType>::OwnedPath,
    >
    where
        Self: 'a;

    fn write<'d, 'a: 'd>(
        self: Pin<&'a Self>,
        path: <<Self as VfsCore>::Path as PathType>::OwnedPath,
        data: &'d [u8],
    ) -> Self::WriteFuture<'d> {
        IoErrorWrapperFuture::new(path.clone(), Box::pin(fs::write(path, data)))
    }

    type RemoveDirAllFuture<'a>
        = IoErrorWrapperFuture<
        (),
        Pin<Box<dyn Future<Output = io::Result<()>> + Send + 'a>>,
        <<Self as VfsCore>::Path as PathType>::OwnedPath,
    >
    where
        Self: 'a;

    fn remove_dir_all<'a>(self: Pin<&'a Self>, path: PathBuf) -> Self::RemoveDirAllFuture<'a> {
        IoErrorWrapperFuture::new(path.clone(), Box::pin(fs::remove_dir_all(path)))
    }

    type CreateDirFuture<'a>
        = IoErrorWrapperFuture<
        (),
        Pin<Box<dyn Future<Output = io::Result<()>> + Send + 'a>>,
        <<Self as VfsCore>::Path as PathType>::OwnedPath,
    >
    where
        Self: 'a;

    fn create_dir<'a>(self: Pin<&'a Self>, path: PathBuf) -> Self::CreateDirFuture<'a> {
        IoErrorWrapperFuture::new(path.clone(), Box::pin(fs::create_dir(path)))
    }

    type CreateDirAllFuture<'a>
        = IoErrorWrapperFuture<
        (),
        Pin<Box<dyn Future<Output = io::Result<()>> + Send + 'a>>,
        <<Self as VfsCore>::Path as PathType>::OwnedPath,
    >
    where
        Self: 'a;

    fn create_dir_all<'a>(self: Pin<&'a Self>, path: PathBuf) -> Self::CreateDirAllFuture<'a> {
        IoErrorWrapperFuture::new(path.clone(), Box::pin(fs::create_dir_all(path)))
    }

    type CreateParentDirFuture<'a>
        = CreateParentDirDefaultFuture<'a, Self>
    where
        Self: 'a;

    fn create_parent_dir<'a>(
        self: Pin<&'a Self>,
        path: PathBuf,
    ) -> Self::CreateParentDirFuture<'a> {
        let parent = path
            .parent()
            .map_or_else(|| path.join(".."), |p| p.to_path_buf());
        CreateParentDirDefaultFuture::Start {
            vfs: self,
            path: parent,
        }
    }
}

mod imp {
    use std::ffi::OsString;
    use std::path::Path;
    use std::task::Context;

    use futures::FutureExt;

    use super::*;
    use crate::error::Error;
    use crate::error::Result;
    use crate::traits::vfs::DirEntryInfo;
    use crate::traits::vfs::DirEntryKind;

    /// Directory walker for asynchronous file system operations on [`tokio::fs`].
    pub struct DirWalker {
        pub(super) inner: fs::ReadDir,
        pub(super) path: PathBuf,

        pub(super) current_kind_future: Option<(
            OsString,
            PathBuf,
            Pin<Box<dyn Future<Output = io::Result<std_fs::FileType>> + Send>>,
        )>,
    }

    impl Stream for DirWalker {
        type Item = Result<DirEntryInfo<Path>, PathBuf>;

        fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
            if let Some((name, path, fut)) = self.current_kind_future.as_mut() {
                match fut.poll_unpin(cx) {
                    Poll::Ready(Ok(kind)) => {
                        let name = name.clone();
                        let path = path.clone();
                        self.current_kind_future = None;
                        let kind = if kind.is_dir() {
                            DirEntryKind::Directory
                        } else {
                            DirEntryKind::File
                        };
                        return Poll::Ready(Some(Ok(DirEntryInfo { name, path, kind })));
                    }
                    Poll::Ready(Err(e)) => {
                        let path = self.path.clone();
                        self.current_kind_future = None;
                        return Poll::Ready(Some(Err(Error::Io(path.clone(), e))));
                    }
                    Poll::Pending => return Poll::Pending,
                }
            }
            match self.inner.poll_next_entry(cx) {
                Poll::Ready(Ok(Some(v))) => {
                    let name = v.file_name();
                    let path = v.path();
                    let fut = Box::pin(async move { v.file_type().await });
                    self.current_kind_future = Some((name, path, fut));
                    cx.waker().wake_by_ref();
                    Poll::Pending
                }
                Poll::Ready(Ok(None)) => Poll::Ready(None),
                Poll::Ready(Err(e)) => Poll::Ready(Some(Err(Error::Io(self.path.clone(), e)))),
                Poll::Pending => Poll::Pending,
            }
        }
    }
}