io-vdir 0.1.0

Vdir client library for Rust
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
//! Standard, blocking Vdir client driving any coroutine against
//! [`std::fs`].
//!
//! Holds a single filesystem root and exposes one method per common
//! coroutine. Every method runs its coroutine to completion through
//! [`VdirClient::run`] by servicing each [`VdirYield`] request via
//! [`std::fs`].

use alloc::{
    collections::{BTreeMap, BTreeSet},
    string::{String, ToString},
    vec::Vec,
};

use std::{fs, io};

use getrandom::fill;
use log::trace;
use thiserror::Error;

use crate::{
    collection::{VdirCollection, create::*, delete::*, list::*, rename::*, update::*},
    coroutine::*,
    item::{
        VdirItem, VdirItemKind, copy::*, delete::*, get::*, list::*, locate::*, r#move::*, store::*,
    },
    path::VdirPath,
};

/// Errors returned by the [`VdirClient`] helpers.
#[derive(Debug, Error)]
pub enum VdirClientError {
    /// A collection create coroutine failed.
    #[error(transparent)]
    VdirCollectionCreate(#[from] VdirCollectionCreateError),
    /// A collection delete coroutine failed.
    #[error(transparent)]
    VdirCollectionDelete(#[from] VdirCollectionDeleteError),
    /// A collection list coroutine failed.
    #[error(transparent)]
    VdirCollectionList(#[from] VdirCollectionListError),
    /// A collection rename coroutine failed.
    #[error(transparent)]
    VdirCollectionRename(#[from] VdirCollectionRenameError),
    /// A collection update coroutine failed.
    #[error(transparent)]
    VdirCollectionUpdate(#[from] VdirCollectionUpdateError),
    /// An item locate coroutine failed.
    #[error(transparent)]
    VdirItemLocate(#[from] VdirItemLocateError),
    /// An item get coroutine failed.
    #[error(transparent)]
    VdirItemGet(#[from] VdirItemGetError),
    /// An item list coroutine failed.
    #[error(transparent)]
    VdirItemList(#[from] VdirItemListError),
    /// An item store coroutine failed.
    #[error(transparent)]
    VdirItemStore(#[from] VdirItemStoreError),
    /// An item copy coroutine failed.
    #[error(transparent)]
    VdirItemCopy(#[from] VdirItemCopyError),
    /// An item move coroutine failed.
    #[error(transparent)]
    VdirItemMove(#[from] VdirItemMoveError),
    /// An item delete coroutine failed.
    #[error(transparent)]
    VdirItemDelete(#[from] VdirItemDeleteError),
    /// A filesystem operation failed while servicing a coroutine
    /// request.
    #[error(transparent)]
    Io(#[from] io::Error),
    /// The system entropy source failed while minting a new item id.
    #[error("Failed to gather randomness for new item id: {0}")]
    Random(getrandom::Error),
}

/// Std-blocking Vdir client wrapping a filesystem root.
#[derive(Debug)]
pub struct VdirClient {
    root: VdirPath,
}

impl VdirClient {
    /// Builds a client rooted at `root`. No filesystem check is
    /// performed at construction time.
    pub fn new(root: impl Into<VdirPath>) -> Self {
        Self { root: root.into() }
    }

    /// Returns the filesystem root this client operates on.
    pub fn root(&self) -> &VdirPath {
        &self.root
    }

    /// Drives any standard-shape coroutine (`Yield = VdirYield`,
    /// `Return = Result<Output, Error>`) against the local filesystem
    /// until it terminates.
    pub fn run<C, T, E>(&self, mut coroutine: C) -> Result<T, VdirClientError>
    where
        C: VdirCoroutine<Yield = VdirYield, Return = Result<T, E>>,
        VdirClientError: From<E>,
    {
        let mut arg: Option<VdirReply> = None;

        loop {
            match coroutine.resume(arg.take()) {
                VdirCoroutineState::Complete(Ok(out)) => return Ok(out),
                VdirCoroutineState::Complete(Err(err)) => return Err(err.into()),
                VdirCoroutineState::Yielded(VdirYield::WantsRandom { len }) => {
                    let mut bytes = vec![0u8; len];
                    fill(&mut bytes).map_err(VdirClientError::Random)?;
                    arg = Some(VdirReply::Random(bytes));
                }
                VdirCoroutineState::Yielded(VdirYield::WantsFileExists(paths)) => {
                    arg = Some(VdirReply::FileExists(file_exists(paths)));
                }
                VdirCoroutineState::Yielded(VdirYield::WantsDirExists(paths)) => {
                    arg = Some(VdirReply::DirExists(dir_exists(paths)));
                }
                VdirCoroutineState::Yielded(VdirYield::WantsDirRead(paths)) => {
                    arg = Some(VdirReply::DirRead(read_dirs(paths)?));
                }
                VdirCoroutineState::Yielded(VdirYield::WantsFileRead(paths)) => {
                    arg = Some(VdirReply::FileRead(read_files(paths)?));
                }
                VdirCoroutineState::Yielded(VdirYield::WantsFileCreate(files)) => {
                    write_files(files)?;
                    arg = Some(VdirReply::FileCreate);
                }
                VdirCoroutineState::Yielded(VdirYield::WantsDirCreate(paths)) => {
                    create_dirs(paths)?;
                    arg = Some(VdirReply::DirCreate);
                }
                VdirCoroutineState::Yielded(VdirYield::WantsDirRemove(paths)) => {
                    remove_dirs(paths)?;
                    arg = Some(VdirReply::DirRemove);
                }
                VdirCoroutineState::Yielded(VdirYield::WantsFileRemove(paths)) => {
                    remove_files(paths)?;
                    arg = Some(VdirReply::FileRemove);
                }
                VdirCoroutineState::Yielded(VdirYield::WantsRename(pairs)) => {
                    rename_paths(pairs)?;
                    arg = Some(VdirReply::Rename);
                }
                VdirCoroutineState::Yielded(VdirYield::WantsCopy(pairs)) => {
                    copy_paths(pairs)?;
                    arg = Some(VdirReply::Copy);
                }
            }
        }
    }

    /// Runs [`VdirCollectionCreate`]: creates the collection directory and
    /// writes its metadata files when present.
    pub fn create_collection(&self, collection: VdirCollection) -> Result<(), VdirClientError> {
        self.run(VdirCollectionCreate::new(
            collection,
            VdirCollectionCreateOptions::default(),
        ))
    }

    /// Runs [`VdirCollectionDelete`]: recursively removes the collection
    /// rooted at `path`.
    pub fn delete_collection(&self, path: impl Into<VdirPath>) -> Result<(), VdirClientError> {
        self.run(VdirCollectionDelete::new(
            path,
            VdirCollectionDeleteOptions::default(),
        ))
    }

    /// Runs [`VdirCollectionList`]: enumerates every collection directly
    /// under [`self.root`](Self::root).
    pub fn list_collections(&self) -> Result<BTreeSet<VdirCollection>, VdirClientError> {
        self.run(VdirCollectionList::new(
            self.root.clone(),
            VdirCollectionListOptions::default(),
        ))
    }

    /// Runs [`VdirCollectionRename`]: renames the collection at `path` to
    /// `name` (keeping the same parent directory).
    pub fn rename_collection(
        &self,
        path: impl Into<VdirPath>,
        name: impl ToString,
    ) -> Result<(), VdirClientError> {
        self.run(VdirCollectionRename::new(
            path,
            name,
            VdirCollectionRenameOptions::default(),
        ))
    }

    /// Runs [`VdirCollectionUpdate`]: atomically rewrites the metadata of
    /// `collection`.
    pub fn update_collection(&self, collection: VdirCollection) -> Result<(), VdirClientError> {
        self.run(VdirCollectionUpdate::new(
            collection,
            VdirCollectionUpdateOptions::default(),
        ))
    }

    /// Runs [`VdirItemLocate`]: finds the on-disk path of item `id` inside
    /// `collection`.
    pub fn locate_item(
        &self,
        collection: impl Into<VdirPath>,
        id: impl ToString,
    ) -> Result<(VdirPath, VdirItemKind), VdirClientError> {
        let VdirItemLocateOutput { path, kind } = self.run(VdirItemLocate::new(
            collection,
            id,
            VdirItemLocateOptions::default(),
        ))?;
        Ok((path, kind))
    }

    /// Runs [`VdirItemGet`]: locates item `id` in `collection` and reads
    /// its contents from disk.
    pub fn get_item(
        &self,
        collection: impl Into<VdirPath>,
        id: impl ToString,
    ) -> Result<VdirItem, VdirClientError> {
        self.run(VdirItemGet::new(
            collection,
            id,
            VdirItemGetOptions::default(),
        ))
    }

    /// Runs [`VdirItemList`]: scans `collection` and returns every
    /// `.vcf`/`.ics` entry, contents included.
    pub fn list_items(
        &self,
        collection: impl Into<VdirPath>,
    ) -> Result<BTreeSet<VdirItem>, VdirClientError> {
        self.run(VdirItemList::new(
            collection,
            VdirItemListOptions::default(),
        ))
    }

    /// Runs [`VdirItemStore`]: writes `contents` as a new (or updated) item
    /// under `collection`. Returns the (possibly generated) id and
    /// final on-disk path.
    ///
    /// When `id` is `None`, a fresh UUIDv4 is generated from the system
    /// entropy source.
    pub fn store_item(
        &self,
        collection: impl Into<VdirPath>,
        id: Option<String>,
        kind: VdirItemKind,
        contents: Vec<u8>,
    ) -> Result<(String, VdirPath), VdirClientError> {
        let VdirItemStoreOutput { id, path } = self.run(VdirItemStore::new(
            collection,
            id,
            kind,
            contents,
            VdirItemStoreOptions::default(),
        ))?;
        Ok((id, path))
    }

    /// Runs [`VdirItemCopy`]: copies item `id` from `source` into `target`.
    pub fn copy_item(
        &self,
        source: impl Into<VdirPath>,
        target: impl Into<VdirPath>,
        id: impl ToString,
    ) -> Result<(), VdirClientError> {
        self.run(VdirItemCopy::new(
            source,
            target,
            id,
            VdirItemCopyOptions::default(),
        ))
    }

    /// Runs [`VdirItemMove`]: moves item `id` from `source` into `target`.
    pub fn move_item(
        &self,
        source: impl Into<VdirPath>,
        target: impl Into<VdirPath>,
        id: impl ToString,
    ) -> Result<(), VdirClientError> {
        self.run(VdirItemMove::new(
            source,
            target,
            id,
            VdirItemMoveOptions::default(),
        ))
    }

    /// Runs [`VdirItemDelete`]: removes item `id` from `collection`.
    pub fn delete_item(
        &self,
        collection: impl Into<VdirPath>,
        id: impl ToString,
    ) -> Result<(), VdirClientError> {
        self.run(VdirItemDelete::new(
            collection,
            id,
            VdirItemDeleteOptions::default(),
        ))
    }
}

fn normalize_path(path: std::path::PathBuf) -> VdirPath {
    let s = path.to_string_lossy().into_owned();
    #[cfg(windows)]
    let s = s.replace('\\', "/");
    VdirPath::new(s)
}

fn create_dirs(paths: BTreeSet<VdirPath>) -> Result<(), io::Error> {
    for path in paths {
        trace!("create_dir_all {path}");
        fs::create_dir_all(path.as_str())?;
    }
    Ok(())
}

fn remove_dirs(paths: BTreeSet<VdirPath>) -> Result<(), io::Error> {
    for path in paths {
        trace!("remove_dir_all {path}");
        fs::remove_dir_all(path.as_str())?;
    }
    Ok(())
}

fn remove_files(paths: BTreeSet<VdirPath>) -> Result<(), io::Error> {
    for path in paths {
        trace!("remove_file {path}");
        fs::remove_file(path.as_str())?;
    }
    Ok(())
}

fn write_files(files: BTreeMap<VdirPath, Vec<u8>>) -> Result<(), io::Error> {
    for (path, contents) in files {
        trace!("write {path} ({} bytes)", contents.len());

        if let Some(parent) = std::path::Path::new(path.as_str()).parent() {
            fs::create_dir_all(parent)?;
        }
        fs::write(path.as_str(), &contents)?;
    }
    Ok(())
}

fn read_dirs(
    paths: BTreeSet<VdirPath>,
) -> Result<BTreeMap<VdirPath, BTreeSet<VdirPath>>, io::Error> {
    let mut entries = BTreeMap::new();

    for path in paths {
        trace!("read_dir {path}");

        let mut names = BTreeSet::new();
        match fs::read_dir(path.as_str()) {
            Ok(iter) => {
                for entry in iter {
                    let entry = entry?;
                    names.insert(normalize_path(entry.path()));
                }
            }
            Err(err) if err.kind() == io::ErrorKind::NotFound => {}
            Err(err) => return Err(err),
        }

        entries.insert(path, names);
    }

    Ok(entries)
}

fn read_files(paths: BTreeSet<VdirPath>) -> Result<BTreeMap<VdirPath, Vec<u8>>, io::Error> {
    let mut contents = BTreeMap::new();

    for path in paths {
        trace!("read_file {path}");
        let bytes = fs::read(path.as_str())?;
        contents.insert(path, bytes);
    }

    Ok(contents)
}

fn rename_paths(pairs: Vec<(VdirPath, VdirPath)>) -> Result<(), io::Error> {
    for (from, to) in pairs {
        trace!("rename {from} -> {to}");
        fs::rename(from.as_str(), to.as_str())?;
    }
    Ok(())
}

fn copy_paths(pairs: Vec<(VdirPath, VdirPath)>) -> Result<(), io::Error> {
    for (from, to) in pairs {
        trace!("copy {from} -> {to}");
        fs::copy(from.as_str(), to.as_str())?;
    }
    Ok(())
}

fn file_exists(paths: BTreeSet<VdirPath>) -> BTreeMap<VdirPath, bool> {
    let mut out = BTreeMap::new();
    for path in paths {
        let exists = fs::metadata(path.as_str())
            .map(|m| m.is_file())
            .unwrap_or(false);
        trace!("file_exists {path}: {exists}");
        out.insert(path, exists);
    }
    out
}

fn dir_exists(paths: BTreeSet<VdirPath>) -> BTreeMap<VdirPath, bool> {
    let mut out = BTreeMap::new();
    for path in paths {
        let exists = fs::metadata(path.as_str())
            .map(|m| m.is_dir())
            .unwrap_or(false);
        trace!("dir_exists {path}: {exists}");
        out.insert(path, exists);
    }
    out
}