cap_primitives/fs/dir_builder.rs
1use crate::fs::DirOptions;
2use std::fmt;
3
4/// A builder used to create directories in various manners.
5///
6/// This corresponds to [`std::fs::DirBuilder`].
7///
8/// Unlike `std::fs::DirBuilder`, this API has no `DirBuilder::create`, because
9/// creating directories requires a capability. Use [`Dir::create_dir_with`]
10/// instead.
11///
12/// [`Dir::create_dir_with`]: https://docs.rs/cap-std/latest/cap_std/fs/struct.Dir.html#method.create_dir_with
13///
14/// <details>
15/// We need to define our own version because the libstd `DirBuilder` doesn't
16/// have public accessors that we can use.
17/// </details>
18pub struct DirBuilder {
19 pub(crate) recursive: bool,
20 pub(crate) options: DirOptions,
21}
22
23impl DirBuilder {
24 /// Creates a new set of options with default mode/security settings for
25 /// all platforms and also non-recursive.
26 ///
27 /// This corresponds to [`std::fs::DirBuilder::new`].
28 #[allow(clippy::new_without_default)]
29 #[inline]
30 pub const fn new() -> Self {
31 Self {
32 recursive: false,
33 options: DirOptions::new(),
34 }
35 }
36
37 /// Indicates that directories should be created recursively, creating all
38 /// parent directories.
39 ///
40 /// This corresponds to [`std::fs::DirBuilder::recursive`].
41 #[inline]
42 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
43 self.recursive = recursive;
44 self
45 }
46
47 /// Return the `DirOptions` contained in this `DirBuilder`.
48 #[inline]
49 pub const fn options(&self) -> &DirOptions {
50 &self.options
51 }
52
53 /// Return the value of the `recursive` flag.
54 #[inline]
55 pub const fn is_recursive(&self) -> bool {
56 self.recursive
57 }
58}
59
60/// Unix-specific extensions to [`fs::DirBuilder`].
61#[cfg(unix)]
62pub trait DirBuilderExt {
63 /// Sets the mode to create new directories with. This option defaults to
64 /// 0o777.
65 fn mode(&mut self, mode: u32) -> &mut Self;
66}
67
68#[cfg(unix)]
69impl DirBuilderExt for DirBuilder {
70 #[inline]
71 fn mode(&mut self, mode: u32) -> &mut Self {
72 self.options.mode(mode);
73 self
74 }
75}
76
77impl fmt::Debug for DirBuilder {
78 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79 let mut b = f.debug_struct("DirBuilder");
80 b.field("recursive", &self.recursive);
81 b.field("options", &self.options);
82 b.finish()
83 }
84}