Skip to content

Commit

Permalink
feat: refactor document creation
Browse files Browse the repository at this point in the history
  • Loading branch information
qvalentin committed Sep 5, 2024
1 parent 15e26cb commit 6446a22
Show file tree
Hide file tree
Showing 15 changed files with 81 additions and 89 deletions.
2 changes: 1 addition & 1 deletion internal/adapter/yamlls/diagnostics.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import (
)

func (c Connector) PublishDiagnostics(ctx context.Context, params *protocol.PublishDiagnosticsParams) (err error) {
doc, ok := c.documents.Get(params.URI)
doc, ok := c.documents.GetTemplateDoc(params.URI)
if !ok {
logger.Println("Error handling diagnostic. Could not get document: " + params.URI.Filename())
return fmt.Errorf("Could not get document: %s", params.URI.Filename())
Expand Down
2 changes: 1 addition & 1 deletion internal/adapter/yamlls/document_sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ func (yamllsConnector Connector) InitiallySyncOpenDocuments(docs []*lsplocal.Tem
continue
}

doc.IsYaml = lsplocal.IsYamlDocument(doc.URI, yamllsConnector.config)
doc.IsYaml = lsplocal.IsYamllsEnabled(doc.URI, yamllsConnector.config)
if !yamllsConnector.isRelevantFile(doc.URI) {
continue
}
Expand Down
2 changes: 1 addition & 1 deletion internal/adapter/yamlls/yamlls.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ func NewConnector(ctx context.Context, yamllsConfiguration util.YamllsConfigurat
}

func (yamllsConnector *Connector) isRelevantFile(uri lsp.URI) bool {
doc, ok := yamllsConnector.documents.Get(uri)
doc, ok := yamllsConnector.documents.GetTemplateDoc(uri)
if !ok {
logger.Error("Could not find document", uri)
return true
Expand Down
2 changes: 1 addition & 1 deletion internal/handler/generic_document_usecase.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ func (h *langHandler) NewGenericDocumentUseCase(
params lsp.TextDocumentPositionParams,
nodeSelection func(ast *sitter.Tree, position lsp.Position) (node *sitter.Node),
) (*languagefeatures.GenericDocumentUseCase, error) {
doc, ok := h.documents.Get(params.TextDocument.URI)
doc, ok := h.documents.GetTemplateDoc(params.TextDocument.URI)
if !ok {
return &languagefeatures.GenericDocumentUseCase{}, errors.New("Could not get document: " + params.TextDocument.URI.Filename())
}
Expand Down
2 changes: 1 addition & 1 deletion internal/handler/initialization.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ func (h *langHandler) configureYamlls(ctx context.Context) {
logger.Error("Error initializing yamlls", err)
}

h.yamllsConnector.InitiallySyncOpenDocuments(h.documents.GetAllDocs())
h.yamllsConnector.InitiallySyncOpenDocuments(h.documents.GetAllTemplateDocs())
}
}

Expand Down
11 changes: 3 additions & 8 deletions internal/handler/text_document.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,12 @@ func (h *langHandler) DidOpen(ctx context.Context, params *lsp.DidOpenTextDocume

h.yamllsConnector.DocumentDidOpen(doc.Ast, *params)

doc, ok := h.documents.Get(params.TextDocument.URI)
if !ok {
return errors.New("Could not get document: " + params.TextDocument.URI.Filename())
}
chart, err := h.chartStore.GetChartOrParentForDoc(doc.URI)
if err != nil {
logger.Error("Error getting chart info for file", doc.URI, err)
}
notifications := lsplocal.GetDiagnosticsNotifications(chart, doc)

defer h.publishDiagnostics(ctx, notifications)
defer h.publishDiagnostics(ctx, lsplocal.GetDiagnosticsNotifications(chart, doc))

return nil
}
Expand All @@ -40,7 +35,7 @@ func (h *langHandler) DidClose(_ context.Context, _ *lsp.DidCloseTextDocumentPar
}

func (h *langHandler) DidSave(ctx context.Context, params *lsp.DidSaveTextDocumentParams) (err error) {
doc, ok := h.documents.Get(params.TextDocument.URI)
doc, ok := h.documents.GetTemplateDoc(params.TextDocument.URI)
if !ok {
return errors.New("Could not get document: " + params.TextDocument.URI.Filename())
}
Expand All @@ -58,7 +53,7 @@ func (h *langHandler) DidSave(ctx context.Context, params *lsp.DidSaveTextDocume
}

func (h *langHandler) DidChange(_ context.Context, params *lsp.DidChangeTextDocumentParams) (err error) {
doc, ok := h.documents.Get(params.TextDocument.URI)
doc, ok := h.documents.GetTemplateDoc(params.TextDocument.URI)
if !ok {
return errors.New("Could not get document: " + params.TextDocument.URI.Filename())
}
Expand Down
4 changes: 2 additions & 2 deletions internal/handler/text_document_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func TestLoadDocsOnNewChart(t *testing.T) {
h.LoadDocsOnNewChart(charts.NewChart(rootURI, util.DefaultConfig.ValuesFilesConfig))

for _, file := range templateFiles {
doc, ok := h.documents.Get(uri.File(file))
doc, ok := h.documents.GetTemplateDoc(uri.File(file))
assert.True(t, ok)
assert.NotNil(t, doc)
assert.False(t, doc.IsOpen)
Expand Down Expand Up @@ -73,7 +73,7 @@ func TestLoadDocsOnNewChartDoesNotOverwrite(t *testing.T) {

h.LoadDocsOnNewChart(charts.NewChart(rootURI, util.DefaultConfig.ValuesFilesConfig))

doc, ok := h.documents.Get(uri.File(templateFile))
doc, ok := h.documents.GetTemplateDoc(uri.File(templateFile))
assert.True(t, ok)
assert.NotNil(t, doc)
// The document should still be open because it's already in the store
Expand Down
2 changes: 1 addition & 1 deletion internal/language_features/generic_template_context.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ func (f *GenericTemplateContextFeature) getTemplateContext() (lsplocal.TemplateC
func (f *GenericTemplateContextFeature) getReferencesFromSymbolTable(templateContext lsplocal.TemplateContext) []lsp.Location {
locations := []lsp.Location{}

for _, doc := range f.GenericDocumentUseCase.DocumentStore.GetAllDocs() {
for _, doc := range f.GenericDocumentUseCase.DocumentStore.GetAllTemplateDocs() {
referenceRanges := doc.SymbolTable.GetTemplateContextRanges(templateContext)
for _, referenceRange := range referenceRanges {
locations = append(locations, util.RangeToLocation(doc.URI, referenceRange))
Expand Down
8 changes: 4 additions & 4 deletions internal/language_features/includes.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ func (f *IncludesDefinitionFeature) References() (result []lsp.Location, err err

func (f *IncludesFeature) getReferenceLocations(includeName string) []lsp.Location {
locations := []lsp.Location{}
for _, doc := range f.GenericDocumentUseCase.DocumentStore.GetAllDocs() {
for _, doc := range f.GenericDocumentUseCase.DocumentStore.GetAllTemplateDocs() {
referenceRanges := doc.SymbolTable.GetIncludeReference(includeName)
for _, referenceRange := range referenceRanges {
locations = append(locations, util.RangeToLocation(doc.URI, referenceRange))
Expand All @@ -101,7 +101,7 @@ func (f *IncludesFeature) getReferenceLocations(includeName string) []lsp.Locati

func (f *IncludesFeature) getDefinitionLocations(includeName string) []lsp.Location {
locations := []lsp.Location{}
for _, doc := range f.GenericDocumentUseCase.DocumentStore.GetAllDocs() {
for _, doc := range f.GenericDocumentUseCase.DocumentStore.GetAllTemplateDocs() {
referenceRanges := doc.SymbolTable.GetIncludeDefinitions(includeName)
for _, referenceRange := range referenceRanges {
locations = append(locations, util.RangeToLocation(doc.URI, referenceRange))
Expand All @@ -116,7 +116,7 @@ func (f *IncludesFeature) getDefinitionLocations(includeName string) []lsp.Locat

func (f *IncludesFeature) getDefinitionsHover(includeName string) protocol.HoverResultsWithFiles {
result := protocol.HoverResultsWithFiles{}
for _, doc := range f.GenericDocumentUseCase.DocumentStore.GetAllDocs() {
for _, doc := range f.GenericDocumentUseCase.DocumentStore.GetAllTemplateDocs() {
referenceRanges := doc.SymbolTable.GetIncludeDefinitions(includeName)
for _, referenceRange := range referenceRanges {
node := doc.Ast.RootNode().NamedDescendantForPointRange(referenceRange.StartPoint, referenceRange.EndPoint)
Expand Down Expand Up @@ -152,7 +152,7 @@ func (f *IncludesCallFeature) Definition() (result []lsp.Location, err error) {

func (f *IncludesCallFeature) Completion() (*lsp.CompletionList, error) {
items := []lsp.CompletionItem{}
for _, doc := range f.GenericDocumentUseCase.DocumentStore.GetAllDocs() {
for _, doc := range f.GenericDocumentUseCase.DocumentStore.GetAllTemplateDocs() {
inlcudeDefinitionNames := doc.SymbolTable.GetAllIncludeDefinitionsNames()
for _, includeDefinitionName := range inlcudeDefinitionNames {
items = append(items, lsp.CompletionItem{
Expand Down
2 changes: 1 addition & 1 deletion internal/language_features/template_context.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ func (f *TemplateContextFeature) Definition() (result []lsp.Location, err error)

func (f *TemplateContextFeature) getReferenceLocations(templateContext lsplocal.TemplateContext) []lsp.Location {
locations := []lsp.Location{}
for _, doc := range f.GenericDocumentUseCase.DocumentStore.GetAllDocs() {
for _, doc := range f.GenericDocumentUseCase.DocumentStore.GetAllTemplateDocs() {
referenceRanges := doc.SymbolTable.GetTemplateContextRanges(templateContext)
for _, referenceRange := range referenceRanges {
locations = append(locations, util.RangeToLocation(doc.URI, referenceRange))
Expand Down
30 changes: 30 additions & 0 deletions internal/lsp/document.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ package lsp
import (
"bytes"
"fmt"
"strings"

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

type Document struct {
Expand All @@ -16,6 +18,15 @@ type Document struct {
IsOpen bool
}

func NewDocument(fileURI uri.URI, content []byte, isOpen bool) *Document {
return &Document{
URI: fileURI,
Path: fileURI.Filename(),
Content: content,
IsOpen: isOpen,
}
}

func (d *Document) ApplyChanges(changes []lsp.TextDocumentContentChangeEvent) {
defer func() {
if r := recover(); r != nil {
Expand All @@ -36,3 +47,22 @@ func (d *Document) ApplyChanges(changes []lsp.TextDocumentContentChangeEvent) {
d.Content = content
d.lines = nil
}

// 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(string(d.Content), "\n")
}
return d.lines
}

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

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

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

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, []byte(params.TextDocument.Text))
doc := &TemplateDocument{
Document: Document{
URI: uri,
Path: path,
Content: []byte(params.TextDocument.Text),
IsOpen: true,
},
Ast: ast,
DiagnosticsCache: NewDiagnosticsCache(helmlsConfig),
SymbolTable: NewSymbolTable(ast, []byte(params.TextDocument.Text)),
IsYaml: IsYamlDocument(uri, helmlsConfig.YamllsConfiguration),
}
doc := NewTemplateDocument(uri, []byte(params.TextDocument.Text), true, helmlsConfig)
logger.Debug("Storing doc ", path)
s.documents.Store(path, doc)
return doc, nil
Expand All @@ -57,25 +36,12 @@ func (s *DocumentStore) Store(path string, content []byte, helmlsConfig util.Hel
if ok {
return
}
ast := ParseAst(nil, content)
fileURI := uri.File(path)
s.documents.Store(fileURI.Filename(),
&TemplateDocument{
Document: Document{
URI: fileURI,
Path: path,
Content: content,
IsOpen: false,
},
Ast: ast,
DiagnosticsCache: NewDiagnosticsCache(helmlsConfig),
SymbolTable: NewSymbolTable(ast, content),
IsYaml: IsYamlDocument(fileURI, helmlsConfig.YamllsConfiguration),
},
)
NewTemplateDocument(fileURI, content, false, helmlsConfig))
}

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

Expand All @@ -85,6 +51,11 @@ func (s *DocumentStore) Get(docuri uri.URI) (*TemplateDocument, bool) {
return d.(*TemplateDocument), ok
}

func IsYamlDocument(uri lsp.URI, yamllsConfiguration util.YamllsConfiguration) bool {
return yamllsConfiguration.EnabledForFilesGlobObject.Match(uri.Filename())
func (s *DocumentStore) GetAllTemplateDocs() []*TemplateDocument {
var docs []*TemplateDocument
s.documents.Range(func(_, v interface{}) bool {
docs = append(docs, v.(*TemplateDocument))
return true
})
return docs
}
8 changes: 4 additions & 4 deletions internal/lsp/document_store_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ import (

func TestIsYamlDocument(t *testing.T) {
assert := assert.New(t)
assert.True(IsYamlDocument(uri.File("test.yaml"), util.DefaultConfig.YamllsConfiguration))
assert.False(IsYamlDocument(uri.File("test.tpl"), util.DefaultConfig.YamllsConfiguration))
assert.True(IsYamlDocument(uri.File("../../testdata/example/templates/hpa.yaml"), util.DefaultConfig.YamllsConfiguration))
assert.False(IsYamlDocument(uri.File("../../testdata/example/templates/_helpers.tpl"), util.DefaultConfig.YamllsConfiguration))
assert.True(IsYamllsEnabled(uri.File("test.yaml"), util.DefaultConfig.YamllsConfiguration))
assert.False(IsYamllsEnabled(uri.File("test.tpl"), util.DefaultConfig.YamllsConfiguration))
assert.True(IsYamllsEnabled(uri.File("../../testdata/example/templates/hpa.yaml"), util.DefaultConfig.YamllsConfiguration))
assert.False(IsYamllsEnabled(uri.File("../../testdata/example/templates/_helpers.tpl"), util.DefaultConfig.YamllsConfiguration))
}
8 changes: 4 additions & 4 deletions internal/lsp/document_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ func TestDocumentStore(t *testing.T) {

sut := NewDocumentStore()

assert.Empty(sut.GetAllDocs())
assert.Empty(sut.GetAllTemplateDocs())

doc, ok := sut.Get(uri.File("test"))
doc, ok := sut.GetTemplateDoc(uri.File("test"))
assert.Nil(doc)
assert.False(ok)

Expand All @@ -29,9 +29,9 @@ func TestDocumentStore(t *testing.T) {
},
}, util.DefaultConfig)

assert.Len(sut.GetAllDocs(), 1)
assert.Len(sut.GetAllTemplateDocs(), 1)

doc, ok = sut.Get(uri.File("test.yaml"))
doc, ok = sut.GetTemplateDoc(uri.File("test.yaml"))
assert.NotNil(doc)
assert.True(ok)
}
38 changes: 17 additions & 21 deletions internal/lsp/template_document.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
package lsp

import (
"strings"

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

// TemplateDocument represents an opened file.
Expand All @@ -18,6 +17,18 @@ type TemplateDocument struct {
IsYaml bool
}

func NewTemplateDocument(fileURI uri.URI, content []byte, isOpen bool, helmlsConfig util.HelmlsConfiguration) *TemplateDocument {
ast := ParseAst(nil, content)
return &TemplateDocument{
Document: *NewDocument(fileURI, content, isOpen),
NeedsRefreshDiagnostics: false,
Ast: ast,
DiagnosticsCache: NewDiagnosticsCache(helmlsConfig),
SymbolTable: NewSymbolTable(ast, content),
IsYaml: IsYamllsEnabled(fileURI, helmlsConfig.YamllsConfiguration),
}
}

// ApplyChanges updates the content of the document from LSP textDocument/didChange events.
func (d *TemplateDocument) ApplyChanges(changes []lsp.TextDocumentContentChangeEvent) {
d.Document.ApplyChanges(changes)
Expand All @@ -29,7 +40,7 @@ func (d *TemplateDocument) ApplyChanges(changes []lsp.TextDocumentContentChangeE
}

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

line, ok := d.getLine(int(pos.Line))
Expand All @@ -40,29 +51,14 @@ func (d *TemplateDocument) WordAt(pos lsp.Position) string {
}

// getLine returns the line at the given index.
func (d *TemplateDocument) getLine(index int) (string, bool) {
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 *TemplateDocument) getLines() []string {
if d.lines == nil {
// We keep \r on purpose, to avoid messing up position conversions.
d.lines = strings.Split(string(d.Content), "\n")
}
return d.lines
}

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

// GetPath implements PossibleDependencyFile.
func (d *TemplateDocument) GetPath() string {
return d.Path
func IsYamllsEnabled(uri lsp.URI, yamllsConfiguration util.YamllsConfiguration) bool {
return yamllsConfiguration.EnabledForFilesGlobObject.Match(uri.Filename())
}

0 comments on commit 6446a22

Please sign in to comment.