-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathutils.rs
More file actions
148 lines (133 loc) · 4.88 KB
/
Copy pathutils.rs
File metadata and controls
148 lines (133 loc) · 4.88 KB
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
use std::borrow::BorrowMut;
use std::path::{Path, PathBuf};
pub(crate) trait PathBufExt: BorrowMut<PathBuf> + Sized {
fn joined<P: AsRef<Path>>(mut self, path: P) -> Self {
self.borrow_mut().push(path);
self
}
fn with_exe_ext(mut self) -> Self {
self.borrow_mut().set_extension(std::env::consts::EXE_EXTENSION);
self
}
fn joined_int<I: itoa::Integer>(self, path_seg: I) -> Self {
self.joined(itoa::Buffer::new().format(path_seg))
}
}
impl PathBufExt for PathBuf {}
/// Declares a new strongly-typed path newtype.
///
/// ```
/// # use spacetimedb_paths::path_type;
/// path_type! {
/// /// optional docs
/// // optional. if false, makes the type's constructor public.
/// # // TODO: replace cfg(any()) with cfg(false) once stabilized (rust-lang/rust#131204)
/// #[non_exhaustive(any())]
/// FooPath: dir // or file. adds extra utility methods for manipulating the file/dir
/// }
/// ```
#[macro_export]
macro_rules! path_type {
($(#[doc = $doc:literal])* $(#[non_exhaustive($($non_exhaustive:tt)+)])? $name:ident) => {
$(#[doc = $doc])*
#[derive(Clone, Debug, $crate::__serde::Serialize, $crate::__serde::Deserialize)]
#[serde(transparent)]
#[cfg_attr(all($($($non_exhaustive)+)?), non_exhaustive)]
pub struct $name(pub std::path::PathBuf);
impl AsRef<std::path::Path> for $name {
#[inline]
fn as_ref(&self) -> &std::path::Path {
&self.0
}
}
impl AsRef<std::ffi::OsStr> for $name {
#[inline]
fn as_ref(&self) -> &std::ffi::OsStr {
self.0.as_ref()
}
}
impl From<std::ffi::OsString> for $name {
fn from(s: std::ffi::OsString) -> Self {
Self(s.into())
}
}
impl $crate::FromPathUnchecked for $name {
fn from_path_unchecked(path: impl Into<std::path::PathBuf>) -> Self {
Self(path.into())
}
}
impl $name {
#[inline]
pub fn display(&self) -> std::path::Display<'_> {
self.0.display()
}
#[inline]
pub fn metadata(&self) -> std::io::Result<std::fs::Metadata> {
self.0.metadata()
}
}
};
($(#[$($attr:tt)+])* $name:ident: dir) => {
path_type!($(#[$($attr)+])* $name);
impl $name {
#[inline]
pub fn create(&self) -> std::io::Result<()> {
std::fs::create_dir_all(self)
}
#[inline]
pub fn read_dir(&self) -> std::io::Result<std::fs::ReadDir> {
self.0.read_dir()
}
#[inline]
pub fn is_dir(&self) -> bool {
self.0.is_dir()
}
}
};
($(#[$($attr:tt)+])* $name:ident: file) => {
path_type!($(#[$($attr)+])* $name);
impl $name {
pub fn read(&self) -> std::io::Result<Vec<u8>> {
std::fs::read(self)
}
pub fn read_to_string(&self) -> std::io::Result<String> {
std::fs::read_to_string(self)
}
pub fn write(&self, contents: impl AsRef<[u8]>) -> std::io::Result<()> {
use std::io::Write as _;
let path = &self.0;
let parent = path.parent().ok_or_else(||
std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!("cannot replace {} without enclosing directory", path.display()))
)?;
std::fs::create_dir_all(&parent)?;
let mut tmp = $crate::__tempfile::NamedTempFile::new_in(parent)?;
tmp.write_all(contents.as_ref())?;
tmp.as_file().sync_all()?;
tmp.persist(&path)?;
// On Windows, syncing the directory is not necessary and doesn't even work.
#[cfg(not(target_os = "windows"))]
std::fs::File::open(parent)?.sync_all()?;
Ok(())
}
/// Opens a file at this path with the given options, ensuring its parent directory exists.
#[inline]
pub fn open_file(&self, options: &std::fs::OpenOptions) -> std::io::Result<std::fs::File> {
self.create_parent()?;
options.open(self)
}
/// Create the parent directory of this path if it doesn't already exist.
#[inline]
pub fn create_parent(&self) -> std::io::Result<()> {
if let Some(parent) = self.0.parent() {
if parent != std::path::Path::new("") {
std::fs::create_dir_all(parent)?;
}
}
Ok(())
}
}
};
}
pub(crate) use path_type;