Skip to content

Commit

Permalink
feat: refactor document
Browse files Browse the repository at this point in the history
  • Loading branch information
qvalentin committed Sep 5, 2024
1 parent 5b1dcc4 commit 15e26cb
Show file tree
Hide file tree
Showing 18 changed files with 137 additions and 111 deletions.
4 changes: 2 additions & 2 deletions internal/adapter/yamlls/diagnostics.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ func (c Connector) PublishDiagnostics(ctx context.Context, params *protocol.Publ
return nil
}

func filterDiagnostics(diagnostics []lsp.Diagnostic, ast *sitter.Tree, content string) (filtered []lsp.Diagnostic) {
func filterDiagnostics(diagnostics []lsp.Diagnostic, ast *sitter.Tree, content []byte) (filtered []lsp.Diagnostic) {
filtered = []lsp.Diagnostic{}

for _, diagnostic := range diagnostics {
Expand All @@ -41,7 +41,7 @@ func filterDiagnostics(diagnostics []lsp.Diagnostic, ast *sitter.Tree, content s

if node.Type() == "text" && childNode.Type() == "text" {
logger.Debug("Diagnostic", diagnostic)
logger.Debug("Node", node.Content([]byte(content)))
logger.Debug("Node", node.Content(content))

if diagnisticIsRelevant(diagnostic, childNode) {
diagnostic.Message = "Yamlls: " + diagnostic.Message
Expand Down
12 changes: 6 additions & 6 deletions internal/adapter/yamlls/document_sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
lsp "go.lsp.dev/protocol"
)

func (yamllsConnector Connector) InitiallySyncOpenDocuments(docs []*lsplocal.Document) {
func (yamllsConnector Connector) InitiallySyncOpenDocuments(docs []*lsplocal.TemplateDocument) {
if yamllsConnector.server == nil {
return
}
Expand All @@ -27,7 +27,7 @@ func (yamllsConnector Connector) InitiallySyncOpenDocuments(docs []*lsplocal.Doc
yamllsConnector.DocumentDidOpen(doc.Ast, lsp.DidOpenTextDocumentParams{
TextDocument: lsp.TextDocumentItem{
URI: doc.URI,
Text: doc.Content,
Text: string(doc.Content),
},
})
}
Expand All @@ -39,15 +39,15 @@ func (yamllsConnector Connector) DocumentDidOpen(ast *sitter.Tree, params lsp.Di
if !yamllsConnector.shouldRun(params.TextDocument.URI) {
return
}
params.TextDocument.Text = lsplocal.TrimTemplate(ast, params.TextDocument.Text)
params.TextDocument.Text = lsplocal.TrimTemplate(ast, []byte(params.TextDocument.Text))

err := yamllsConnector.server.DidOpen(context.Background(), &params)
if err != nil {
logger.Error("Error calling yamlls for didOpen", err)
}
}

func (yamllsConnector Connector) DocumentDidSave(doc *lsplocal.Document, params lsp.DidSaveTextDocumentParams) {
func (yamllsConnector Connector) DocumentDidSave(doc *lsplocal.TemplateDocument, params lsp.DidSaveTextDocumentParams) {
if !yamllsConnector.shouldRun(doc.URI) {
return
}
Expand All @@ -66,7 +66,7 @@ func (yamllsConnector Connector) DocumentDidSave(doc *lsplocal.Document, params
})
}

func (yamllsConnector Connector) DocumentDidChange(doc *lsplocal.Document, params lsp.DidChangeTextDocumentParams) {
func (yamllsConnector Connector) DocumentDidChange(doc *lsplocal.TemplateDocument, params lsp.DidChangeTextDocumentParams) {
if !yamllsConnector.shouldRun(doc.URI) {
return
}
Expand Down Expand Up @@ -95,7 +95,7 @@ func (yamllsConnector Connector) DocumentDidChange(doc *lsplocal.Document, param
}
}

func (yamllsConnector Connector) DocumentDidChangeFullSync(doc *lsplocal.Document, params lsp.DidChangeTextDocumentParams) {
func (yamllsConnector Connector) DocumentDidChangeFullSync(doc *lsplocal.TemplateDocument, params lsp.DidChangeTextDocumentParams) {
if !yamllsConnector.shouldRun(doc.URI) {
return
}
Expand Down
2 changes: 1 addition & 1 deletion internal/language_features/generic_document_usecase.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
)

type GenericDocumentUseCase struct {
Document *lsplocal.Document
Document *lsplocal.TemplateDocument
DocumentStore *lsplocal.DocumentStore
Chart *charts.Chart
Node *sitter.Node
Expand Down
6 changes: 3 additions & 3 deletions internal/lsp/ast.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ import (
lsp "go.lsp.dev/protocol"
)

func ParseAst(oldTree *sitter.Tree, content string) *sitter.Tree {
func ParseAst(oldTree *sitter.Tree, content []byte) *sitter.Tree {
parser := sitter.NewParser()
parser.SetLanguage(gotemplate.GetLanguage())
tree, _ := parser.ParseCtx(context.Background(), oldTree, []byte(content))
tree, _ := parser.ParseCtx(context.Background(), oldTree, content)
return tree
}

Expand Down Expand Up @@ -69,7 +69,7 @@ func isPointLargerOrEq(a sitter.Point, b sitter.Point) bool {
return a.Row > b.Row
}

func (d *Document) ApplyChangesToAst(newContent string) {
func (d *TemplateDocument) ApplyChangesToAst(newContent []byte) {
d.Ast = ParseAst(nil, newContent)
}

Expand Down
2 changes: 1 addition & 1 deletion internal/lsp/ast_diagnostics_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (

func TestIsInElseBranch(t *testing.T) {
template := `{{if pipeline}} t1 {{ else if pipeline }} t2 {{ else if pipeline2 }} t3 {{ else }} t4 {{ end }}`
ast := ParseAst(nil, template)
ast := ParseAst(nil, []byte(template))
// (template [0, 0] - [1, 0]
// (if_action [0, 0] - [0, 95]
// condition: (function_call [0, 5] - [0, 13]
Expand Down
2 changes: 1 addition & 1 deletion internal/lsp/ast_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ func TestFindRelevantChildNodeCompletio(t *testing.T) {
{{ .Chart.N }}
{{ . }}
`
ast := ParseAst(nil, template)
ast := ParseAst(nil, []byte(template))

logger.Println("RootNode:", ast.RootNode().String())

Expand Down
66 changes: 7 additions & 59 deletions internal/lsp/document.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,36 +3,27 @@ package lsp
import (
"bytes"
"fmt"
"strings"

"github.com/mrjosh/helm-ls/internal/util"
sitter "github.com/smacker/go-tree-sitter"
lsp "go.lsp.dev/protocol"
)

// Document represents an opened file.
type Document struct {
URI lsp.DocumentURI
Path string
NeedsRefreshDiagnostics bool
Content string
lines []string
Ast *sitter.Tree
DiagnosticsCache DiagnosticsCache
IsOpen bool
SymbolTable *SymbolTable
IsYaml bool
URI lsp.DocumentURI
Path string
Content []byte
lines []string
IsOpen bool
}

// ApplyChanges updates the content of the document from LSP textDocument/didChange events.
func (d *Document) ApplyChanges(changes []lsp.TextDocumentContentChangeEvent) {
defer func() {
if r := recover(); r != nil {
logger.Error(fmt.Sprintf("Recovered in ApplyChanges for %s, the document may be corrupted ", d.URI), r)
}
}()

content := []byte(d.Content)
content := d.Content
for _, change := range changes {
start, end := util.PositionToIndex(change.Range.Start, content), util.PositionToIndex(change.Range.End, content)

Expand All @@ -42,49 +33,6 @@ func (d *Document) ApplyChanges(changes []lsp.TextDocumentContentChangeEvent) {
buf.Write(content[end:])
content = buf.Bytes()
}
d.Content = string(content)

d.ApplyChangesToAst(d.Content)
d.SymbolTable = NewSymbolTable(d.Ast, content)

d.Content = content
d.lines = nil
}

// WordAt returns the word found at the given location.
func (d *Document) WordAt(pos lsp.Position) string {
logger.Debug(pos)

line, ok := d.getLine(int(pos.Line))
if !ok {
return ""
}
return util.WordAt(line, int(pos.Character))
}

// getLine returns the line at the given index.
func (d *Document) getLine(index int) (string, bool) {
lines := d.getLines()
if index < 0 || index > len(lines) {
return "", false
}
return lines[index], true
}

// getLines returns all the lines in the document.
func (d *Document) getLines() []string {
if d.lines == nil {
// We keep \r on purpose, to avoid messing up position conversions.
d.lines = strings.Split(d.Content, "\n")
}
return d.lines
}

// GetContent implements PossibleDependencyFile.
func (d *Document) GetContent() []byte {
return []byte(d.Content)
}

// GetPath implements PossibleDependencyFile.
func (d *Document) GetPath() string {
return d.Path
}
46 changes: 25 additions & 21 deletions internal/lsp/document_store.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,28 +20,30 @@ func NewDocumentStore() *DocumentStore {
}
}

func (s *DocumentStore) GetAllDocs() []*Document {
var docs []*Document
func (s *DocumentStore) GetAllDocs() []*TemplateDocument {
var docs []*TemplateDocument
s.documents.Range(func(_, v interface{}) bool {
docs = append(docs, v.(*Document))
docs = append(docs, v.(*TemplateDocument))
return true
})
return docs
}

func (s *DocumentStore) DidOpen(params *lsp.DidOpenTextDocumentParams, helmlsConfig util.HelmlsConfiguration) (*Document, error) {
func (s *DocumentStore) DidOpen(params *lsp.DidOpenTextDocumentParams, helmlsConfig util.HelmlsConfiguration) (*TemplateDocument, error) {
logger.Debug(fmt.Sprintf("Opening document %s with langID %s", params.TextDocument.URI, params.TextDocument.LanguageID))

uri := params.TextDocument.URI
path := uri.Filename()
ast := ParseAst(nil, params.TextDocument.Text)
doc := &Document{
URI: uri,
Path: path,
Content: params.TextDocument.Text,
ast := ParseAst(nil, []byte(params.TextDocument.Text))
doc := &TemplateDocument{
Document: Document{
URI: uri,
Path: path,
Content: []byte(params.TextDocument.Text),
IsOpen: true,
},
Ast: ast,
DiagnosticsCache: NewDiagnosticsCache(helmlsConfig),
IsOpen: true,
SymbolTable: NewSymbolTable(ast, []byte(params.TextDocument.Text)),
IsYaml: IsYamlDocument(uri, helmlsConfig.YamllsConfiguration),
}
Expand All @@ -50,35 +52,37 @@ func (s *DocumentStore) DidOpen(params *lsp.DidOpenTextDocumentParams, helmlsCon
return doc, nil
}

func (s *DocumentStore) Store(filename string, content []byte, helmlsConfig util.HelmlsConfiguration) {
_, ok := s.documents.Load(filename)
func (s *DocumentStore) Store(path string, content []byte, helmlsConfig util.HelmlsConfiguration) {
_, ok := s.documents.Load(path)
if ok {
return
}
ast := ParseAst(nil, string(content))
fileURI := uri.File(filename)
ast := ParseAst(nil, content)
fileURI := uri.File(path)
s.documents.Store(fileURI.Filename(),
&Document{
URI: fileURI,
Path: filename,
Content: string(content),
&TemplateDocument{
Document: Document{
URI: fileURI,
Path: path,
Content: content,
IsOpen: false,
},
Ast: ast,
DiagnosticsCache: NewDiagnosticsCache(helmlsConfig),
IsOpen: false,
SymbolTable: NewSymbolTable(ast, content),
IsYaml: IsYamlDocument(fileURI, helmlsConfig.YamllsConfiguration),
},
)
}

func (s *DocumentStore) Get(docuri uri.URI) (*Document, bool) {
func (s *DocumentStore) Get(docuri uri.URI) (*TemplateDocument, bool) {
path := docuri.Filename()
d, ok := s.documents.Load(path)

if !ok {
return nil, false
}
return d.(*Document), ok
return d.(*TemplateDocument), ok
}

func IsYamlDocument(uri lsp.URI, yamllsConfiguration util.YamllsConfiguration) bool {
Expand Down
2 changes: 1 addition & 1 deletion internal/lsp/lint.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import (

var logger = log.GetLogger()

func GetDiagnosticsNotifications(chart *charts.Chart, doc *Document) []lsp.PublishDiagnosticsParams {
func GetDiagnosticsNotifications(chart *charts.Chart, doc *TemplateDocument) []lsp.PublishDiagnosticsParams {
vals := chart.ValuesFiles.MainValuesFile.Values
if chart.ValuesFiles.OverlayValuesFile != nil {
vals = chartutil.CoalesceTables(chart.ValuesFiles.OverlayValuesFile.Values, chart.ValuesFiles.MainValuesFile.Values)
Expand Down
10 changes: 8 additions & 2 deletions internal/lsp/lint_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ func TestLintNotifications(t *testing.T) {
AdditionalValuesFiles: []*charts.ValuesFile{},
},
}
diagnostics := GetDiagnosticsNotifications(&chart, &Document{URI: uri.File("../../testdata/example/templates/deployment-no-templates.yaml")})
diagnostics := GetDiagnosticsNotifications(&chart, &TemplateDocument{
Document: Document{URI: uri.File("../../testdata/example/templates/deployment-no-templates.yaml")},
})
assert.NotEmpty(t, diagnostics)
assert.Len(t, diagnostics, 3)

Expand All @@ -50,7 +52,11 @@ func TestLintNotificationsIncludesEmptyDiagnosticsForFixedIssues(t *testing.T) {
AdditionalValuesFiles: []*charts.ValuesFile{},
},
}
diagnostics := GetDiagnosticsNotifications(&chart, &Document{URI: uri.File("../../testdata/example/templates/deployment-no-templates.yaml")})
diagnostics := GetDiagnosticsNotifications(&chart, &TemplateDocument{
Document: Document{
URI: uri.File("../../testdata/example/templates/deployment-no-templates.yaml"),
},
})

uris := []string{}
for _, notification := range diagnostics {
Expand Down
2 changes: 1 addition & 1 deletion internal/lsp/symbol_table_template_context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ func TestGetContextForSelectorExpression(t *testing.T) {
}
for _, tC := range testCases {
t.Run(tC.desc, func(t *testing.T) {
ast := ParseAst(nil, tC.template)
ast := ParseAst(nil, []byte(tC.template))
node := ast.RootNode().Child(1)

assert.Equal(t, tC.nodeContent, node.Content([]byte(tC.template)))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ func TestResolveVariablesInTemplateContext(t *testing.T) {
t.Run(tt.template, func(t *testing.T) {
col := strings.Index(tt.template, "^")
buf := strings.Replace(tt.template, "^", "", 1)
ast := ParseAst(nil, tt.template)
ast := ParseAst(nil, []byte(tt.template))
symbolTable := NewSymbolTable(ast, []byte(buf))

result, err := symbolTable.ResolveVariablesInTemplateContext(
Expand Down
10 changes: 5 additions & 5 deletions internal/lsp/symbol_table_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ func TestSymbolTableForIncludeDefinitions(t *testing.T) {
{{ end }}
`

ast := ParseAst(nil, content)
ast := ParseAst(nil, []byte(content))

symbolTable := NewSymbolTable(ast, []byte(content))

Expand Down Expand Up @@ -68,7 +68,7 @@ func TestSymbolTableForValues(t *testing.T) {
{{ end }}
`

ast := ParseAst(nil, content)
ast := ParseAst(nil, []byte(content))

symbolTable := NewSymbolTable(ast, []byte(content))
type expectedValue struct {
Expand Down Expand Up @@ -187,9 +187,9 @@ func TestSymbolTableForValuesTestFile(t *testing.T) {
if err != nil {
t.Fatal("Could not read test file", err)
}
ast := ParseAst(nil, string(content))
ast := ParseAst(nil, content)

symbolTable := NewSymbolTable(ast, []byte(content))
symbolTable := NewSymbolTable(ast, content)
type expectedValue struct {
path []string
startPoint sitter.Point
Expand Down Expand Up @@ -324,7 +324,7 @@ func TestSymbolTableForValuesSingleTests(t *testing.T) {

for _, v := range testCases {
t.Run(v.template, func(t *testing.T) {
ast := ParseAst(nil, v.template)
ast := ParseAst(nil, []byte(v.template))
symbolTable := NewSymbolTable(ast, []byte(v.template))
values := symbolTable.GetTemplateContextRanges(v.path)
points := []sitter.Point{}
Expand Down
Loading

0 comments on commit 15e26cb

Please sign in to comment.