Create document if it doesn't exist on save

pull/125/head
Wojciech Kępka 4 years ago committed by Ivan Tham
parent 392631b21d
commit 14f511da93

@ -104,6 +104,10 @@ pub fn normalize_path(path: &Path) -> PathBuf {
ret ret
} }
pub fn canonicalize_path(path: &Path) -> std::io::Result<PathBuf> {
std::env::current_dir().map(|current_dir| normalize_path(&current_dir.join(path)))
}
use helix_lsp::lsp; use helix_lsp::lsp;
use url::Url; use url::Url;
@ -133,13 +137,14 @@ impl Document {
// TODO: async fn? // TODO: async fn?
pub fn load(path: PathBuf) -> Result<Self, Error> { pub fn load(path: PathBuf) -> Result<Self, Error> {
use std::{env, fs::File, io::BufReader}; use std::{fs::File, io::BufReader};
let _current_dir = env::current_dir()?;
let file = File::open(path.clone()).context(format!("unable to open {:?}", path))?;
let doc = Rope::from_reader(BufReader::new(file))?;
// TODO: create if not found let doc = if !path.exists() {
Rope::from("\n")
} else {
let file = File::open(&path).context(format!("unable to open {:?}", path))?;
Rope::from_reader(BufReader::new(file))?
};
let mut doc = Self::new(doc); let mut doc = Self::new(doc);
// set the path and try detecting the language // set the path and try detecting the language
@ -192,6 +197,13 @@ impl Document {
async move { async move {
use tokio::{fs::File, io::AsyncWriteExt}; use tokio::{fs::File, io::AsyncWriteExt};
if let Some(parent) = path.parent() {
if !parent.exists() {
return Err(Error::msg(
"can't save file, parent directory does not exist",
));
}
}
let mut file = File::create(path).await?; let mut file = File::create(path).await?;
// write all the rope chunks to file // write all the rope chunks to file
@ -220,16 +232,11 @@ impl Document {
} }
pub fn set_path(&mut self, path: &Path) -> Result<(), std::io::Error> { pub fn set_path(&mut self, path: &Path) -> Result<(), std::io::Error> {
// canonicalize path to absolute value let path = canonicalize_path(path)?;
let current_dir = std::env::current_dir()?;
let path = normalize_path(&current_dir.join(path)); // if parent doesn't exist we still want to open the document
// and error out when document is saved
if let Some(parent) = path.parent() { self.path = Some(path);
// TODO: return error as necessary
if parent.exists() {
self.path = Some(path);
}
}
// try detecting the language based on filepath // try detecting the language based on filepath
self.detect_language(); self.detect_language();

@ -137,7 +137,7 @@ impl Editor {
} }
pub fn open(&mut self, path: PathBuf, action: Action) -> Result<DocumentId, Error> { pub fn open(&mut self, path: PathBuf, action: Action) -> Result<DocumentId, Error> {
let path = std::fs::canonicalize(path)?; let path = crate::document::canonicalize_path(&path)?;
let id = self let id = self
.documents() .documents()

Loading…
Cancel
Save