Skip to main content

griz_core/
workspace_edit.rs

1//! Converts an LSP `WorkspaceEdit` into griz [`Op`]s.
2//!
3//! Small serde structs of our own, not `lsp-types`: only the shapes griz
4//! needs to turn edits from another tool into operations `plan` already
5//! understands. `changes` and `documentChanges` combine `TextDocumentEdit`
6//! (a file's text edits) with the resource operations `CreateFile`,
7//! `RenameFile`, and `DeleteFile`.
8
9use crate::position::Position;
10use schemars::JsonSchema;
11use serde::Deserialize;
12use std::{collections::BTreeMap, path::PathBuf};
13
14/// A half-open `[start, end)` span of positions.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, JsonSchema)]
16pub struct Range {
17    /// First position.
18    pub start: Position,
19    /// One past the last position.
20    pub end: Position,
21}
22
23/// One text change within a file.
24#[derive(Debug, Clone, PartialEq, Eq, Deserialize, JsonSchema)]
25#[serde(rename_all = "camelCase")]
26pub struct TextEdit {
27    /// Span to replace.
28    pub range: Range,
29    /// Replacement text.
30    pub new_text: String,
31}
32
33/// Identifies the file a [`TextDocumentEdit`] changes.
34#[derive(Debug, Clone, PartialEq, Eq, Deserialize, JsonSchema)]
35pub struct TextDocumentIdentifier {
36    /// `file://` URI of the document.
37    pub uri: String,
38}
39
40/// Every edit to one file, applied together against its original text.
41#[derive(Debug, Clone, PartialEq, Eq, Deserialize, JsonSchema)]
42#[serde(rename_all = "camelCase")]
43pub struct TextDocumentEdit {
44    /// File the edits apply to.
45    pub text_document: TextDocumentIdentifier,
46    /// Edits, each against the file's original text.
47    pub edits: Vec<TextEdit>,
48}
49
50/// Creates a new, empty file.
51#[derive(Debug, Clone, PartialEq, Eq, Deserialize, JsonSchema)]
52pub struct CreateFile {
53    /// `file://` URI to create.
54    pub uri: String,
55    /// Create options; only `overwrite` changes what griz does.
56    pub options: Option<CreateFileOptions>,
57}
58
59/// What a `CreateFile` does when the file already exists.
60#[derive(Debug, Clone, PartialEq, Eq, Deserialize, JsonSchema)]
61#[serde(rename_all = "camelCase")]
62pub struct CreateFileOptions {
63    /// Replace the file when it exists, instead of refusing.
64    #[serde(default)]
65    pub overwrite: bool,
66}
67
68/// Renames a file. Becomes [`Op::Move`].
69#[derive(Debug, Clone, PartialEq, Eq, Deserialize, JsonSchema)]
70#[serde(rename_all = "camelCase")]
71pub struct RenameFile {
72    /// `file://` URI of the existing file.
73    pub old_uri: String,
74    /// `file://` URI it becomes.
75    pub new_uri: String,
76}
77
78/// Deletes a file.
79#[derive(Debug, Clone, PartialEq, Eq, Deserialize, JsonSchema)]
80pub struct DeleteFile {
81    /// `file://` URI to delete.
82    pub uri: String,
83}
84
85/// One entry of `documentChanges`: edits to a file's text, or a resource
86/// operation on it. A resource operation carries a `kind` of `create`,
87/// `rename`, or `delete`; a text edit carries none, which is how the two are
88/// told apart on the wire.
89#[derive(Debug, Clone, PartialEq, Eq, JsonSchema)]
90#[serde(untagged)]
91pub enum DocumentChange {
92    /// Edits to one file's text.
93    Edit(TextDocumentEdit),
94    /// A new, empty file.
95    Create(CreateFile),
96    /// A file rename.
97    Rename(RenameFile),
98    /// A file deletion.
99    Delete(DeleteFile),
100}
101
102impl<'de> Deserialize<'de> for DocumentChange {
103    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
104    where
105        D: serde::Deserializer<'de>,
106    {
107        let value = serde_json::Value::deserialize(deserializer)?;
108        let kind = value
109            .get("kind")
110            .and_then(serde_json::Value::as_str)
111            .map(str::to_string);
112        from_kind(kind.as_deref(), value).map_err(serde::de::Error::custom)
113    }
114}
115
116fn from_kind(
117    kind: Option<&str>,
118    value: serde_json::Value,
119) -> Result<DocumentChange, serde_json::Error> {
120    match kind {
121        Some("create") => serde_json::from_value(value).map(DocumentChange::Create),
122        Some("rename") => serde_json::from_value(value).map(DocumentChange::Rename),
123        Some("delete") => serde_json::from_value(value).map(DocumentChange::Delete),
124        _ => serde_json::from_value(value).map(DocumentChange::Edit),
125    }
126}
127
128/// A workspace-wide edit from another tool.
129#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, JsonSchema)]
130#[serde(rename_all = "camelCase")]
131pub struct WorkspaceEdit {
132    /// Per-file edits, keyed by `file://` URI. Ignored when `document_changes`
133    /// is given.
134    #[serde(default)]
135    pub changes: Option<BTreeMap<String, Vec<TextEdit>>>,
136    /// Edits and resource operations, in order. Preferred over `changes`.
137    #[serde(default)]
138    pub document_changes: Option<Vec<DocumentChange>>,
139}
140
141/// Why a `WorkspaceEdit` could not become operations.
142#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
143pub enum WorkspaceEditError {
144    /// A `uri` was not a `file://` URI, or did not decode as valid UTF-8.
145    #[error("bad file URI `{uri}`")]
146    BadUri {
147        /// The URI as given.
148        uri: String,
149    },
150    /// The file could not be read to convert its positions.
151    #[error("{}: {message}", path.display())]
152    Unreadable {
153        /// File that could not be read.
154        path: PathBuf,
155        /// Why.
156        message: String,
157    },
158    /// A position's line or character falls outside the file's text.
159    #[error("{}: position {line}:{character} is out of range", path.display())]
160    BadPosition {
161        /// File the position was inside.
162        path: PathBuf,
163        /// 0-based line.
164        line: u32,
165        /// 0-based character.
166        character: u32,
167    },
168}