summaryrefslogtreecommitdiff
path: root/systems/_framework/src/space.rs
blob: 79c9b374f071f26922554f43eaa8ee32fd1204ff (plain)
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
use crate::space::error::SpaceError;
use just_fmt::fmt_path::{PathFormatConfig, fmt_path, fmt_path_custom};
use std::{
    cell::Cell,
    env::current_dir,
    ffi::OsString,
    ops::Deref,
    path::{Path, PathBuf},
};

pub mod error;

pub struct Space<T: SpaceRoot> {
    path_format_cfg: PathFormatConfig,

    content: T,
    space_dir: Cell<Option<PathBuf>>,
    current_dir: Option<PathBuf>,
}

impl<T: SpaceRoot> Space<T> {
    /// Create a new `Space` instance with the given content.
    pub fn new(content: T) -> Self {
        Space {
            path_format_cfg: PathFormatConfig {
                resolve_parent_dirs: true,
                ..Default::default()
            },
            content,
            space_dir: Cell::new(None),
            current_dir: None,
        }
    }

    /// Initialize a space at the given path.
    ///
    /// Checks if a space exists at the given path. If not, creates a new space
    /// by calling `T::create_space()` at that path.
    pub async fn init(&self, path: impl AsRef<Path>) -> Result<(), SpaceError> {
        let path = path.as_ref();
        let pattern = T::get_pattern();

        if !find_space_root_with(path.to_path_buf(), pattern).is_ok() {
            T::create_space(path).await?;
        }
        Ok(())
    }

    /// Create a new space at the given path with the specified name.
    ///
    /// The full path is constructed as `path/name`. Checks if a space already
    /// exists at that location. If not, creates a new space by calling
    /// `T::create_space()` at that path.
    pub async fn create(&self, path: impl AsRef<Path>, name: &str) -> Result<(), SpaceError> {
        let full_path = path.as_ref().join(name);
        self.init(full_path).await
    }

    /// Initialize a space in the current directory.
    ///
    /// Checks if a space exists in the current directory. If not, creates a new space
    /// by calling `T::create_space()` at the current directory.
    pub async fn init_here(&self) -> Result<(), SpaceError> {
        let current_dir = self.current_dir()?;
        self.init(current_dir).await
    }

    /// Create a new space in the current directory with the specified name.
    ///
    /// The full path is constructed as `current_dir/name`. Checks if a space already
    /// exists at that location. If not, creates a new space by calling
    /// `T::create_space()` at that path.
    pub async fn create_here(&self, name: &str) -> Result<(), SpaceError> {
        let current_dir = self.current_dir()?;
        self.create(current_dir, name).await
    }

    /// Consume the `Space`, returning the inner content.
    pub fn into_inner(self) -> T {
        self.content
    }

    /// Get the space directory for the given current directory.
    ///
    /// If the space directory has already been found, it is returned from cache.
    /// Otherwise, it is found using the pattern from `T::get_pattern()`.
    pub fn space_dir(&self, current_dir: impl Into<PathBuf>) -> Result<PathBuf, SpaceError> {
        let pattern = T::get_pattern();
        match self.space_dir.take() {
            Some(dir) => {
                self.update_space_dir(Some(dir.clone()));
                Ok(dir)
            }
            None => {
                let result = find_space_root_with(current_dir.into(), pattern);
                match result {
                    Ok(r) => {
                        self.update_space_dir(Some(r.clone()));
                        Ok(r)
                    }
                    Err(e) => Err(e),
                }
            }
        }
    }

    /// Get the space directory using the current directory.
    ///
    /// The current directory is either the explicitly set directory or the process's current directory.
    pub fn space_dir_current(&self) -> Result<PathBuf, SpaceError> {
        self.space_dir(self.current_dir()?)
    }

    /// Set the current directory explicitly.
    ///
    /// This clears any cached space directory.
    pub fn set_current_dir(&mut self, path: PathBuf) -> Result<(), SpaceError> {
        self.update_space_dir(None);
        self.current_dir = Some(fmt_path(path)?);
        Ok(())
    }

    /// Reset the current directory to the process's current directory.
    ///
    /// This clears any cached space directory.
    pub fn reset_current_dir(&mut self) {
        self.update_space_dir(None);
        self.current_dir = None
    }

    /// Get the current directory.
    ///
    /// Returns the explicitly set directory if any, otherwise the process's current directory.
    fn current_dir(&self) -> Result<PathBuf, SpaceError> {
        match &self.current_dir {
            Some(d) => Ok(d.clone()),
            None => Ok(fmt_path(current_dir()?)?),
        }
    }

    /// Update the cached space directory.
    fn update_space_dir(&self, space_dir: Option<PathBuf>) {
        self.space_dir.set(space_dir);
    }
}

impl<T: SpaceRoot> Space<T> {
    /// Convert a relative path to an absolute path within the space.
    ///
    /// The path is formatted according to the space's path format configuration.
    pub fn local_path(&self, relative_path: impl AsRef<Path>) -> Result<PathBuf, SpaceError> {
        let path = fmt_path_custom(relative_path.as_ref().to_path_buf(), &self.path_format_cfg)?;
        let raw_path = self.space_dir_current()?.join(path);
        Ok(fmt_path(raw_path)?)
    }

    /// Convert an absolute path to a relative path within the space, if possible.
    ///
    /// Returns `None` if the absolute path is not under the space directory.
    pub fn to_local_path(
        &self,
        absolute_path: impl AsRef<Path>,
    ) -> Result<Option<PathBuf>, SpaceError> {
        let path = fmt_path(absolute_path.as_ref())?;
        let current = self.space_dir_current()?;
        match path.strip_prefix(current) {
            Ok(result) => Ok(Some(result.to_path_buf())),
            Err(_) => Ok(None),
        }
    }

    /// Canonicalize a relative path within the space.
    pub async fn canonicalize(
        &self,
        relative_path: impl AsRef<Path>,
    ) -> Result<PathBuf, SpaceError> {
        let path = self.local_path(relative_path)?;
        Ok(tokio::fs::canonicalize(path).await?)
    }

    /// Copy a file from one relative path to another within the space.
    pub async fn copy(
        &self,
        from: impl AsRef<Path>,
        to: impl AsRef<Path>,
    ) -> Result<u64, SpaceError> {
        let from_path = self.local_path(from)?;
        let to_path = self.local_path(to)?;
        Ok(tokio::fs::copy(from_path, to_path).await?)
    }

    /// Create a directory at the given relative path within the space.
    pub async fn create_dir(&self, relative_path: impl AsRef<Path>) -> Result<(), SpaceError> {
        let path = self.local_path(relative_path)?;
        Ok(tokio::fs::create_dir(path).await?)
    }

    /// Recursively create a directory and all its parents at the given relative path within the space.
    pub async fn create_dir_all(&self, relative_path: impl AsRef<Path>) -> Result<(), SpaceError> {
        let path = self.local_path(relative_path)?;
        Ok(tokio::fs::create_dir_all(path).await?)
    }

    /// Create a hard link from `src` to `dst` within the space.
    pub async fn hard_link(
        &self,
        src: impl AsRef<Path>,
        dst: impl AsRef<Path>,
    ) -> Result<(), SpaceError> {
        let src_path = self.local_path(src)?;
        let dst_path = self.local_path(dst)?;
        Ok(tokio::fs::hard_link(src_path, dst_path).await?)
    }

    /// Get metadata for a file or directory at the given relative path within the space.
    pub async fn metadata(
        &self,
        relative_path: impl AsRef<Path>,
    ) -> Result<std::fs::Metadata, SpaceError> {
        let path = self.local_path(relative_path)?;
        Ok(tokio::fs::metadata(path).await?)
    }

    /// Read the entire contents of a file at the given relative path within the space.
    pub async fn read(&self, relative_path: impl AsRef<Path>) -> Result<Vec<u8>, SpaceError> {
        let path = self.local_path(relative_path)?;
        Ok(tokio::fs::read(path).await?)
    }

    /// Read the directory entries at the given relative path within the space.
    pub async fn read_dir(
        &self,
        relative_path: impl AsRef<Path>,
    ) -> Result<tokio::fs::ReadDir, SpaceError> {
        let path = self.local_path(relative_path)?;
        Ok(tokio::fs::read_dir(path).await?)
    }

    /// Read the target of a symbolic link at the given relative path within the space.
    pub async fn read_link(&self, relative_path: impl AsRef<Path>) -> Result<PathBuf, SpaceError> {
        let path = self.local_path(relative_path)?;
        Ok(tokio::fs::read_link(path).await?)
    }

    /// Read the entire contents of a file as a string at the given relative path within the space.
    pub async fn read_to_string(
        &self,
        relative_path: impl AsRef<Path>,
    ) -> Result<String, SpaceError> {
        let path = self.local_path(relative_path)?;
        Ok(tokio::fs::read_to_string(path).await?)
    }

    /// Remove an empty directory at the given relative path within the space.
    pub async fn remove_dir(&self, relative_path: impl AsRef<Path>) -> Result<(), SpaceError> {
        let path = self.local_path(relative_path)?;
        Ok(tokio::fs::remove_dir(path).await?)
    }

    /// Remove a directory and all its contents at the given relative path within the space.
    pub async fn remove_dir_all(&self, relative_path: impl AsRef<Path>) -> Result<(), SpaceError> {
        let path = self.local_path(relative_path)?;
        Ok(tokio::fs::remove_dir_all(path).await?)
    }

    /// Remove a file at the given relative path within the space.
    pub async fn remove_file(&self, relative_path: impl AsRef<Path>) -> Result<(), SpaceError> {
        let path = self.local_path(relative_path)?;
        Ok(tokio::fs::remove_file(path).await?)
    }

    /// Rename a file or directory from one relative path to another within the space.
    pub async fn rename(
        &self,
        from: impl AsRef<Path>,
        to: impl AsRef<Path>,
    ) -> Result<(), SpaceError> {
        let from_path = self.local_path(from)?;
        let to_path = self.local_path(to)?;
        Ok(tokio::fs::rename(from_path, to_path).await?)
    }

    /// Set permissions for a file or directory at the given relative path within the space.
    pub async fn set_permissions(
        &self,
        relative_path: impl AsRef<Path>,
        perm: std::fs::Permissions,
    ) -> Result<(), SpaceError> {
        let path = self.local_path(relative_path)?;
        Ok(tokio::fs::set_permissions(path, perm).await?)
    }

    /// Create a symbolic link from `src` to `dst` within the space (Unix only).
    #[cfg(unix)]
    pub async fn symlink(
        &self,
        src: impl AsRef<Path>,
        dst: impl AsRef<Path>,
    ) -> Result<(), SpaceError> {
        let src_path = self.local_path(src)?;
        let dst_path = self.local_path(dst)?;
        Ok(tokio::fs::symlink(src_path, dst_path).await?)
    }

    /// Create a directory symbolic link from `src` to `dst` within the space (Windows only).
    #[cfg(windows)]
    pub async fn symlink_dir(
        &self,
        src: impl AsRef<Path>,
        dst: impl AsRef<Path>,
    ) -> Result<(), SpaceError> {
        let src_path = self.local_path(src)?;
        let dst_path = self.local_path(dst)?;
        Ok(tokio::fs::symlink_dir(src_path, dst_path).await?)
    }

    /// Create a file symbolic link from `src` to `dst` within the space (Windows only).
    #[cfg(windows)]
    pub async fn symlink_file(
        &self,
        src: impl AsRef<Path>,
        dst: impl AsRef<Path>,
    ) -> Result<(), SpaceError> {
        let src_path = self.local_path(src)?;
        let dst_path = self.local_path(dst)?;
        Ok(tokio::fs::symlink_file(src_path, dst_path).await?)
    }

    /// Get metadata for a file or directory without following symbolic links.
    pub async fn symlink_metadata(
        &self,
        relative_path: impl AsRef<Path>,
    ) -> Result<std::fs::Metadata, SpaceError> {
        let path = self.local_path(relative_path)?;
        Ok(tokio::fs::symlink_metadata(path).await?)
    }

    /// Check if a file or directory exists at the given relative path within the space.
    pub async fn try_exists(&self, relative_path: impl AsRef<Path>) -> Result<bool, SpaceError> {
        let path = self.local_path(relative_path)?;
        Ok(tokio::fs::try_exists(path).await?)
    }

    /// Write data to a file at the given relative path within the space.
    pub async fn write(
        &self,
        relative_path: impl AsRef<Path>,
        contents: impl AsRef<[u8]>,
    ) -> Result<(), SpaceError> {
        let path = self.local_path(relative_path)?;
        Ok(tokio::fs::write(path, contents).await?)
    }
}

impl<T: SpaceRoot> From<T> for Space<T> {
    fn from(content: T) -> Self {
        Space::<T>::new(content)
    }
}

impl<T: SpaceRoot> AsRef<T> for Space<T> {
    fn as_ref(&self) -> &T {
        &self.content
    }
}

impl<T: SpaceRoot> Deref for Space<T> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        &self.as_ref()
    }
}

pub trait SpaceRoot: Sized {
    /// Get the pattern used to identify the space root
    fn get_pattern() -> SpaceRootFindPattern;

    /// Given a non-space directory, implement logic to make it a space-recognizable directory
    fn create_space(path: &Path) -> impl Future<Output = Result<(), SpaceError>> + Send;
}

pub enum SpaceRootFindPattern {
    IncludeDotDir(OsString),
    IncludeFile(OsString),
}

/// Find the space directory containing the current directory,
/// Use Pattern to specify the search method
///
/// For the full implementation, see `find_space_root_with`
pub fn find_space_root(pattern: SpaceRootFindPattern) -> Result<PathBuf, SpaceError> {
    find_space_root_with(current_dir()?, pattern)
}

/// Find the space directory containing the specified directory,
/// Use Pattern to specify the search method
///
/// IncludeDotDir(OsString)
/// - Contains a specific directory, e.g., to find `.git`, use `IncludeDotDir("git".into())`
///
/// IncludeFile(OsString)
/// - Contains a specific file, e.g., to find `Cargo.toml`, use `IncludeFile("Cargo.toml".into())`
///
/// ```rust
/// # use std::env::current_dir;
/// # use std::path::PathBuf;
/// # use framework::space::SpaceRootFindPattern;
/// # use framework::space::find_space_root_with;
/// // Find the `.cargo` directory
/// let path = find_space_root_with(
///     current_dir().unwrap(),
///     SpaceRootFindPattern::IncludeDotDir(
///         "cargo".into()
///     )
/// );
/// assert!(path.is_ok());
/// assert!(path.unwrap().join(".cargo").is_dir())
/// ```
/// ```rust
/// # use std::env::current_dir;
/// # use std::path::PathBuf;
/// # use framework::space::SpaceRootFindPattern;
/// # use framework::space::find_space_root_with;
/// // Find the `.cargo` directory
/// let path = find_space_root_with(
///     current_dir().unwrap(),
///     SpaceRootFindPattern::IncludeDotDir(
///         ".cargo".into()
///     )
/// );
/// assert!(path.is_ok());
/// assert!(path.unwrap().join(".cargo").is_dir())
/// ```
/// ```rust
/// # use std::env::current_dir;
/// # use std::path::PathBuf;
/// # use framework::space::SpaceRootFindPattern;
/// # use framework::space::find_space_root_with;
/// // Find the `Cargo.toml` file
/// let path = find_space_root_with(
///     current_dir().unwrap(),
///     SpaceRootFindPattern::IncludeFile(
///         "Cargo.toml".into()
///     )
/// );
/// assert!(path.is_ok());
/// assert!(path.unwrap().join("Cargo.toml").is_file())
/// ```
pub fn find_space_root_with(
    current_dir: PathBuf,
    pattern: SpaceRootFindPattern,
) -> Result<PathBuf, SpaceError> {
    // Get the pattern used for matching
    let match_pattern: Box<dyn Fn(&Path) -> bool> = match pattern {
        SpaceRootFindPattern::IncludeDotDir(dot_dir_name) => Box::new(move |path| {
            let dir_name = dot_dir_name.to_string_lossy();
            let dir_name = if dir_name.starts_with('.') {
                dir_name.to_string()
            } else {
                format!(".{}", dir_name)
            };
            path.join(dir_name).is_dir()
        }),
        SpaceRootFindPattern::IncludeFile(file_name) => {
            Box::new(move |path| path.join(&file_name).is_file())
        }
    };
    // Match parent directories
    let mut current = current_dir;
    loop {
        if match_pattern(current.as_path()) {
            return Ok(current);
        }
        if let Some(parent) = current.parent() {
            current = parent.to_path_buf();
        } else {
            break;
        }
    }
    Err(SpaceError::SpaceNotFound)
}