simics_package/util/
mod.rs

1// Copyright (C) 2024 Intel Corporation
2// SPDX-License-Identifier: Apache-2.0
3
4//! Utilities helpful for packaging modules
5
6use crate::{Error, Result};
7use std::{
8    fs::{copy, create_dir_all},
9    path::{Path, PathBuf},
10};
11use walkdir::WalkDir;
12
13/// Recursively list all files in a directory
14pub fn recursive_directory_listing<P>(directory: P) -> Vec<PathBuf>
15where
16    P: AsRef<Path>,
17{
18    WalkDir::new(directory.as_ref())
19        .into_iter()
20        .filter_map(|p| p.ok())
21        .map(|p| p.path().to_path_buf())
22        .filter(|p| p.is_file())
23        .collect::<Vec<_>>()
24}
25
26/// Copy the contents of one directory to another, recursively, overwriting files if they exist but
27/// without replacing directories or their contents if they already exist
28pub fn copy_dir_contents<P>(src_dir: P, dst_dir: P) -> Result<()>
29where
30    P: AsRef<Path>,
31{
32    let src_dir = src_dir.as_ref().to_path_buf();
33
34    if !src_dir.is_dir() {
35        return Err(Error::NotADirectory {
36            path: src_dir.clone(),
37        });
38    }
39
40    let dst_dir = dst_dir.as_ref().to_path_buf();
41
42    if !dst_dir.is_dir() {
43        create_dir_all(&dst_dir)?;
44    }
45
46    for (src, dst) in WalkDir::new(&src_dir)
47        .into_iter()
48        .filter_map(|p| p.ok())
49        .filter_map(|p| {
50            let src = p.path().to_path_buf();
51            match src.strip_prefix(&src_dir) {
52                Ok(suffix) => Some((src.clone(), dst_dir.join(suffix))),
53                Err(_) => None,
54            }
55        })
56    {
57        if src.is_dir() {
58            create_dir_all(&dst)?;
59        } else if src.is_file() {
60            copy(&src, &dst)?;
61        }
62    }
63
64    Ok(())
65}