Skip to main content

agent_hub_runtime/core/
project_file_actions.rs

1//! File tree operations within an already authorized checkout.
2pub mod paste;
3use anyhow::{bail, Context, Result};
4use serde::Deserialize;
5use std::{
6    fs,
7    path::{Component, Path, PathBuf},
8};
9
10use super::{path_guard, project_worktrees};
11
12#[derive(Deserialize)]
13#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
14pub enum FileAction {
15    NewFile { name: String },
16    NewDirectory { name: String },
17    Rename { name: String },
18    Delete,
19}
20
21/// Reject links in every component, including links pointing inside the checkout.
22pub fn existing_path(root: &Path, relative: &str) -> Result<PathBuf> {
23    let path = project_worktrees::file_path(root, relative)?;
24    let mut current = root.to_path_buf();
25    for part in Path::new(relative).components() {
26        if part
27            .as_os_str()
28            .to_string_lossy()
29            .eq_ignore_ascii_case(".git")
30        {
31            bail!("Git metadata cannot be changed as a workspace file");
32        }
33        current.push(part);
34        if path_guard::is_link_or_reparse_point(&fs::symlink_metadata(&current)?) {
35            bail!("Linked files and directories cannot be used for this operation");
36        }
37    }
38    fs::symlink_metadata(&path).context("Workspace entry is no longer available")?;
39    Ok(path)
40}
41
42fn named_child(parent: &Path, name: &str) -> Result<PathBuf> {
43    let mut components = Path::new(name).components();
44    if name.trim().is_empty()
45        || name != name.trim()
46        || name.contains(['/', '\\'])
47        || name
48            .chars()
49            .any(|c| c.is_control() || matches!(c, ':' | '*' | '?' | '"' | '<' | '>' | '|'))
50        || name.ends_with('.')
51        || !matches!(components.next(), Some(Component::Normal(_)))
52        || components.next().is_some()
53        || name.eq_ignore_ascii_case(".git")
54    {
55        bail!("Enter a single file or directory name without path separators");
56    }
57    let target = parent.join(name);
58    if fs::symlink_metadata(&target).is_ok() {
59        bail!("An entry with this name already exists");
60    }
61    Ok(target)
62}
63
64// Refuse destructive operations on embedded repositories or linked checkouts.
65// Bound the scan so selecting a huge directory cannot monopolize the worker.
66fn protect_repositories(path: &Path) -> Result<()> {
67    let mut pending = vec![path.to_path_buf()];
68    let mut visited = 0;
69    while let Some(current) = pending.pop() {
70        let metadata = fs::symlink_metadata(&current)?;
71        if !metadata.is_dir() || path_guard::is_link_or_reparse_point(&metadata) {
72            continue;
73        }
74        for entry in fs::read_dir(current)? {
75            let entry = entry?;
76            visited += 1;
77            if visited > 100_000 {
78                bail!("Directory is too large; manage it in your file manager");
79            }
80            if entry
81                .file_name()
82                .to_string_lossy()
83                .eq_ignore_ascii_case(".git")
84            {
85                bail!("Directories containing Git metadata cannot be renamed or deleted here");
86            }
87            if entry.file_type()?.is_dir() {
88                pending.push(entry.path());
89            }
90        }
91    }
92    Ok(())
93}
94
95pub fn apply(root: &Path, relative: &str, action: FileAction) -> Result<String> {
96    static OPERATIONS: std::sync::Mutex<()> = std::sync::Mutex::new(());
97    let _guard = OPERATIONS.lock().unwrap_or_else(|error| error.into_inner());
98    let source = existing_path(root, relative)?;
99    let target = match action {
100        FileAction::NewFile { name } => {
101            let target = named_child(&source, &name)?;
102            fs::OpenOptions::new()
103                .write(true)
104                .create_new(true)
105                .open(&target)?;
106            target
107        }
108        FileAction::NewDirectory { name } => {
109            let target = named_child(&source, &name)?;
110            fs::create_dir(&target)?;
111            target
112        }
113        FileAction::Rename { name } => {
114            if relative.is_empty() {
115                bail!("The checkout root cannot be renamed");
116            }
117            protect_repositories(&source)?;
118            let target = named_child(source.parent().context("Missing parent directory")?, &name)?;
119            rename_without_replace(&source, &target)?;
120            target
121        }
122        FileAction::Delete => {
123            if relative.is_empty() {
124                bail!("The checkout root cannot be deleted");
125            }
126            protect_repositories(&source)?;
127            if source.is_dir() {
128                fs::remove_dir_all(&source)?;
129            } else {
130                fs::remove_file(&source)?;
131            }
132            source
133        }
134    };
135    Ok(target
136        .strip_prefix(root)?
137        .to_string_lossy()
138        .replace('\\', "/"))
139}
140
141// A preflight exists check alone would allow a concurrent writer to be overwritten.
142fn rename_without_replace(source: &Path, target: &Path) -> Result<()> {
143    #[cfg(any(target_os = "macos", target_os = "linux"))]
144    {
145        use std::{ffi::CString, os::unix::ffi::OsStrExt};
146        let source = CString::new(source.as_os_str().as_bytes())?;
147        let target = CString::new(target.as_os_str().as_bytes())?;
148        #[cfg(target_os = "macos")]
149        let result =
150            unsafe { libc::renamex_np(source.as_ptr(), target.as_ptr(), libc::RENAME_EXCL) };
151        #[cfg(target_os = "linux")]
152        let result = unsafe {
153            libc::renameat2(
154                libc::AT_FDCWD,
155                source.as_ptr(),
156                libc::AT_FDCWD,
157                target.as_ptr(),
158                libc::RENAME_NOREPLACE,
159            )
160        };
161        if result != 0 {
162            return Err(std::io::Error::last_os_error().into());
163        }
164        Ok(())
165    }
166    #[cfg(windows)]
167    {
168        use std::os::windows::ffi::OsStrExt;
169        use windows::{core::PCWSTR, Win32::Storage::FileSystem::MoveFileW};
170        let source: Vec<_> = source.as_os_str().encode_wide().chain(Some(0)).collect();
171        let target: Vec<_> = target.as_os_str().encode_wide().chain(Some(0)).collect();
172        // MoveFileW refuses an existing destination atomically, including races.
173        unsafe { MoveFileW(PCWSTR(source.as_ptr()), PCWSTR(target.as_ptr()))? };
174        Ok(())
175    }
176}
177
178#[cfg(test)]
179mod tests;