assemble-core 0.2.0

The core crate of the assemble-rs package
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
//! Workspaces help provide limited access to files

use crate::file::RegularFile;

use log::debug;

use std::collections::HashSet;

use std::fs::{create_dir_all, OpenOptions};
use std::io::{Read, Write};
use std::path::{Component, Path, PathBuf};

use std::io;
use std::sync::{Arc, PoisonError, RwLock};
use tempfile::TempDir;

#[derive(Debug, thiserror::Error)]
pub enum WorkspaceError {
    #[error("Empty file name unsupported")]
    EmptyFileName,
    #[error("Given path is protected, and can not be written to")]
    PathProtected(PathBuf),
    #[error(transparent)]
    IoError(#[from] io::Error),
    #[error("Protected paths were poisoned")]
    PoisonError,
}

impl<T> From<PoisonError<T>> for WorkspaceError {
    fn from(_: PoisonError<T>) -> Self {
        Self::PoisonError
    }
}

pub type WorkspaceResult<T> = Result<T, WorkspaceError>;

pub trait WorkspaceEntry {
    fn into_absolute_path(self) -> WorkspaceResult<PathBuf>;
}

pub trait WorkspaceDirectory: WorkspaceEntry {
    /// Create a workspace that's relative to this workspace. Shares proteced paths with parent workspace
    /// and other created workspaces.
    ///
    /// # Error
    /// Will panic if any `..` paths are present.
    fn new_workspace<P: AsRef<Path>>(&self, path: P) -> Workspace {
        let resolved = self.my_workspace().resolve_path(path.as_ref());
        Workspace {
            root_dir: resolved,
            protected_path: self.my_workspace().protected_path.clone(),
        }
    }

    /// Gets the workspace this directory is part of.
    fn my_workspace(&self) -> &Workspace;

    /// Gets the path of this directory relative to the workspace.
    fn rel_path(&self) -> PathBuf;

    /// Gets the absolute path of this directory
    fn absolute_path(&self) -> PathBuf {
        self.my_workspace().resolve_path(&self.rel_path())
    }

    /// Creates a file within this directory
    ///
    /// # Error
    /// Will panic if `..` paths are present at root of workspace
    fn file(&self, file: &str) -> WorkspaceResult<RegularFile>;

    /// Creates a directory within this directory
    /// # Error
    /// Will panic if `..` paths are present at root of workspace
    fn dir(&self, name: &str) -> WorkspaceResult<Dir>;

    /// Creates a _protected_ directory in this directory
    /// # Error
    /// Will panic if `..` paths are present at root of workspace
    fn protected_dir(&self, name: &str) -> WorkspaceResult<Dir>;

    /// Creates a _protected_ file in this directory
    /// # Error
    /// Will panic if `..` paths are present at root of workspace
    fn protected_file(&self, name: &str) -> WorkspaceResult<RegularFile>;

    /// Checks if a path is protected.
    ///
    /// The path should be a relative path from the member.
    fn is_protected(&self, path: &Path) -> bool {
        self.my_workspace().is_protected(path)
    }
}

#[derive(Debug, Clone)]
pub struct Workspace {
    root_dir: PathBuf,
    protected_path: Arc<RwLock<HashSet<PathBuf>>>,
}

impl Workspace {
    /// Creates a workspace that's temporary
    pub fn new_temp() -> Self {
        let file = TempDir::new().unwrap();
        Self::new(file.into_path())
    }

    pub fn new(path: impl AsRef<Path>) -> Self {
        Self {
            root_dir: path.as_ref().to_path_buf(),
            protected_path: Arc::new(Default::default()),
        }
    }

    /// Gets the root directory of the workspace
    pub fn path(&self) -> &Path {
        &self.root_dir
    }

    /// Resolves a path relative to this workspace.
    ///
    /// '/' is treated as the workspace root.
    /// # Panic
    ///
    /// - Will panic if `..` present at root.
    /// - Will also panic if prefix is present (only on windows)
    pub fn resolve_path(&self, path: &Path) -> PathBuf {
        let origin = &self.root_dir;
        let mut relative = self.root_dir.clone();
        for component in path.components() {
            match component {
                Component::Prefix(_) => {
                    panic!("Prefix not supported")
                }
                Component::RootDir => {
                    relative = origin.clone();
                }
                Component::CurDir => {
                    // do nothing
                }
                Component::ParentDir => {
                    if &relative == origin {
                        panic!("Can't use .. from root of workspace")
                    }
                }
                Component::Normal(part) => relative.push(part),
            }
        }
        self.root_dir.join(relative)
    }

    pub fn is_protected(&self, path: &Path) -> bool {
        let guard = self
            .protected_path
            .read()
            .expect("Couldn't get protected paths");
        let resolved = self.resolve_path(path);
        guard.contains(&resolved)
    }

    fn protect_path(&self, file: &Path) -> Result<(), WorkspaceError> {
        if self.is_protected(file) {
            Err(WorkspaceError::PathProtected(file.to_path_buf()))
        } else {
            let mut guard = self.protected_path.write()?;
            let resolved = self.resolve_path(file);
            guard.insert(resolved);
            Ok(())
        }
    }

    pub fn create_file(&self, path: &Path) -> Result<RegularFile, WorkspaceError> {
        if self.is_protected(path) {
            Err(WorkspaceError::PathProtected(path.to_path_buf()))
        } else {
            let path = self.resolve_path(path);
            debug!("resolved path to {:?}", path);
            let true_path = self.root_dir.join(path);
            debug!("creating path at {:?}", true_path);
            if let Some(parent) = true_path.parent() {
                create_dir_all(parent)?;
            }
            RegularFile::with_options(
                true_path,
                OpenOptions::new().read(true).write(true).create(true),
            )
            .map_err(WorkspaceError::from)
        }
    }

    pub fn as_dir(&self) -> Dir {
        self.dir("").unwrap()
    }

    pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
        self.root_dir.join(path)
    }
}

impl WorkspaceEntry for Workspace {
    fn into_absolute_path(self) -> WorkspaceResult<PathBuf> {
        std::fs::canonicalize(self.root_dir).map_err(|e| e.into())
    }
}

impl WorkspaceDirectory for Workspace {
    fn my_workspace(&self) -> &Workspace {
        self
    }

    fn rel_path(&self) -> PathBuf {
        PathBuf::new()
    }

    fn file(&self, file: &str) -> WorkspaceResult<RegularFile> {
        let file_path = PathBuf::from(file);
        self.create_file(&file_path)
    }

    fn dir(&self, name: &str) -> WorkspaceResult<Dir> {
        let dir_path = PathBuf::from(name);
        if self.is_protected(&dir_path) {
            return Err(WorkspaceError::PathProtected(dir_path));
        }
        let resolved = self.resolve_path(&dir_path);
        std::fs::create_dir_all(resolved)?;
        Ok(Dir {
            workspace: self,
            dir_path,
        })
    }

    fn protected_dir(&self, name: &str) -> WorkspaceResult<Dir> {
        let output = self.dir(name)?;
        self.protect_path(&output.rel_path())?;
        Ok(output)
    }

    fn protected_file(&self, name: &str) -> WorkspaceResult<RegularFile> {
        let output = self.file(name)?;
        let path = Path::new(name);
        self.protect_path(path)?;
        Ok(output)
    }
}

pub struct Dir<'w> {
    workspace: &'w Workspace,
    dir_path: PathBuf,
}

impl WorkspaceEntry for Dir<'_> {
    fn into_absolute_path(self) -> WorkspaceResult<PathBuf> {
        std::fs::canonicalize(self.workspace.resolve_path(&self.dir_path)).map_err(|e| e.into())
    }
}

impl<'w> WorkspaceDirectory for Dir<'w> {
    fn my_workspace(&self) -> &Workspace {
        self.workspace
    }

    fn rel_path(&self) -> PathBuf {
        self.dir_path.clone()
    }

    fn file(&self, file: &str) -> WorkspaceResult<RegularFile> {
        let file_path = self.dir_path.join(file);
        self.workspace.create_file(&file_path)
    }

    fn dir(&self, name: &str) -> WorkspaceResult<Dir> {
        let dir_path = self.dir_path.join(name);
        std::fs::create_dir(self.workspace.resolve_path(&dir_path))?;
        if self.workspace.is_protected(&dir_path) {
            return Err(WorkspaceError::PathProtected(dir_path));
        }
        Ok(Dir {
            workspace: self.workspace,
            dir_path,
        })
    }

    fn protected_dir(&self, name: &str) -> WorkspaceResult<Dir> {
        let output = self.dir(name)?;
        self.workspace.protect_path(&output.rel_path())?;
        Ok(output)
    }

    fn protected_file(&self, name: &str) -> WorkspaceResult<RegularFile> {
        let output = self.file(name)?;
        let path = Path::new(name);
        self.workspace.protect_path(path)?;
        Ok(output)
    }
}

/// The default workspaces provide access common workspaces used within assemble
pub mod default_workspaces {
    use crate::workspace::Workspace;
    use once_cell::sync::Lazy;
    use std::env;
    use std::ops::{Deref, DerefMut};
    use std::path::PathBuf;

    /// The environment variable checked for home directory of assemble.
    pub const ASSEMBLE_HOME_VAR: &str = "ASSEMBLE_HOME";
    const ASSEMBLE_HOME_DIR_NAME: &str = ".assemble";

    /// Provides access to the instance of the Assemble home workspace
    pub static ASSEMBLE_HOME: Lazy<AssembleHome> = Lazy::new(AssembleHome::default);

    /// Provide access to the Home workspace of the assemble application. This value
    /// is determined by the environment variable `ASSEMBLE_HOME`. If this variable is not set,
    /// `$HOME/.assemble` is used.
    #[derive(Debug)]
    pub struct AssembleHome(Workspace);

    impl AssembleHome {
        /// Gets an instance of [`AssembleHome`](Self).
        ///
        /// # Panic
        ///
        /// Will panic if `ASSEMBLE_HOME` and `HOME` isn't set.
        ///
        /// Will panic if the location doesn't exist and can't be created.
        ///
        /// Will panic if the location already exists but is a file.
        fn default() -> Self {
            let location = env::var_os(ASSEMBLE_HOME_VAR).map_or_else(
                || {
                    let home = dirs::home_dir()
                        .expect("HOME variable must be set is ASSEMBLE_HOME is not");
                    let path = home;
                    path.join(ASSEMBLE_HOME_DIR_NAME)
                },
                PathBuf::from,
            );
            trace!("location = {:?}", location);
            if !location.exists() {
                std::fs::create_dir_all(&location).unwrap();
            } else if location.is_file() {
                panic!(
                    "Can not use assemble home at {:?} because it already exists as a file",
                    location
                );
            }

            let workspace = Workspace::new(location);
            trace!("ASSEMBLE_HOME workspace = {:?}", workspace);
            Self(workspace)
        }
    }

    impl Deref for AssembleHome {
        type Target = Workspace;

        fn deref(&self) -> &Self::Target {
            &self.0
        }
    }

    impl DerefMut for AssembleHome {
        fn deref_mut(&mut self) -> &mut Self::Target {
            &mut self.0
        }
    }

    #[cfg(test)]
    mod tests {
        use crate::file_collection::FileCollection;

        use crate::ASSEMBLE_HOME;

        #[test]
        fn assemble_home_exists() {
            let path_buf = ASSEMBLE_HOME.path();
            assert!(!path_buf.as_os_str().is_empty(), "ASSEMBLE_HOME is empty");
            println!("path = {:?}", path_buf);
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::workspace::{Workspace, WorkspaceDirectory};

    #[test]
    fn create_file() {
        let workspace = Workspace::new_temp();
        let file = workspace.file("temp.text").unwrap();
        assert!(file.metadata().unwrap().is_file());
    }

    #[test]
    fn create_file_in_dir() {
        let workspace = Workspace::new_temp();
        let dir = workspace.dir("temp").unwrap();
        println!("absolute: {:?}", dir.absolute_path());
        assert!(dir.absolute_path().is_dir());
        let file = dir.file("tests.txt").unwrap();
        assert!(file.metadata().unwrap().is_file());
    }
}