summaryrefslogtreecommitdiff
path: root/server/common/src/fs_utils.rs
blob: 7905d01d29ff2d8e94634038281bb76e62c02bb2 (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
#![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).await {
        Ok(_) => Ok(()),
        Err(e) => {
            if e.kind() == io::ErrorKind::AlreadyExists {
                Ok(())
            } 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)
            }
        }
    }
}