github.com/terraform-linters/tflint@v0.51.2-0.20240520175844-3750771571b6/langserver/text_document_did_change.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) textDocumentDidChange(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.DidChangeTextDocumentParams
    25  	if err := json.Unmarshal(*req.Params, &params); err != nil {
    26  		return nil, &jsonrpc2.Error{
    27  			Code:    jsonrpc2.CodeParseError,
    28  			Message: err.Error(),
    29  			Data:    req.Params,
    30  		}
    31  	}
    32  
    33  	changedPath, err := uriToPath(params.TextDocument.URI)
    34  	if err != nil {
    35  		return nil, err
    36  	}
    37  
    38  	if err := h.chdir(filepath.Dir(changedPath)); err != nil {
    39  		return nil, err
    40  	}
    41  
    42  	for idx, contentChange := range params.ContentChanges {
    43  		if err := afero.WriteFile(h.fs, filepath.Base(changedPath), []byte(contentChange.Text), os.ModePerm); err != nil {
    44  			return nil, fmt.Errorf("Failed to synchronize contentChanges[%d].Text: %s", idx, err)
    45  		}
    46  	}
    47  
    48  	diagnostics, err := h.inspect()
    49  	if err != nil {
    50  		return nil, err
    51  	}
    52  
    53  	log.Printf("Notify textDocument/publishDiagnostics with %#v", diagnostics)
    54  	for path, diags := range diagnostics {
    55  		err = conn.Notify(
    56  			ctx,
    57  			"textDocument/publishDiagnostics",
    58  			lsp.PublishDiagnosticsParams{
    59  				URI:         pathToURI(path),
    60  				Diagnostics: diags,
    61  			},
    62  		)
    63  		if err != nil {
    64  			return nil, fmt.Errorf("Failed to notify textDocument/publishDiagnostics: %s", err)
    65  		}
    66  	}
    67  
    68  	return nil, nil
    69  }