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    /// The returned operation must be closed with `WriteOp::close` to commit the write.
13    ///
14    /// Returns `Err(FileAlreadyExists)` if the file already exists.
15    pub fn write(&self) -> Result<WriteOp, Error> {
16        if let Some(write) = self.write_if_not_exists()? {
17            Ok(write)
18        } else {
19            Err(Error::new(
20                self.clone(),
21                Write,
22                Reason::FileAlreadyExists,
23            ))
24        }
25    }
26
27    /// Opens a write operation to create a new file.
28    ///
29    /// The returned operation must be closed with `WriteOp::close` to commit the write.
30    ///
31    /// Returns `Ok(None)` if the file already exists.
32    pub fn write_if_not_exists(&self) -> Result<Option<WriteOp>, Error> {
33        if let Some(path) = LocalPath::new(self.path()) {
34            return path.write_if_not_exists().map(|op| {
35                op.map(|op| WriteOp {
36                    inner: WriteOpInner::Local(op),
37                })
38            });
39        }
40
41        #[cfg(feature = "r2")]
42        if let Some(path) = crate::R2Path::new(self.path()) {
43            return path.write_if_not_exists().map(|op| {
44                op.map(|op| WriteOp {
45                    inner: WriteOpInner::R2(op),
46                })
47            });
48        }
49
50        Err(Error::new(
51            self.clone(),
52            Write,
53            Reason::UnknownFileSystem,
54        ))
55    }
56}