use crate::{
ByteRange, Occurrence, Op, Source, content_hash,
position::{self, Position, PositionEncoding},
uri,
};
use schemars::JsonSchema;
use serde::Deserialize;
use std::{collections::BTreeMap, path::PathBuf};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, JsonSchema)]
pub struct Range {
pub start: Position,
pub end: Position,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct TextEdit {
pub range: Range,
pub new_text: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, JsonSchema)]
pub struct TextDocumentIdentifier {
pub uri: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct TextDocumentEdit {
pub text_document: TextDocumentIdentifier,
pub edits: Vec<TextEdit>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, JsonSchema)]
pub struct CreateFile {
pub uri: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct RenameFile {
pub old_uri: String,
pub new_uri: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, JsonSchema)]
pub struct DeleteFile {
pub uri: String,
}
#[derive(Debug, Clone, PartialEq, Eq, JsonSchema)]
#[serde(untagged)]
pub enum DocumentChange {
Edit(TextDocumentEdit),
Create(CreateFile),
Rename(RenameFile),
Delete(DeleteFile),
}
impl<'de> Deserialize<'de> for DocumentChange {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = serde_json::Value::deserialize(deserializer)?;
let kind = value
.get("kind")
.and_then(serde_json::Value::as_str)
.map(str::to_string);
from_kind(kind.as_deref(), value).map_err(serde::de::Error::custom)
}
}
fn from_kind(
kind: Option<&str>,
value: serde_json::Value,
) -> Result<DocumentChange, serde_json::Error> {
match kind {
Some("create") => serde_json::from_value(value).map(DocumentChange::Create),
Some("rename") => serde_json::from_value(value).map(DocumentChange::Rename),
Some("delete") => serde_json::from_value(value).map(DocumentChange::Delete),
_ => serde_json::from_value(value).map(DocumentChange::Edit),
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct WorkspaceEdit {
#[serde(default)]
pub changes: Option<BTreeMap<String, Vec<TextEdit>>>,
#[serde(default)]
pub document_changes: Option<Vec<DocumentChange>>,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum WorkspaceEditError {
#[error("bad file URI `{uri}`")]
BadUri {
uri: String,
},
#[error("{}: {message}", path.display())]
Unreadable {
path: PathBuf,
message: String,
},
#[error("{}: position {line}:{character} is out of range", path.display())]
BadPosition {
path: PathBuf,
line: u32,
character: u32,
},
}
pub fn to_ops(
edit: &WorkspaceEdit,
encoding: PositionEncoding,
source: &dyn Source,
) -> Result<Vec<Op>, WorkspaceEditError> {
if let Some(changes) = &edit.document_changes {
return flatten(
changes
.iter()
.map(|change| document_change_ops(change, encoding, source)),
);
}
match &edit.changes {
Some(changes) => flatten(
changes
.iter()
.map(|(uri, edits)| text_edit_ops(uri, edits, encoding, source)),
),
None => Ok(Vec::new()),
}
}
fn flatten(
results: impl Iterator<Item = Result<Vec<Op>, WorkspaceEditError>>,
) -> Result<Vec<Op>, WorkspaceEditError> {
let mut ops = Vec::new();
for result in results {
ops.extend(result?);
}
Ok(ops)
}
fn document_change_ops(
change: &DocumentChange,
encoding: PositionEncoding,
source: &dyn Source,
) -> Result<Vec<Op>, WorkspaceEditError> {
match change {
DocumentChange::Edit(edit) => {
text_edit_ops(&edit.text_document.uri, &edit.edits, encoding, source)
}
DocumentChange::Create(create) => Ok(vec![Op::Create {
path: path_of(&create.uri)?,
text: String::new(),
}]),
DocumentChange::Rename(rename) => Ok(vec![Op::Move {
path: path_of(&rename.old_uri)?,
to: path_of(&rename.new_uri)?,
expect_hash: None,
}]),
DocumentChange::Delete(delete) => Ok(vec![Op::Delete {
path: path_of(&delete.uri)?,
expect_hash: None,
}]),
}
}
fn text_edit_ops(
uri: &str,
edits: &[TextEdit],
encoding: PositionEncoding,
source: &dyn Source,
) -> Result<Vec<Op>, WorkspaceEditError> {
let path = path_of(uri)?;
let text = read(&path, source)?;
let hash = content_hash(&text);
edits
.iter()
.map(|edit| text_edit_op(&path, &text, edit, encoding, &hash))
.collect()
}
fn read(path: &std::path::Path, source: &dyn Source) -> Result<String, WorkspaceEditError> {
source
.read(path)
.map_err(|message| unreadable(path, message))?
.ok_or_else(|| unreadable(path, "file not found".to_string()))
}
fn unreadable(path: &std::path::Path, message: String) -> WorkspaceEditError {
WorkspaceEditError::Unreadable {
path: path.to_path_buf(),
message,
}
}
fn text_edit_op(
path: &std::path::Path,
text: &str,
edit: &TextEdit,
encoding: PositionEncoding,
hash: &str,
) -> Result<Op, WorkspaceEditError> {
let range = byte_range(path, text, edit.range, encoding)?;
Ok(Op::Replace {
path: path.to_path_buf(),
find: None,
range: Some(range),
pattern: None,
replace: edit.new_text.clone(),
occurrence: Occurrence::default(),
target: None,
expect_hash: Some(hash.to_string()),
})
}
fn byte_range(
path: &std::path::Path,
text: &str,
range: Range,
encoding: PositionEncoding,
) -> Result<ByteRange, WorkspaceEditError> {
let start =
position::to_byte(text, range.start, encoding).ok_or_else(|| bad(path, range.start))?;
let end = position::to_byte(text, range.end, encoding).ok_or_else(|| bad(path, range.end))?;
Ok(ByteRange { start, end })
}
fn bad(path: &std::path::Path, position: Position) -> WorkspaceEditError {
WorkspaceEditError::BadPosition {
path: path.to_path_buf(),
line: position.line,
character: position.character,
}
}
fn path_of(target: &str) -> Result<PathBuf, WorkspaceEditError> {
uri::to_path(target).map_err(|uri| WorkspaceEditError::BadUri { uri })
}