Fix saving files in single-file worktrees

Co-Authored-By: Nathan Sobo <nathan@zed.dev>
This commit is contained in:
Antonio Scandurra 2021-05-11 16:46:22 +02:00
parent d8eed53f13
commit d8f7054f28

View file

@ -166,16 +166,20 @@ impl Worktree {
path.starts_with(&self.snapshot.abs_path) path.starts_with(&self.snapshot.abs_path)
} }
fn absolutize(&self, path: &Path) -> PathBuf {
if path.file_name().is_some() {
self.snapshot.abs_path.join(path)
} else {
self.snapshot.abs_path.to_path_buf()
}
}
pub fn load_history( pub fn load_history(
&self, &self,
path: &Path, path: &Path,
ctx: &AppContext, ctx: &AppContext,
) -> impl Future<Output = Result<History>> { ) -> impl Future<Output = Result<History>> {
let abs_path = if path.file_name().is_some() { let abs_path = self.absolutize(path);
self.snapshot.abs_path.join(path)
} else {
self.snapshot.abs_path.to_path_buf()
};
ctx.background_executor().spawn(async move { ctx.background_executor().spawn(async move {
let mut file = std::fs::File::open(&abs_path)?; let mut file = std::fs::File::open(&abs_path)?;
let mut base_text = String::new(); let mut base_text = String::new();
@ -190,7 +194,7 @@ impl Worktree {
content: BufferSnapshot, content: BufferSnapshot,
ctx: &AppContext, ctx: &AppContext,
) -> Task<Result<()>> { ) -> Task<Result<()>> {
let abs_path = self.snapshot.abs_path.join(path); let abs_path = self.absolutize(path);
ctx.background_executor().spawn(async move { ctx.background_executor().spawn(async move {
let buffer_size = content.text_summary().bytes.min(10 * 1024); let buffer_size = content.text_summary().bytes.min(10 * 1024);
let file = std::fs::File::create(&abs_path)?; let file = std::fs::File::create(&abs_path)?;
@ -1444,6 +1448,31 @@ mod tests {
}); });
} }
#[test]
fn test_save_in_single_file_worktree() {
App::test_async((), |mut app| async move {
let dir = temp_tree(json!({
"file1": "the old contents",
}));
let tree = app.add_model(|ctx| Worktree::new(dir.path().join("file1"), ctx));
app.read(|ctx| tree.read(ctx).scan_complete()).await;
app.read(|ctx| assert_eq!(tree.read(ctx).file_count(), 1));
let buffer =
app.add_model(|ctx| Buffer::new(1, "a line of text.\n".repeat(10 * 1024), ctx));
let file = app.read(|ctx| tree.file("", ctx));
app.update(|ctx| {
assert_eq!(file.path().file_name(), None);
smol::block_on(file.save(buffer.read(ctx).snapshot(), ctx.as_ref())).unwrap();
});
let history = app.read(|ctx| file.load_history(ctx)).await.unwrap();
app.read(|ctx| assert_eq!(history.base_text.as_ref(), buffer.read(ctx).text()));
});
}
#[test] #[test]
fn test_rescan_simple() { fn test_rescan_simple() {
App::test_async((), |mut app| async move { App::test_async((), |mut app| async move {