Skip to main content

file_storage/op/file/write/
write.rs

1use crate::op::WriteOpInner;
2use crate::system::LocalPath;
3use crate::Operation::Write;
4use crate::Reason;
5use crate::{Error, FilePath, WriteOp};
6
7impl FilePath {
8    //! Write
9
10    /// Opens a write operation to the file.
11    ///
12    /// Returns `Err(FileAlreadyExists)` if the file already exists.
13    pub fn write(&self) -> Result<WriteOp, Error> {
14        if let Some(write) = self.write_if_not_exists()? {
15            Ok(write)
16        } else {
17            Err(Error::new(
18                self.clone(),
19                Write,
20                Reason::FileAlreadyExists,
21            ))
22        }
23    }
24
25    /// Opens a write operation to create a new file.
26    ///
27    /// Returns `Ok(None)` if the file already exists.
28    pub fn write_if_not_exists(&self) -> Result<Option<WriteOp>, Error> {
29        if let Some(path) = LocalPath::new(self.path()) {
30            return path.write_if_not_exists().map(|op| {
31                op.map(|op| WriteOp {
32                    inner: WriteOpInner::Local(op),
33                })
34            });
35        }
36
37        #[cfg(feature = "r2")]
38        if let Some(path) = crate::R2Path::new(self.path()) {
39            return path.write_if_not_exists().map(|op| {
40                op.map(|op| WriteOp {
41                    inner: WriteOpInner::R2(op),
42                })
43            });
44        }
45
46        Err(Error::new(
47            self.clone(),
48            Write,
49            Reason::UnknownFileSystem,
50        ))
51    }
52}