ctb_io_csc/
path_resolution.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Rsync-compatible path and trailing-slash resolution.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use std::path::PathBuf;
30
31/// A resolved copy task mapping a source root to a destination root.
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct ResolvedCopyTask {
34    /// The source root path as specified by the user.
35    pub source_root: PathBuf,
36    /// The computed target directory or file destination.
37    pub target_root: PathBuf,
38    /// Whether only the contents of the source directory should be copied,
39    /// rather than creating the source directory itself in the destination.
40    pub copy_contents_only: bool,
41}
42
43pub use ctb_io::file::path_has_trailing_slash;
44use ctb_io::file::resolve_existing_ancestors;
45
46/// Resolves a list of CLI paths (sources... destination) into discrete copy tasks.
47///
48/// Follows standard rsync trailing-slash conventions:
49/// - `src/ dest/`: copies contents of `src` into `dest/`.
50/// - `src dest/`: copies `src` into `dest/src`.
51/// - Multiple sources always require destination to be treated as a container directory.
52pub fn resolve_tasks(
53    paths: &[PathBuf],
54) -> Result<(Vec<ResolvedCopyTask>, PathBuf)> {
55    anyhow::ensure!(
56        paths.len() >= 2,
57        "At least one source path and one destination path are required"
58    );
59
60    let Some((dest_arg, sources)) = paths.split_last() else {
61        anyhow::bail!("Missing destination argument");
62    };
63    let dest_path = dest_arg.clone();
64
65    let dest_has_slash = path_has_trailing_slash(&dest_path);
66    let dest_is_dir = dest_path.is_dir();
67
68    let multiple_sources = sources.len() > 1;
69    let treat_dest_as_dir = dest_has_slash || dest_is_dir || multiple_sources;
70
71    let mut tasks = Vec::with_capacity(sources.len());
72
73    for source in sources {
74        let source_meta =
75            std::fs::symlink_metadata(source).with_context(|| {
76                format!("Source path does not exist: {}", source.display())
77            })?;
78        let src_has_slash = path_has_trailing_slash(source);
79        let src_is_dir = source_meta.is_dir();
80
81        if src_is_dir {
82            if src_has_slash {
83                // e.g. "csc a/ b/" -> copy contents of a directly into b
84                tasks.push(ResolvedCopyTask {
85                    source_root: source.clone(),
86                    target_root: dest_path.clone(),
87                    copy_contents_only: true,
88                });
89            } else if treat_dest_as_dir {
90                // e.g. "csc a b/" -> copy a into b/a
91                let dir_name = source
92                    .file_name()
93                    .context("Source directory has no file name component")?;
94                let target = dest_path.join(dir_name);
95                tasks.push(ResolvedCopyTask {
96                    source_root: source.clone(),
97                    target_root: target,
98                    copy_contents_only: false,
99                });
100            } else {
101                // e.g. "csc a b" where b does not exist -> copy a as b
102                tasks.push(ResolvedCopyTask {
103                    source_root: source.clone(),
104                    target_root: dest_path.clone(),
105                    copy_contents_only: false,
106                });
107            }
108        } else {
109            // Source is a regular file, symlink, or special file
110            if treat_dest_as_dir {
111                let file_name = source
112                    .file_name()
113                    .context("Source file has no file name component")?;
114                let target = dest_path.join(file_name);
115                tasks.push(ResolvedCopyTask {
116                    source_root: source.clone(),
117                    target_root: target,
118                    copy_contents_only: false,
119                });
120            } else {
121                // e.g. "csc file1 file2" -> copy file1 to file2
122                anyhow::ensure!(
123                    dest_path.file_name().is_some(),
124                    "Target path has no file name component: {}",
125                    dest_path.display()
126                );
127                tasks.push(ResolvedCopyTask {
128                    source_root: source.clone(),
129                    target_root: dest_path.clone(),
130                    copy_contents_only: false,
131                });
132            }
133        }
134    }
135
136    validate_task_overlap(&tasks)?;
137    Ok((tasks, dest_path))
138}
139
140pub(crate) fn validate_task_overlap(tasks: &[ResolvedCopyTask]) -> Result<()> {
141    for source_task in tasks {
142        let source_meta = std::fs::symlink_metadata(&source_task.source_root)?;
143        let source = resolve_existing_ancestors(&source_task.source_root)?;
144        for target_task in tasks {
145            let target = resolve_existing_ancestors(&target_task.target_root)?;
146            anyhow::ensure!(
147                source != target
148                    && !(source_meta.is_dir() && target.starts_with(&source))
149                    && !source.starts_with(&target),
150                "Source and destination overlap: {} -> {}",
151                source.display(),
152                target.display()
153            );
154            #[cfg(unix)]
155            if let Ok(target_meta) =
156                std::fs::symlink_metadata(&target_task.target_root)
157            {
158                use std::os::unix::fs::MetadataExt;
159                anyhow::ensure!(
160                    source_meta.dev() != target_meta.dev()
161                        || source_meta.ino() != target_meta.ino(),
162                    "Source and destination refer to the same inode"
163                );
164            }
165        }
166    }
167    Ok(())
168}
169
170#[cfg(test)]
171#[allow(
172    clippy::panic,
173    clippy::expect_used,
174    clippy::unwrap_used,
175    clippy::unwrap_in_result,
176    clippy::panic_in_result_fn,
177    clippy::indexing_slicing,
178    clippy::arithmetic_side_effects,
179    reason = "Standard repository test boilerplate"
180)]
181mod tests {
182    use super::*;
183    use std::path::Path;
184    use tempfile::tempdir;
185
186    #[crate::ctb_test]
187    fn test_trailing_slash_detection() {
188        assert!(path_has_trailing_slash(Path::new("a/")));
189        assert!(path_has_trailing_slash(Path::new("a/.")));
190        assert!(!path_has_trailing_slash(Path::new("a")));
191        assert!(!path_has_trailing_slash(Path::new("a/b")));
192    }
193
194    #[crate::ctb_test]
195    fn test_resolve_directory_with_and_without_slash() {
196        let temp = tempdir().expect("create tempdir");
197        let src_dir = temp.path().join("src_folder");
198        std::fs::create_dir(&src_dir).expect("create src dir");
199        let dest_dir = temp.path().join("dest_folder");
200        std::fs::create_dir(&dest_dir).expect("create dest dir");
201
202        // Case 1: src with trailing slash
203        let src_with_slash = PathBuf::from(format!("{}/", src_dir.display()));
204        let (tasks1, _) = resolve_tasks(&[src_with_slash, dest_dir.clone()])
205            .expect("resolve");
206        assert_eq!(tasks1.len(), 1);
207        assert!(tasks1[0].copy_contents_only);
208        assert_eq!(tasks1[0].target_root, dest_dir);
209
210        // Case 2: src without trailing slash, dest is existing dir
211        let (tasks2, _) = resolve_tasks(&[src_dir.clone(), dest_dir.clone()])
212            .expect("resolve");
213        assert_eq!(tasks2.len(), 1);
214        assert!(!tasks2[0].copy_contents_only);
215        assert_eq!(tasks2[0].target_root, dest_dir.join("src_folder"));
216    }
217
218    #[crate::ctb_test]
219    fn test_resolve_single_file() {
220        let temp = tempdir().expect("create tempdir");
221        let src_file = temp.path().join("file.txt");
222        std::fs::write(&src_file, b"content").expect("write file");
223        let dest_dir = temp.path().join("dest_folder");
224        std::fs::create_dir(&dest_dir).expect("create dest dir");
225
226        let (tasks, _) =
227            resolve_tasks(&[src_file, dest_dir.clone()]).expect("resolve");
228        assert_eq!(tasks.len(), 1);
229        assert_eq!(tasks[0].target_root, dest_dir.join("file.txt"));
230    }
231
232    #[crate::ctb_test]
233    fn test_reject_overlapping_copy_paths() {
234        let temp = tempdir().unwrap();
235        let source = temp.path().join("source");
236        std::fs::create_dir(&source).unwrap();
237        assert!(resolve_tasks(&[source.join(""), source.clone()]).is_err());
238        assert!(
239            resolve_tasks(&[source.clone(), source.join("nested/destination")])
240                .is_err()
241        );
242        assert!(!source.join("nested").exists());
243    }
244
245    #[cfg(unix)]
246    #[crate::ctb_test]
247    fn test_resolve_dangling_symlink_source() {
248        let temp = tempdir().unwrap();
249        let source = temp.path().join("dangling");
250        std::os::unix::fs::symlink("missing", &source).unwrap();
251        assert!(
252            resolve_tasks(&[source, temp.path().join("destination")]).is_ok()
253        );
254        assert!(!path_has_trailing_slash(Path::new("literal\\")));
255    }
256}