Skip to main content

pg_embedded_setup_unpriv/cache/operations/
copy.rs

1//! File and directory copy operations for the binary cache.
2//!
3//! Provides recursive directory copying with permission preservation.
4
5use std::{fs, io, path::Path};
6
7use camino::Utf8Path;
8use color_eyre::eyre::Context;
9use tracing::debug;
10
11use crate::error::BootstrapResult;
12
13/// Observability target for cache operations.
14const LOG_TARGET: &str = "pg_embed::cache";
15
16/// Copies cached binaries to the target installation directory.
17///
18/// Performs a recursive copy of the source directory contents to the target,
19/// preserving directory structure and file permissions.
20///
21/// # Arguments
22///
23/// * `source` - Source directory containing cached binaries
24/// * `target` - Target installation directory
25///
26/// # Errors
27///
28/// Returns an error if:
29/// - The source directory does not exist or cannot be read
30/// - The target directory cannot be created
31/// - Any file copy operation fails
32///
33/// # Examples
34///
35/// ```no_run
36/// use camino::Utf8Path;
37/// use pg_embedded_setup_unpriv::cache::copy_from_cache;
38///
39/// let source = Utf8Path::new("/home/user/.cache/pg-embedded/binaries/17.4.0");
40/// let target = Utf8Path::new("/tmp/sandbox/install");
41/// copy_from_cache(source, target)?;
42/// # Ok::<(), color_eyre::Report>(())
43/// ```
44pub fn copy_from_cache(source: &Utf8Path, target: &Utf8Path) -> BootstrapResult<()> {
45    log_copy_start(source, target);
46
47    fs::create_dir_all(target)
48        .with_context(|| format!("failed to create target directory for cache copy: {target}"))?;
49
50    copy_dir_recursive(source.as_std_path(), target.as_std_path())
51        .with_context(|| format!("failed to copy cached binaries from {source} to {target}"))?;
52
53    log_copy_complete(source, target);
54    Ok(())
55}
56
57/// Logs the start of a cache copy operation.
58fn log_copy_start(source: &Utf8Path, target: &Utf8Path) {
59    debug!(
60        target: LOG_TARGET,
61        source = %source,
62        target = %target,
63        "copying binaries from cache"
64    );
65}
66
67/// Logs the completion of a cache copy operation.
68fn log_copy_complete(source: &Utf8Path, target: &Utf8Path) {
69    debug!(
70        target: LOG_TARGET,
71        source = %source,
72        target = %target,
73        "cache copy completed"
74    );
75}
76
77/// Recursively copies a directory and its contents.
78///
79/// Preserves directory structure and copies file metadata where possible.
80pub(crate) fn copy_dir_recursive(src: &Path, dst: &Path) -> io::Result<()> {
81    if !dst.exists() {
82        fs::create_dir_all(dst)?;
83    }
84
85    for dir_entry in fs::read_dir(src)? {
86        let entry = dir_entry?;
87        let file_type = entry.file_type()?;
88        let src_path = entry.path();
89        let dst_path = dst.join(entry.file_name());
90
91        if file_type.is_dir() {
92            copy_dir_recursive(&src_path, &dst_path)?;
93        } else if file_type.is_symlink() {
94            copy_symlink(&src_path, &dst_path)?;
95        } else {
96            copy_file_with_permissions(&src_path, &dst_path)?;
97        }
98    }
99
100    copy_permissions(src, dst);
101
102    Ok(())
103}
104
105/// Copies a file preserving its permissions.
106fn copy_file_with_permissions(src: &Path, dst: &Path) -> io::Result<()> {
107    fs::copy(src, dst)?;
108    copy_permissions(src, dst);
109    Ok(())
110}
111
112/// Best-effort permission copy from source to destination.
113fn copy_permissions(src: &Path, dst: &Path) {
114    let Ok(metadata) = fs::metadata(src) else {
115        return;
116    };
117    if let Err(err) = fs::set_permissions(dst, metadata.permissions()) {
118        log_permission_copy_failure(src, dst, &err);
119    }
120}
121
122/// Logs a permission copy failure for debugging.
123fn log_permission_copy_failure(src: &Path, dst: &Path, err: &io::Error) {
124    debug!(
125        target: LOG_TARGET,
126        src = %src.display(),
127        dst = %dst.display(),
128        error = %err,
129        "failed to copy permissions (best effort)"
130    );
131}
132
133/// Copies a symbolic link.
134#[cfg(unix)]
135fn copy_symlink(src: &Path, dst: &Path) -> io::Result<()> {
136    let target = fs::read_link(src)?;
137    std::os::unix::fs::symlink(&target, dst)?;
138    Ok(())
139}
140
141#[cfg(not(unix))]
142fn copy_symlink(src: &Path, dst: &Path) -> io::Result<()> {
143    // On non-Unix, follow the symlink and copy the target.
144    // The symlink target is resolved by checking src directly (after following).
145    if src.is_file() {
146        fs::copy(src, dst)?;
147    } else if src.is_dir() {
148        copy_dir_recursive(src, dst)?;
149    } else {
150        return Err(io::Error::new(
151            io::ErrorKind::NotFound,
152            format!(
153                "symlink target does not exist or cannot be read: {}",
154                src.display()
155            ),
156        ));
157    }
158    Ok(())
159}