MCPcopy Create free account
hub / github.com/codeinred/untree / touch_file

Function touch_file

lib/functions.rs:36–59  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

34/// operation on the filesystem. If the file already exists, this function exits
35/// without affecting that file.
36pub 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
62pub fn touch_directory(path: &Path) -> Result<()> {

Callers 1

create_pathFunction · 0.85

Calls 1

onMethod · 0.80

Tested by

no test coverage detected