summaryrefslogtreecommitdiff
path: root/server/common/src/fs_utils.rs
blob: 684e905322a59e8ea02142ebae36a0326dcd5de0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#![allow(dead_code)]

use std::io;
use std::path::Path;
use tokio::fs;

pub async fn create_dir_allow_existing(path: impl AsRef<Path>) -> io::Result<()> {
    match fs::create_dir(path.as_ref()).await {
        Ok(_) => Ok(()),
        Err(e) => {
            if e.kind() == io::ErrorKind::AlreadyExists {
                match fs::metadata(path).await {
                    Ok(metadata) => {
                        if metadata.is_dir() {
                            Ok(())
                        } else {
                            Err(e)
                        }
                    }
                    Err(e) => Err(e),
                }
            } else {
                Err(e)
            }
        }
    }
}

pub async fn remove_file_allow_not_found(path: impl AsRef<Path>) -> io::Result<()> {
    match fs::remove_file(path).await {
        Ok(_) => Ok(()),
        Err(e) => {
            if e.kind() == io::ErrorKind::NotFound {
                Ok(())
            } else {
                Err(e)
            }
        }
    }
}

pub async fn symlink_update_existing(
    src: impl AsRef<Path>,
    dst: impl AsRef<Path>,
) -> io::Result<()> {
    let src = src.as_ref();
    let dst = dst.as_ref();
    match fs::symlink(&src, &dst).await {
        Ok(_) => Ok(()),
        Err(e) => {
            if e.kind() == io::ErrorKind::AlreadyExists {
                let path = fs::read_link(&dst).await?;
                if path == src {
                    return Ok(());
                }
                fs::remove_file(&dst).await?;
                fs::symlink(&src, &dst).await
            } else {
                Err(e)
            }
        }
    }
}