uv_fs/cachedir.rs
1//! Vendored from cachedir 0.3.1 to replace `std::fs` with `fs_err`.
2
3use std::io::Write;
4use std::{io, path};
5
6/// The `CACHEDIR.TAG` file header as defined by the [specification](https://bford.info/cachedir/).
7const HEADER: &[u8; 43] = b"Signature: 8a477f597d28d172789f06886806bc55";
8
9/// Adds a tag to the specified `directory`.
10///
11/// Will return an error if:
12///
13/// * The `directory` exists and contains a `CACHEDIR.TAG` file, regardless of its content.
14/// * The file can't be created for any reason (the `directory` doesn't exist, permission error,
15/// can't write to the file etc.)
16pub fn add_tag<P: AsRef<path::Path>>(directory: P) -> io::Result<()> {
17 let directory = directory.as_ref();
18 match fs_err::OpenOptions::new()
19 .write(true)
20 .create_new(true)
21 .open(directory.join("CACHEDIR.TAG"))
22 {
23 Ok(mut cachedir_tag) => cachedir_tag.write_all(HEADER),
24 Err(e) => Err(e),
25 }
26}
27
28/// Ensures the tag exists in `directory`.
29///
30/// This function considers the `CACHEDIR.TAG` file in `directory` existing, regardless of its
31/// content, as a success.
32///
33/// Will return an error if The tag file doesn't exist and can't be created for any reason
34/// (the `directory` doesn't exist, permission error, can't write to the file etc.).
35pub fn ensure_tag<P: AsRef<path::Path>>(directory: P) -> io::Result<()> {
36 match add_tag(&directory) {
37 Err(e) => match e.kind() {
38 io::ErrorKind::AlreadyExists => Ok(()),
39 // If it exists, but we can't write to it for some reason don't fail
40 io::ErrorKind::PermissionDenied if directory.as_ref().join("CACHEDIR.TAG").exists() => {
41 Ok(())
42 }
43 _ => Err(e),
44 },
45 other => other,
46 }
47}