on master help sign in
discard outdated workspace edits recived from the LS
commitb6a4927f00cba3d55a6bad93bfd93346a876ca74 authorPascal Kuthe <pascal.kuthe@semimod.de> dateSun 12 Mar 2023, 01:01 (4 years ago) parent3c9d5d0
2 files changed+94−34
helix-term/src/application.rs+7−4 helix-term/src/commands/lsp.rs+87−30
helix-term/src/application.rs+7−4
@@ -999,16 +999,19 @@ impl Application {
999999 Ok(serde_json::Value::Null)
10001000 }
10011001 Ok(MethodCall::ApplyWorkspaceEdit(params)) => {
1002− apply_workspace_edit(
1002+ let res = apply_workspace_edit(
10031003 &mut self.editor,
10041004 helix_lsp::OffsetEncoding::Utf8,
10051005 &params.edit,
10061006 );
10071007
10081008 Ok(json!(lsp::ApplyWorkspaceEditResponse {
1009− applied: true,
1010− failure_reason: None,
1011− failed_change: None,
1009+ applied: res.is_ok(),
1010+ failure_reason: res.as_ref().err().map(|err| err.kind.to_string()),
1011+ failed_change: res
1012+ .as_ref()
1013+ .err()
1014+ .map(|err| err.failed_change_idx as u32),
10121015 }))
10131016 }
10141017 Ok(MethodCall::WorkspaceFolders) => {
helix-term/src/commands/lsp.rs+87−30
@@ -651,7 +651,7 @@ pub fn code_action(cx: &mut Context) {
651651 log::debug!("code action: {:?}", code_action);
652652 if let Some(ref workspace_edit) = code_action.edit {
653653 log::debug!("edit: {:?}", workspace_edit);
654− apply_workspace_edit(editor, offset_encoding, workspace_edit);
654+ let _ = apply_workspace_edit(editor, offset_encoding, workspace_edit);
655655 }
656656
657657 // if code action provides both edit and command first the edit
@@ -757,19 +757,50 @@ pub fn apply_document_resource_op(op: &lsp::ResourceOp) -> std::io::Result<()> {
757757 }
758758}
759759
760+#[derive(Debug)]
761+pub struct ApplyEditError {
762+ pub kind: ApplyEditErrorKind,
763+ pub failed_change_idx: usize,
764+}
765+
766+#[derive(Debug)]
767+pub enum ApplyEditErrorKind {
768+ DocumentChanged,
769+ FileNotFound,
770+ UnknownURISchema,
771+ IoError(std::io::Error),
772+ // TODO: check edits before applying and propagate failure
773+ // InvalidEdit,
774+}
775+
776+impl ToString for ApplyEditErrorKind {
777+ fn to_string(&self) -> String {
778+ match self {
779+ ApplyEditErrorKind::DocumentChanged => "document has changed".to_string(),
780+ ApplyEditErrorKind::FileNotFound => "file not found".to_string(),
781+ ApplyEditErrorKind::UnknownURISchema => "URI schema not supported".to_string(),
782+ ApplyEditErrorKind::IoError(err) => err.to_string(),
783+ }
784+ }
785+}
786+
787+///TODO make this transactional (and set failureMode to transactional)
760788pub fn apply_workspace_edit(
761789 editor: &mut Editor,
762790 offset_encoding: OffsetEncoding,
763791 workspace_edit: &lsp::WorkspaceEdit,
764−) {
765− let mut apply_edits = |uri: &helix_lsp::Url, text_edits: Vec<lsp::TextEdit>| {
792+) -> Result<(), ApplyEditError> {
793+ let mut apply_edits = |uri: &helix_lsp::Url,
794+ version: Option<i32>,
795+ text_edits: Vec<lsp::TextEdit>|
796+ -> Result<(), ApplyEditErrorKind> {
766797 let path = match uri.to_file_path() {
767798 Ok(path) => path,
768799 Err(_) => {
769800 let err = format!("unable to convert URI to filepath: {}", uri);
770801 log::error!("{}", err);
771802 editor.set_error(err);
772− return;
803+ return Err(ApplyEditErrorKind::UnknownURISchema);
773804 }
774805 };
775806
@@ -780,11 +811,19 @@ pub fn apply_workspace_edit(
780811 let err = format!("failed to open document: {}: {}", uri, err);
781812 log::error!("{}", err);
782813 editor.set_error(err);
783− return;
814+ return Err(ApplyEditErrorKind::FileNotFound);
784815 }
785816 };
786817
787818 let doc = doc_mut!(editor, &doc_id);
819+ if let Some(version) = version {
820+ if version != doc.version() {
821+ let err = format!("outdated workspace edit for {path:?}");
822+ log::error!("{err}, expected {} but got {version}", doc.version());
823+ editor.set_error(err);
824+ return Err(ApplyEditErrorKind::DocumentChanged);
825+ }
826+ }
788827
789828 // Need to determine a view for apply/append_changes_to_history
790829 let selections = doc.selections();
@@ -808,31 +847,13 @@ pub fn apply_workspace_edit(
808847 let view = view_mut!(editor, view_id);
809848 doc.apply(&transaction, view.id);
810849 doc.append_changes_to_history(view);
850+ Ok(())
811851 };
812852
813− if let Some(ref changes) = workspace_edit.changes {
814− log::debug!("workspace changes: {:?}", changes);
815− for (uri, text_edits) in changes {
816− let text_edits = text_edits.to_vec();
817− apply_edits(uri, text_edits)
818− }
819− return;
820− // Not sure if it works properly, it'll be safer to just panic here to avoid breaking some parts of code on which code actions will be used
821− // TODO: find some example that uses workspace changes, and test it
822− // for (url, edits) in changes.iter() {
823− // let file_path = url.origin().ascii_serialization();
824− // let file_path = std::path::PathBuf::from(file_path);
825− // let file = std::fs::File::open(file_path).unwrap();
826− // let mut text = Rope::from_reader(file).unwrap();
827− // let transaction = edits_to_changes(&text, edits);
828− // transaction.apply(&mut text);
829− // }
830− }
831−
832853 if let Some(ref document_changes) = workspace_edit.document_changes {
833854 match document_changes {
834855 lsp::DocumentChanges::Edits(document_edits) => {
835− for document_edit in document_edits {
856+ for (i, document_edit) in document_edits.iter().enumerate() {
836857 let edits = document_edit
837858 .edits
838859 .iter()
@@ -844,15 +865,26 @@ pub fn apply_workspace_edit(
844865 })
845866 .cloned()
846867 .collect();
847− apply_edits(&document_edit.text_document.uri, edits);
868+ apply_edits(
869+ &document_edit.text_document.uri,
870+ document_edit.text_document.version,
871+ edits,
872+ )
873+ .map_err(|kind| ApplyEditError {
874+ kind,
875+ failed_change_idx: i,
876+ })?;
848877 }
849878 }
850879 lsp::DocumentChanges::Operations(operations) => {
851880 log::debug!("document changes - operations: {:?}", operations);
852− for operation in operations {
881+ for (i, operation) in operations.iter().enumerate() {
853882 match operation {
854883 lsp::DocumentChangeOperation::Op(op) => {
855− apply_document_resource_op(op).unwrap();
884+ apply_document_resource_op(op).map_err(|io| ApplyEditError {
885+ kind: ApplyEditErrorKind::IoError(io),
886+ failed_change_idx: i,
887+ })?;
856888 }
857889
858890 lsp::DocumentChangeOperation::Edit(document_edit) => {
@@ -867,13 +899,36 @@ pub fn apply_workspace_edit(
867899 })
868900 .cloned()
869901 .collect();
870− apply_edits(&document_edit.text_document.uri, edits);
902+ apply_edits(
903+ &document_edit.text_document.uri,
904+ document_edit.text_document.version,
905+ edits,
906+ )
907+ .map_err(|kind| ApplyEditError {
908+ kind,
909+ failed_change_idx: i,
910+ })?;
871911 }
872912 }
873913 }
874914 }
875915 }
916+
917+ return Ok(());
876918 }
919+
920+ if let Some(ref changes) = workspace_edit.changes {
921+ log::debug!("workspace changes: {:?}", changes);
922+ for (i, (uri, text_edits)) in changes.iter().enumerate() {
923+ let text_edits = text_edits.to_vec();
924+ apply_edits(uri, None, text_edits).map_err(|kind| ApplyEditError {
925+ kind,
926+ failed_change_idx: i,
927+ })?;
928+ }
929+ }
930+
931+ Ok(())
877932}
878933
879934fn goto_impl(
@@ -1297,7 +1352,9 @@ pub fn rename_symbol(cx: &mut Context) {
12971352 }
12981353 };
12991354 match block_on(future) {
1300− Ok(edits) => apply_workspace_edit(cx.editor, offset_encoding, &edits),
1355+ Ok(edits) => {
1356+ let _ = apply_workspace_edit(cx.editor, offset_encoding, &edits);
1357+ }
13011358 Err(err) => cx.editor.set_error(err.to_string()),
13021359 }
13031360 },