kxio 3.2.0

Provides injectable Filesystem and Network resources to make code more testable
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
//
use std::{
    fmt::Display,
    marker::PhantomData,
    path::{Path, PathBuf},
};

use crate::fs::{Error, Result};

use super::{DirHandle, FileHandle, PathHandle};

/// Marker trait for the type of [PathReal].
pub trait PathType {}

/// Path marker for the type of [PathReal].
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PathMarker;
impl PathType for PathMarker {}

/// File marker for the type of [PathReal].
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct FileMarker;
impl PathType for FileMarker {}

/// Dir marker for the type of [PathReal].
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct DirMarker;
impl PathType for DirMarker {}

/// Represents a path in the filesystem.
///
/// It can be a simple path, or it can be a file or a directory.
#[derive(Clone, Debug, Default)]
pub struct PathReal<T: PathType> {
    base: PathBuf,
    path: PathBuf,
    _phanton: PhantomData<T>,
    pub(super) error: Option<Error>,
}
impl<T: PathType> PathReal<T> {
    #[tracing::instrument(skip_all)]
    pub(super) fn new(base: impl Into<PathBuf>, path: impl Into<PathBuf>) -> Self {
        let base: PathBuf = base.into();
        let path: PathBuf = path.into();
        let error = PathReal::<T>::validate(&base, &path);
        tracing::debug!(?base, ?path, ?error, "new");
        Self {
            base,
            path,
            _phanton: PhantomData::<T>,
            error,
        }
    }

    /// Returns a [PathBuf] for the path.
    ///
    /// ```
    /// # use kxio::fs::Result;
    /// # fn main() -> Result<()> {
    /// let fs = kxio::fs::temp()?;
    /// let path = fs.base().join("foo");
    /// let path = fs.path(&path);
    /// let pathbuf = path.as_pathbuf();
    /// #    Ok(())
    /// # }
    /// ```
    pub fn as_pathbuf(&self) -> PathBuf {
        self.base.join(&self.path)
    }

    // only stores the first error, subsequent errors are dropped
    pub(super) fn put(&mut self, error: Error) {
        if self.error.is_none() {
            self.error.replace(error);
        }
    }

    fn validate(base: &Path, path: &Path) -> Option<Error> {
        match PathReal::<PathMarker>::clean_path(path) {
            Err(error) => Some(error),
            Ok(path) => {
                if !path.starts_with(base) {
                    return Some(Error::PathTraversal {
                        base: base.to_path_buf(),
                        path,
                    });
                }
                None
            }
        }
    }

    #[tracing::instrument]
    fn clean_path(path: &Path) -> Result<PathBuf> {
        use path_clean::PathClean;
        let abs_path = if path.is_absolute() {
            tracing::debug!("is absolute");
            path.to_path_buf()
        } else {
            tracing::debug!("std::env::current_dir");
            std::env::current_dir().expect("current_dir").join(path)
        }
        .clean();
        tracing::debug!(?abs_path);
        Ok(abs_path)
    }

    #[tracing::instrument(skip_all)]
    pub(super) fn check_error(&self) -> Result<()> {
        if let Some(error) = &self.error {
            tracing::warn!(?error, "error");
            Err(error.clone())
        } else {
            Ok(())
        }
    }

    /// Returns true if the path exists.
    ///
    /// N.B. If you have the path used to create the file or directory, you
    /// should use [std::path::Path::exists] instead.
    ///
    /// ```
    /// # use kxio::fs::Result;
    /// # fn main() -> Result<()> {
    /// let fs = kxio::fs::temp()?;
    /// let path = fs.base().join("foo");
    /// let dir = fs.dir(&path);
    /// #    dir.create()?;
    /// if dir.exists()? { /* ... */ }
    /// #    Ok(())
    /// # }
    /// ```
    #[tracing::instrument(skip_all)]
    pub fn exists(&self) -> Result<bool> {
        self.check_error()?;
        let path = self.as_pathbuf();
        tracing::debug!(?path, "PathBuf::exists");
        Ok(path.exists())
    }

    /// Returns true if the path is a directory.
    ///
    /// ```
    /// # use kxio::fs::Result;
    /// # fn main() -> Result<()> {
    /// let fs = kxio::fs::temp()?;
    /// let path = fs.base().join("foo");
    /// #    fs.dir(&path).create()?;
    /// if path.is_dir() { /* ... */ }
    /// #    Ok(())
    /// # }
    /// ```
    #[tracing::instrument(skip_all)]
    pub fn is_dir(&self) -> Result<bool> {
        self.check_error()?;
        let path = self.as_pathbuf();
        tracing::debug!(?path, "PathBuf::is_dir");
        Ok(path.is_dir())
    }

    /// Returns true if the path is a file.
    ///
    /// ```
    /// # use kxio::fs::Result;
    /// # fn main() -> Result<()> {
    /// let fs = kxio::fs::temp()?;
    /// let path = fs.base().join("foo");
    /// #    fs.dir(&path).create()?;
    /// if path.is_file() { /* ... */ }
    /// #    Ok(())
    /// # }
    /// ```
    #[tracing::instrument(skip_all)]
    pub fn is_file(&self) -> Result<bool> {
        self.check_error()?;
        let path = self.as_pathbuf();
        tracing::debug!(?path, "PathBuf::is_file");
        Ok(path.is_file())
    }

    /// Returns the path as a directory if it exists and is a directory, otherwise
    /// it will return None.
    ///
    /// ```
    /// # use kxio::fs::Result;
    /// # fn main() -> Result<()> {
    /// let fs = kxio::fs::temp()?;
    /// let path = fs.base().join("foo");
    /// #    fs.dir(&path).create()?;
    /// let file = fs.path(&path);
    /// if let Ok(Some(dir)) = file.as_dir() { /* ... */ }
    /// #    Ok(())
    /// # }
    /// ```
    #[tracing::instrument(skip_all)]
    pub fn as_dir(&self) -> Result<Option<DirHandle>> {
        self.check_error()?;
        let path = self.as_pathbuf();
        let is_dir = path.is_dir();
        tracing::debug!(?path, ?is_dir, "PathBuf::is_dir");
        if is_dir {
            Ok(Some(PathReal::new(&self.base, &self.path)))
        } else {
            Ok(None)
        }
    }

    /// Returns the path as a file if it exists and is a file, otherwise
    /// it will return None.
    ///
    /// ```
    /// # use kxio::fs::Result;
    /// # fn main() -> Result<()> {
    /// let fs = kxio::fs::temp()?;
    /// let path = fs.base().join("foo");
    /// #    fs.dir(&path).create()?;
    /// let file = fs.path(&path);
    /// if let Ok(Some(file)) = file.as_file() { /* ... */ }
    /// #    Ok(())
    /// # }
    /// ```
    #[tracing::instrument(skip_all)]
    pub fn as_file(&self) -> Result<Option<FileHandle>> {
        self.check_error()?;
        let path = self.as_pathbuf();
        let is_file = path.is_file();
        tracing::debug!(?path, ?is_file, "PathBuf::is_file");
        if is_file {
            Ok(Some(PathReal::new(&self.base, &self.path)))
        } else {
            Ok(None)
        }
    }

    /// Renames a path.
    ///
    /// Wrapper for [std::fs::rename]
    ///
    /// ```
    /// # use kxio::fs::Result;
    /// # fn main() -> Result<()> {
    /// let fs = kxio::fs::temp()?;
    /// let src_path = fs.base().join("foo");
    /// let src = fs.file(&src_path);
    /// # src.write("bar")?;
    /// let dst_path = fs.base().join("bar");
    /// let dst = fs.file(&dst_path);
    /// src.rename(&dst)?;
    /// #    Ok(())
    /// # }
    /// ```
    #[tracing::instrument(skip_all)]
    pub fn rename(&self, dest: &PathHandle<T>) -> Result<()> {
        self.check_error()?;
        let from = self.as_pathbuf();
        let to = dest.as_pathbuf();
        tracing::debug!(?from, ?to, "std::fs::rename");
        std::fs::rename(from, to).map_err(Error::Io)
    }

    /// Returns the metadata for a path.
    ///
    /// Wrapper for [std::fs::metadata]
    ///
    /// ```
    /// # fn try_main() -> kxio::fs::Result<()> {
    /// let fs = kxio::fs::temp()?;
    /// let path = fs.base().join("foo");
    /// let file = fs.file(&path);
    /// let metadata = file.metadata()?;
    /// # Ok(())
    /// # }
    /// ```
    #[tracing::instrument(skip_all)]
    pub fn metadata(&self) -> Result<std::fs::Metadata> {
        self.check_error()?;
        let path = self.as_pathbuf();
        tracing::debug!(?path, "std::fs::metadata");
        std::fs::metadata(path).map_err(Error::Io)
    }

    /// Creates a symbolic link to a path.
    ///
    /// Wrapper for [std::os::unix::fs::symlink]
    ///
    /// ```
    /// # use kxio::fs::Result;
    /// # fn main() -> Result<()> {
    /// let fs = kxio::fs::temp()?;
    /// let src_path = fs.base().join("foo");
    /// let src = fs.file(&src_path);
    /// # src.write("bar")?;
    /// let link_path = fs.base().join("bar");
    /// let link = fs.path(&link_path);
    /// src.soft_link(&link)?;
    /// #    Ok(())
    /// # }
    /// ```
    #[tracing::instrument(skip_all)]
    pub fn soft_link(&self, link: &PathReal<PathMarker>) -> Result<()> {
        self.check_error()?;
        let original = self.as_pathbuf();
        let link = link.as_pathbuf();
        tracing::debug!(?original, ?link, "std::os::unix::fs::symlink");
        std::os::unix::fs::symlink(original, link).map_err(Error::Io)
    }

    /// Returns true if the path is a symbolic link.
    ///
    /// ```
    /// # use kxio::fs::Result;
    /// # fn main() -> Result<()> {
    /// let fs = kxio::fs::temp()?;
    /// let path = fs.base().join("foo");
    /// let dir = fs.dir(&path);
    /// # dir.create()?;
    /// if dir.is_link()? { /* ... */ }
    /// #    Ok(())
    /// # }
    /// ```
    #[tracing::instrument(skip_all)]
    pub fn is_link(&self) -> Result<bool> {
        self.check_error()?;
        let path = self.as_pathbuf();
        tracing::debug!(?path, "PathBuf::is_symlink");
        Ok(path.is_symlink())
    }

    /// Returns the canonical, absolute form of the path with all intermediate
    /// components normalized and symbolic links resolved.
    ///
    /// ```
    /// # use kxio::fs::Result;
    /// # fn main() -> Result<()> {
    /// let fs = kxio::fs::temp()?;
    /// let path = fs.base().join("foo");
    /// #    fs.dir(&path).create()?;
    /// let dir = fs.path(&path);
    /// let canonical = dir.canonicalize()?;
    /// #    Ok(())
    /// # }
    /// ```
    #[tracing::instrument(skip_all)]
    pub fn canonicalize(&self) -> Result<PathBuf> {
        self.check_error()?;
        let path = self.as_pathbuf();
        tracing::debug!(?path, "PathBuf::canonicalize");
        path.canonicalize().map_err(Error::Io)
    }

    /// Returns the metadata for a path without following symlinks.
    ///
    /// Wrapper for [std::fs::symlink_metadata]
    ///
    /// ```
    /// # fn try_main() -> kxio::fs::Result<()> {
    /// let fs = kxio::fs::temp()?;
    /// let path = fs.base().join("foo");
    /// let file = fs.file(&path);
    /// let metadata = file.symlink_metadata()?;
    /// # Ok(())
    /// # }
    /// ```
    #[tracing::instrument(skip_all)]
    pub fn symlink_metadata(&self) -> Result<std::fs::Metadata> {
        self.check_error()?;
        let path = self.as_pathbuf();
        tracing::debug!(?path, "std::fs::symlink_metadata");
        std::fs::symlink_metadata(path).map_err(Error::Io)
    }

    /// Sets the permissions of a file or directory.
    ///
    /// Wrapper for [std::fs::set_permissions]
    ///
    /// ```
    /// # use kxio::fs::Result;
    /// # use std::os::unix::fs::PermissionsExt;
    /// # fn main() -> Result<()> {
    /// let fs = kxio::fs::temp()?;
    /// let path = fs.base().join("foo");
    /// let file = fs.file(&path);
    /// # file.write("bar")?;
    /// file.set_permissions(std::fs::Permissions::from_mode(0o755))?;
    /// #    Ok(())
    /// # }
    /// ```
    #[tracing::instrument(skip_all)]
    pub fn set_permissions(&self, perms: std::fs::Permissions) -> Result<()> {
        self.check_error()?;
        let path = self.as_pathbuf();
        tracing::debug!(?path, ?perms, "std::fs::set_permissions");
        std::fs::set_permissions(path, perms).map_err(Error::Io)
    }

    #[tracing::instrument(skip_all)]
    pub fn read_link(&self) -> Result<PathReal<PathMarker>> {
        self.check_error()?;
        let path = self.as_pathbuf();
        tracing::debug!(?path, "std::fs::read_link");
        let read_path = std::fs::read_link(path).map_err(Error::Io)?;
        let path = read_path.strip_prefix(&self.base).unwrap().to_path_buf();
        Ok(PathReal::new(&self.base, &path))
    }
}
impl From<PathHandle<PathMarker>> for PathBuf {
    fn from(path: PathReal<PathMarker>) -> Self {
        path.base.join(path.path)
    }
}
impl From<DirHandle> for PathHandle<PathMarker> {
    fn from(dir: DirHandle) -> Self {
        PathReal::new(dir.base, dir.path)
    }
}
impl From<FileHandle> for PathHandle<PathMarker> {
    fn from(file: FileHandle) -> Self {
        PathReal::new(file.base, file.path)
    }
}

impl Display for PathReal<PathMarker> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_pathbuf().display())
    }
}