griz-core 0.2.0

Pure edit engine for griz: find, plan, match, diff, and merge without writing
Documentation
//! Converts an LSP `WorkspaceEdit` into griz [`Op`]s.
//!
//! Small serde structs of our own, not `lsp-types`: only the shapes griz
//! needs to turn edits from another tool into operations `plan` already
//! understands. `changes` and `documentChanges` combine `TextDocumentEdit`
//! (a file's text edits) with the resource operations `CreateFile`,
//! `RenameFile`, and `DeleteFile`.

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};

/// A half-open `[start, end)` span of positions.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, JsonSchema)]
pub struct Range {
    /// First position.
    pub start: Position,
    /// One past the last position.
    pub end: Position,
}

/// One text change within a file.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct TextEdit {
    /// Span to replace.
    pub range: Range,
    /// Replacement text.
    pub new_text: String,
}

/// Identifies the file a [`TextDocumentEdit`] changes.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, JsonSchema)]
pub struct TextDocumentIdentifier {
    /// `file://` URI of the document.
    pub uri: String,
}

/// Every edit to one file, applied together against its original text.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct TextDocumentEdit {
    /// File the edits apply to.
    pub text_document: TextDocumentIdentifier,
    /// Edits, each against the file's original text.
    pub edits: Vec<TextEdit>,
}

/// Creates a new, empty file.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, JsonSchema)]
pub struct CreateFile {
    /// `file://` URI to create.
    pub uri: String,
}

/// Renames a file. Becomes [`Op::Move`].
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct RenameFile {
    /// `file://` URI of the existing file.
    pub old_uri: String,
    /// `file://` URI it becomes.
    pub new_uri: String,
}

/// Deletes a file.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, JsonSchema)]
pub struct DeleteFile {
    /// `file://` URI to delete.
    pub uri: String,
}

/// One entry of `documentChanges`: edits to a file's text, or a resource
/// operation on it. A resource operation carries a `kind` of `create`,
/// `rename`, or `delete`; a text edit carries none, which is how the two are
/// told apart on the wire.
#[derive(Debug, Clone, PartialEq, Eq, JsonSchema)]
#[serde(untagged)]
pub enum DocumentChange {
    /// Edits to one file's text.
    Edit(TextDocumentEdit),
    /// A new, empty file.
    Create(CreateFile),
    /// A file rename.
    Rename(RenameFile),
    /// A file deletion.
    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),
    }
}

/// A workspace-wide edit from another tool.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct WorkspaceEdit {
    /// Per-file edits, keyed by `file://` URI. Ignored when `document_changes`
    /// is given.
    #[serde(default)]
    pub changes: Option<BTreeMap<String, Vec<TextEdit>>>,
    /// Edits and resource operations, in order. Preferred over `changes`.
    #[serde(default)]
    pub document_changes: Option<Vec<DocumentChange>>,
}

/// Why a `WorkspaceEdit` could not become operations.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum WorkspaceEditError {
    /// A `uri` was not a `file://` URI, or did not decode as valid UTF-8.
    #[error("bad file URI `{uri}`")]
    BadUri {
        /// The URI as given.
        uri: String,
    },
    /// The file could not be read to convert its positions.
    #[error("{}: {message}", path.display())]
    Unreadable {
        /// File that could not be read.
        path: PathBuf,
        /// Why.
        message: String,
    },
    /// A position's line or character falls outside the file's text.
    #[error("{}: position {line}:{character} is out of range", path.display())]
    BadPosition {
        /// File the position was inside.
        path: PathBuf,
        /// 0-based line.
        line: u32,
        /// 0-based character.
        character: u32,
    },
}

/// Converts `edit` into operations, resolving positions against each file's
/// text as read through `source`. Every text operation carries `expect_hash`
/// for the text it was converted against, so a file changed since is refused
/// as stale when the plan is built. `document_changes` is preferred over
/// `changes` when both are given, matching the LSP client preference.
///
/// # Errors
/// Returns an error for a URI that is not `file://`, a file that cannot be
/// read, or a position outside the file.
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 })
}