~iptq/garbage

ref: 45fc4f1ee1bf4703e50eaed3e5f61ee06a7f6f81 garbage/src/utils.rs -rw-r--r-- 1.2 KiB
45fc4f1e — Michael Zhang add sourcehut build badge and remove deps.rs one 1 year, 3 months ago
                                                                                
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
use std::env;
use std::fs;
use std::path::{Path, PathBuf};

use anyhow::Result;
use walkdir::WalkDir;

pub fn into_absolute(path: impl AsRef<Path>) -> Result<PathBuf> {
    let path = path.as_ref();

    Ok(if !path.is_absolute() {
        env::current_dir()?.canonicalize()?.join(path)
    } else {
        path.to_path_buf()
    })
}

pub fn get_uid() -> u64 {
    unsafe { libc::getuid().into() }
}

/// This function recursively copies all the contents of src into dst.
pub fn recursive_copy(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> Result<()> {
    let src = src.as_ref();
    let dst = dst.as_ref();

    for entry in WalkDir::new(src)
        .contents_first(false)
        .follow_links(false)
        .same_file_system(true)
    {
        let entry = entry?;
        let path = entry.path();
        let relative_path = path.strip_prefix(src)?;

        // this must be the root
        if let None = relative_path.file_name() {
            fs::create_dir(dst)?;
            continue;
        }

        let target_name = dst.join(relative_path);
        if path.is_dir() {
            fs::create_dir(&target_name)?;
        } else {
            fs::copy(path, &target_name)?;
        }
    }

    Ok(())
}