Skip to main content

file_storage/path/mutate/
make_file.rs

1use crate::{Error, FilePath, FolderPath, Operation, Reason, StoragePath};
2
3impl StoragePath {
4    //! Make File
5
6    /// Makes the path a file path.
7    ///
8    /// If the path is a file, the file will be returned.
9    ///
10    /// If the path is a folder, the `file_name` will be appended then:
11    ///     1. If the path is a file, the file will be returned.
12    ///     2. If the `file_name` is empty or ends with the file-separator, it will be `None`.
13    pub fn make_file(self, file_name: &str) -> Result<FilePath, Error> {
14        if self.is_file() {
15            self.to_file()
16        } else {
17            let path: StoragePath = self.with_appended(file_name);
18            if path.is_file() {
19                path.to_file()
20            } else {
21                let original_len: usize = path.len() - file_name.len();
22                let path: StoragePath = unsafe { path.truncated(original_len) };
23                Err(Error::new(path, Operation::ModifyPath, Reason::Other))
24            }
25        }
26    }
27}
28
29impl FolderPath {
30    //! Make File
31
32    /// Makes the folder path a file path.
33    ///
34    /// Returns `None` if the `file_name` is empty or ends with the file-separator.
35    pub fn make_file(self, file_name: &str) -> Result<FilePath, Error> {
36        self.to_path().make_file(file_name)
37    }
38}
39
40#[cfg(test)]
41mod tests {
42    use crate::StoragePath;
43    use std::error::Error;
44
45    #[test]
46    fn make_file() -> Result<(), Box<dyn Error>> {
47        let path: StoragePath = StoragePath::unix_root();
48
49        let path: StoragePath = path.make_file("folder.txt")?.to_path();
50        assert_eq!(path.as_str(), "/folder.txt");
51
52        let path: StoragePath = path.make_file("ignored")?.to_path();
53        assert_eq!(path.as_str(), "/folder.txt");
54
55        Ok(())
56    }
57}