tsdocument-changes.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright 2022 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package protocol
  5. import (
  6. "encoding/json"
  7. "fmt"
  8. )
  9. // DocumentChange is a union of various file edit operations.
  10. //
  11. // Exactly one field of this struct is non-nil; see [DocumentChange.Valid].
  12. //
  13. // See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#resourceChanges
  14. type DocumentChange struct {
  15. TextDocumentEdit *TextDocumentEdit
  16. CreateFile *CreateFile
  17. RenameFile *RenameFile
  18. DeleteFile *DeleteFile
  19. }
  20. // Valid reports whether the DocumentChange sum-type value is valid,
  21. // that is, exactly one of create, delete, edit, or rename.
  22. func (ch DocumentChange) Valid() bool {
  23. n := 0
  24. if ch.TextDocumentEdit != nil {
  25. n++
  26. }
  27. if ch.CreateFile != nil {
  28. n++
  29. }
  30. if ch.RenameFile != nil {
  31. n++
  32. }
  33. if ch.DeleteFile != nil {
  34. n++
  35. }
  36. return n == 1
  37. }
  38. func (d *DocumentChange) UnmarshalJSON(data []byte) error {
  39. var m map[string]any
  40. if err := json.Unmarshal(data, &m); err != nil {
  41. return err
  42. }
  43. if _, ok := m["textDocument"]; ok {
  44. d.TextDocumentEdit = new(TextDocumentEdit)
  45. return json.Unmarshal(data, d.TextDocumentEdit)
  46. }
  47. // The {Create,Rename,Delete}File types all share a 'kind' field.
  48. kind := m["kind"]
  49. switch kind {
  50. case "create":
  51. d.CreateFile = new(CreateFile)
  52. return json.Unmarshal(data, d.CreateFile)
  53. case "rename":
  54. d.RenameFile = new(RenameFile)
  55. return json.Unmarshal(data, d.RenameFile)
  56. case "delete":
  57. d.DeleteFile = new(DeleteFile)
  58. return json.Unmarshal(data, d.DeleteFile)
  59. }
  60. return fmt.Errorf("DocumentChanges: unexpected kind: %q", kind)
  61. }
  62. func (d *DocumentChange) MarshalJSON() ([]byte, error) {
  63. if d.TextDocumentEdit != nil {
  64. return json.Marshal(d.TextDocumentEdit)
  65. } else if d.CreateFile != nil {
  66. return json.Marshal(d.CreateFile)
  67. } else if d.RenameFile != nil {
  68. return json.Marshal(d.RenameFile)
  69. } else if d.DeleteFile != nil {
  70. return json.Marshal(d.DeleteFile)
  71. }
  72. return nil, fmt.Errorf("empty DocumentChanges union value")
  73. }