pub mod edit;
pub mod edit_format;
pub mod glob;
pub mod grep;
pub mod list_dir;
pub mod read;
pub mod write;
pub mod write_files;
pub use edit::EditTool;
pub use glob::GlobTool;
pub use grep::GrepTool;
pub use list_dir::ListDirTool;
pub use read::ReadFileTool;
pub use write::WriteFileTool;
pub use write_files::{WRITE_FILES_TOOL_NAME, WriteFilesTool};
use std::path::{Path, PathBuf};
use thiserror::Error;
#[derive(Debug, Error)]
pub enum FsError {
#[error("path escapes working directory: {0}")]
PathTraversal(PathBuf),
#[error("not found: {0}")]
NotFound(PathBuf),
#[error("not a directory: {0}")]
NotADirectory(PathBuf),
#[error("glob: invalid pattern '{pattern}': {reason}")]
GlobPattern { pattern: String, reason: String },
#[error("grep: invalid pattern '{pattern}': {reason}")]
GrepPattern { pattern: String, reason: String },
#[error("file too large ({bytes} bytes, max {max} bytes): {path}")]
FileTooLarge { path: PathBuf, bytes: u64, max: u64 },
#[error("edit: old_string not found in {path}")]
EditNotFound { path: PathBuf },
#[error("edit: old_string is ambiguous ({count} matches) in {path}")]
EditAmbiguous { path: PathBuf, count: usize },
#[error(
"edit: Parity mode requires a unified-diff edit (provide 'diff'); \
SEARCH/REPLACE and whole-file are not accepted under Parity for {path}"
)]
ParityDiffRequired { path: PathBuf },
#[error("edit: invalid unified diff: {reason}")]
DiffHunkHeader { reason: String },
#[error("edit: diff context mismatch in {path} near original line {line}: {reason}")]
DiffContextMismatch {
path: PathBuf,
line: usize,
reason: String,
},
#[error("io error on {path}: {source}")]
Io {
path: PathBuf,
#[source]
source: std::io::Error,
},
}
impl FsError {
pub(crate) fn io(path: impl Into<PathBuf>, source: std::io::Error) -> Self {
FsError::Io {
path: path.into(),
source,
}
}
}
pub(crate) fn scoped_path(base_dir: &Path, raw_path: &Path) -> Result<PathBuf, FsError> {
let joined = if raw_path.is_absolute() {
raw_path.to_path_buf()
} else {
base_dir.join(raw_path)
};
let canonical_base = std::fs::canonicalize(base_dir).map_err(|e| FsError::io(base_dir, e))?;
let resolved = resolve_candidate(&canonical_base, &joined)?;
if !resolved.starts_with(&canonical_base) {
return Err(FsError::PathTraversal(raw_path.to_path_buf()));
}
Ok(resolved)
}
fn resolve_candidate(_canonical_base: &Path, candidate: &Path) -> Result<PathBuf, FsError> {
if let Ok(c) = std::fs::canonicalize(candidate) {
return Ok(c);
}
let mut existing = candidate.to_path_buf();
let mut tail = std::collections::VecDeque::new();
loop {
if existing.exists() {
break;
}
match existing.file_name() {
Some(name) => {
tail.push_front(name.to_owned());
existing = existing
.parent()
.unwrap_or(existing.as_path())
.to_path_buf();
}
None => break,
}
}
let mut resolved = if existing.exists() {
std::fs::canonicalize(&existing).unwrap_or(existing)
} else {
existing
};
for component in tail {
resolved.push(component);
}
Ok(normalize_path(&resolved))
}
fn normalize_path(path: &Path) -> PathBuf {
let mut components = Vec::new();
for component in path.components() {
use std::path::Component;
match component {
Component::Prefix(p) => components.push(Component::Prefix(p).as_os_str().to_owned()),
Component::RootDir => {
components.clear();
components.push(std::ffi::OsString::from("/"));
}
Component::CurDir => {}
Component::ParentDir => {
let last_is_root = components
.last()
.map(|c| c.as_encoded_bytes() == b"/")
.unwrap_or(false);
if !components.is_empty() && !last_is_root {
components.pop();
}
}
Component::Normal(n) => components.push(n.to_owned()),
}
}
let mut out = PathBuf::new();
for (i, c) in components.iter().enumerate() {
if i == 0 && c.as_encoded_bytes() == b"/" {
out.push("/");
} else {
out.push(c);
}
}
out
}
#[cfg(test)]
mod tests {
use std::path::Path;
use super::*;
#[test]
fn scoped_path_accepts_relative_inside_dir() {
let tmp = tempfile::tempdir().expect("tempdir");
let canonical_tmp = std::fs::canonicalize(tmp.path()).expect("canonicalize tmp");
let resolved = scoped_path(tmp.path(), Path::new("foo.txt")).expect("should accept");
assert!(
resolved.starts_with(&canonical_tmp),
"resolved {resolved:?} must be inside canonical tmp {canonical_tmp:?}"
);
}
#[test]
fn scoped_path_rejects_parent_traversal() {
let tmp = tempfile::tempdir().expect("tempdir");
let err = scoped_path(tmp.path(), Path::new("../etc/passwd"));
assert!(
matches!(err, Err(FsError::PathTraversal(_))),
"expected PathTraversal, got {err:?}"
);
}
#[test]
fn scoped_path_accepts_absolute_inside_dir() {
let tmp = tempfile::tempdir().expect("tempdir");
let canonical_tmp = std::fs::canonicalize(tmp.path()).expect("canonicalize tmp");
let abs = canonical_tmp.join("subdir").join("file.py");
let resolved = scoped_path(tmp.path(), &abs).expect("should accept absolute inside dir");
assert!(
resolved.starts_with(&canonical_tmp),
"resolved {resolved:?} must be inside canonical tmp {canonical_tmp:?}"
);
}
#[test]
fn scoped_path_rejects_absolute_outside_dir() {
let tmp = tempfile::tempdir().expect("tempdir");
let err = scoped_path(tmp.path(), Path::new("/etc/passwd"));
assert!(
matches!(err, Err(FsError::PathTraversal(_))),
"expected PathTraversal, got {err:?}"
);
}
}