Atomically create a file, if it doesn't already exist. This is an atomic operation on the filesystem. If the file already exists, this function exits without affecting that file.
(path: &Path)
| 34 | /// operation on the filesystem. If the file already exists, this function exits |
| 35 | /// without affecting that file. |
| 36 | pub fn touch_file(path: &Path) -> Result<()> { |
| 37 | // create_new is used to implement creation + existence checking as an |
| 38 | // atomic filesystem operation. |
| 39 | |
| 40 | // create_new is used instead of create because the program should NOT |
| 41 | // attempt to open files that already exist. This could result in an |
| 42 | // exception being thrown if the file is locked by another program, or |
| 43 | // marked as read only. |
| 44 | |
| 45 | // write(true) is passed because new files must be created as |
| 46 | // write-accessible. Otherwise a permissions error is thrown. |
| 47 | |
| 48 | // See https://doc.rust-lang.org/std/fs/struct.OpenOptions.html#method.create for more details |
| 49 | match OpenOptions::new().write(true).create_new(true).open(path) { |
| 50 | Ok(_) => Ok(()), |
| 51 | Err(err) => match err.kind() { |
| 52 | // If the file already exists, that's fine - we don't need to take |
| 53 | // an action |
| 54 | AlreadyExists => Ok(()), |
| 55 | // Otherwise, we propagate the error forward |
| 56 | _ => Err(err).context(CreateFile.on(path))?, |
| 57 | }, |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | /// Create a directory, along with any parents that haven't been created |
| 62 | pub fn touch_directory(path: &Path) -> Result<()> { |