github.com/terraform-linters/tflint@v0.51.2-0.20240520175844-3750771571b6/langserver/text_document_did_open.go (about) 1 package langserver 2 3 import ( 4 "context" 5 "encoding/json" 6 "fmt" 7 "log" 8 "os" 9 "path/filepath" 10 11 lsp "github.com/sourcegraph/go-lsp" 12 "github.com/sourcegraph/jsonrpc2" 13 "github.com/spf13/afero" 14 ) 15 16 func (h *handler) textDocumentDidOpen(ctx context.Context, conn *jsonrpc2.Conn, req *jsonrpc2.Request) (result interface{}, err error) { 17 if req.Params == nil { 18 return nil, &jsonrpc2.Error{ 19 Code: jsonrpc2.CodeInvalidRequest, 20 Message: "request params are nil", 21 } 22 } 23 24 var params lsp.DidOpenTextDocumentParams 25 if err := json.Unmarshal(*req.Params, ¶ms); err != nil { 26 return nil, &jsonrpc2.Error{ 27 Code: jsonrpc2.CodeParseError, 28 Message: err.Error(), 29 Data: req.Params, 30 } 31 } 32 33 openedPath, err := uriToPath(params.TextDocument.URI) 34 if err != nil { 35 return nil, err 36 } 37 38 if err := h.chdir(filepath.Dir(openedPath)); err != nil { 39 return nil, err 40 } 41 42 if err := afero.WriteFile(h.fs, filepath.Base(openedPath), []byte(params.TextDocument.Text), os.ModePerm); err != nil { 43 return nil, fmt.Errorf("Failed to synchronize TextDocument.Text: %s", err) 44 } 45 46 diagnostics, err := h.inspect() 47 if err != nil { 48 return nil, err 49 } 50 51 log.Printf("Notify textDocument/publishDiagnostics with %#v", diagnostics) 52 for path, diags := range diagnostics { 53 err = conn.Notify( 54 ctx, 55 "textDocument/publishDiagnostics", 56 lsp.PublishDiagnosticsParams{ 57 URI: pathToURI(path), 58 Diagnostics: diags, 59 }, 60 ) 61 if err != nil { 62 return nil, fmt.Errorf("Failed to notify textDocument/publishDiagnostics: %s", err) 63 } 64 } 65 66 return nil, nil 67 }