Skip to main content

file_storage/system/local/file/
write.rs

1use crate::system::{LocalPath, LocalWriteOp};
2use crate::{Error, Operation};
3use std::io::ErrorKind::AlreadyExists;
4
5impl<'a> LocalPath<'a> {
6    //! Write
7
8    /// Prepares a write operation.
9    fn prepare(&self) -> Result<(), Error> {
10        if let Some(parent) = std::path::Path::new(self.path).parent() {
11            match std::fs::create_dir_all(parent) {
12                Ok(()) => Ok(()),
13                Err(error) => Err(Error::from_source(
14                    self.path.clone(),
15                    Operation::Write,
16                    error,
17                )),
18            }
19        } else {
20            Ok(())
21        }
22    }
23
24    /// See `FilePath::write_if_not_exists`.
25    pub fn write_if_not_exists(&self) -> Result<Option<LocalWriteOp>, Error> {
26        self.prepare()?;
27
28        match std::fs::File::create_new(self.path) {
29            Ok(file) => Ok(Some(LocalWriteOp { file })),
30            Err(error) => {
31                if error.kind() == AlreadyExists {
32                    Ok(None)
33                } else {
34                    Err(Error::from_source(
35                        self.path.clone(),
36                        Operation::Write,
37                        error,
38                    ))
39                }
40            }
41        }
42    }
43}