Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions src/git.rs
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,27 @@ pub fn read_worktree_file(cwd: impl AsRef<Path>, rel_path: &str) -> Result<Vec<u
std::fs::read(&canonical).map_err(|_| GitError::FileNotFound)
}

/// Overwrites an existing working-tree file. Same path checks as
/// `read_worktree_file`; never creates new files.
pub fn write_worktree_file(cwd: impl AsRef<Path>, rel_path: &str, contents: &[u8]) -> Result<()> {
if !is_safe_repo_path(rel_path) {
return Err(GitError::InvalidRepoPath);
}
let root = root(cwd)?;
let canonical_root = root.canonicalize().map_err(|_| GitError::NoWorkdir)?;
let candidate = root.join(rel_path);
let canonical = candidate
.canonicalize()
.map_err(|_| GitError::FileNotFound)?;
if !canonical.starts_with(&canonical_root) {
return Err(GitError::InvalidRepoPath);
}
if !canonical.is_file() {
return Err(GitError::FileNotFound);
}
std::fs::write(&canonical, contents).map_err(|_| GitError::FileNotFound)
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -675,6 +696,27 @@ mod tests {
));
}

#[test]
fn write_worktree_file_overwrites_existing_files_only() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().canonicalize().unwrap();
git(&root, &["init", "-b", "main"]);
fs::write(root.join("existing.txt"), "before\n").unwrap();

write_worktree_file(&root, "existing.txt", b"after\n").unwrap();
assert_eq!(fs::read(root.join("existing.txt")).unwrap(), b"after\n");

assert!(matches!(
write_worktree_file(&root, "created.txt", b"nope"),
Err(GitError::FileNotFound)
));
assert!(!root.join("created.txt").exists());
assert!(matches!(
write_worktree_file(&root, "../outside.txt", b"nope"),
Err(GitError::InvalidRepoPath)
));
}

#[test]
fn read_worktree_file_rejects_symlink_escape() {
let outside = tempfile::tempdir().unwrap();
Expand Down
90 changes: 88 additions & 2 deletions src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use axum::{
IntoResponse, Response, Sse,
sse::{Event, KeepAlive},
},
routing::{delete, get, post},
routing::{delete, get, post, put},
};
use notify::{RecursiveMode, Watcher};
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -119,6 +119,12 @@ struct PullFileQuery {
side: Option<String>,
}

#[derive(Debug, Deserialize)]
struct WorktreeWriteBody {
path: String,
contents: String,
}

pub struct RunningServer {
pub router: Router,
_watcher: Option<notify::RecommendedWatcher>,
Expand Down Expand Up @@ -183,6 +189,7 @@ pub fn new(cfg: ServerConfig) -> anyhow::Result<RunningServer> {
)
.route("/api/patch/{org}/{repo}/{number}", get(handle_patch))
.route("/api/blob", get(handle_blob))
.route("/api/worktree-file", put(handle_write_worktree_file))
.route(
"/api/pull/{org}/{repo}/{number}/file",
get(handle_pull_file),
Expand Down Expand Up @@ -557,6 +564,24 @@ async fn handle_blob(State(state): State<AppState>, Query(query): Query<BlobQuer
}
}

/// Saves inline-editor contents to an existing working-tree file.
async fn handle_write_worktree_file(
State(state): State<AppState>,
Json(body): Json<WorktreeWriteBody>,
) -> Response {
let path = body.path.trim();
if path.is_empty() {
return error(StatusCode::BAD_REQUEST, "path is required");
}
if body.contents.len() > MAX_BLOB_BYTES {
return error(StatusCode::PAYLOAD_TOO_LARGE, "contents too large");
}
match git::write_worktree_file(&state.cwd, path, body.contents.as_bytes()) {
Ok(()) => StatusCode::NO_CONTENT.into_response(),
Err(err) => blob_error(err),
}
}

/// Fetches a single file's raw content from one side of a pull request, for
/// `loadDiffFiles` hydration of PR diffs.
async fn handle_pull_file(
Expand Down Expand Up @@ -836,6 +861,9 @@ fn start_watcher(
std::thread::spawn(move || {
// Repository handle for `git status` lookups; lives only on this thread.
let repo = git::discover(&status_cwd).ok();
// Previous status, so a file restored to HEAD (no longer in status)
// still triggers a refresh.
let mut last_status = repo.as_ref().and_then(|repo| git::status_map(repo).ok());
loop {
let mut pending: BTreeSet<String> = BTreeSet::new();
let mut git_state = false;
Expand All @@ -858,7 +886,11 @@ fn start_watcher(
Some(map) => changed_files_for_events(&pending, map),
None => changed_files_from_events(&pending),
};
let broadcast = !changed.is_empty() || git_state;
let reverted = last_status
.as_ref()
.is_some_and(|prev| !changed_files_for_events(&pending, prev).is_empty());
last_status = status;
let broadcast = !changed.is_empty() || reverted || git_state;
if broadcast {
let _ = events.send(());
if let Some(on_change) = &on_change {
Expand Down Expand Up @@ -1183,6 +1215,60 @@ mod tests {
assert!(!is_structurally_ignored(FsPath::new("/repo/my.git/x")));
}

#[test]
fn watcher_broadcasts_when_file_returns_to_head() {
use std::process::Command;
let dir = tempfile::tempdir().unwrap();
let root = dir.path().canonicalize().unwrap();
let git = |args: &[&str]| {
let ok = Command::new("git")
.args(args)
.current_dir(&root)
.status()
.unwrap()
.success();
assert!(ok, "git {args:?} failed");
};
git(&["init", "-q", "-b", "main"]);
std::fs::write(root.join("a.txt"), "base\n").unwrap();
git(&["add", "a.txt"]);
git(&[
"-c",
"user.email=t@t",
"-c",
"user.name=t",
"commit",
"-qm",
"init",
]);

let (events, mut rx) = broadcast::channel(16);
let _watcher = start_watcher(root.clone(), events, None).unwrap();
let expect_broadcast = |rx: &mut broadcast::Receiver<()>, what: &str| {
let deadline = std::time::Instant::now() + Duration::from_secs(10);
loop {
match rx.try_recv() {
Ok(()) => break,
Err(broadcast::error::TryRecvError::Empty)
if std::time::Instant::now() < deadline =>
{
std::thread::sleep(Duration::from_millis(20))
}
Err(err) => panic!("no broadcast after {what}: {err:?}"),
}
}
// Drain duplicate events before the next step.
std::thread::sleep(WATCH_DEBOUNCE * 4);
while rx.try_recv().is_ok() {}
};

std::fs::write(root.join("a.txt"), "edited\n").unwrap();
expect_broadcast(&mut rx, "modifying a.txt");
// Restoring HEAD content removes a.txt from status; still a change.
std::fs::write(root.join("a.txt"), "base\n").unwrap();
expect_broadcast(&mut rx, "restoring a.txt to HEAD");
}

#[test]
fn changed_files_for_events_intersects_status() {
let mut status = BTreeMap::new();
Expand Down
Loading
Loading