Skip to content

Commit

Permalink
move SyncToDisk function to interface
Browse files Browse the repository at this point in the history
  • Loading branch information
qvalentin committed Aug 20, 2024
1 parent 3242a1e commit 4350412
Show file tree
Hide file tree
Showing 12 changed files with 139 additions and 140 deletions.
2 changes: 2 additions & 0 deletions internal/adapter/yamlls/diagnostics.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package yamlls

import (
"context"
"fmt"
"runtime"
"strings"

Expand All @@ -15,6 +16,7 @@ func (c Connector) PublishDiagnostics(ctx context.Context, params *protocol.Publ
doc, ok := c.documents.Get(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())
}

doc.DiagnosticsCache.SetYamlDiagnostics(filterDiagnostics(params.Diagnostics, doc.Ast.Copy(), doc.Content))
Expand Down
47 changes: 47 additions & 0 deletions internal/charts/dependency_files.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package charts

import (
"os"
"path/filepath"
"strings"

"helm.sh/helm/v3/pkg/chart"
)

type DependencyTemplateFile struct {
Content []byte
Path string
}

var DependencyCacheFolder = ".helm_ls_cache"

func (c *Chart) NewDependencyTemplateFile(chartName string, file *chart.File) *DependencyTemplateFile {
path := filepath.Join(c.RootURI.Filename(), "charts", DependencyCacheFolder, chartName, file.Name)

return &DependencyTemplateFile{Content: file.Data, Path: path}
}

type PossibleDependencyFile interface {
GetContent() string
GetPath() string
}

// SyncToDisk writes the content of the document to disk if it is a dependency file.
// If it is a dependency file, it was read from a archive, so we need to write it back,
// to be able to open it in a editor when using go-to-definition or go-to-reference.
func SyncToDisk(d PossibleDependencyFile) {
if !IsDependencyFile(d) {
return
}
err := os.MkdirAll(filepath.Dir(d.GetPath()), 0o755)
if err == nil {
err = os.WriteFile(d.GetPath(), []byte(d.GetContent()), 0o444)
}
if err != nil {
logger.Error("Could not write dependency file", d.GetPath(), err)
}
}

func IsDependencyFile(d PossibleDependencyFile) bool {
return strings.Contains(d.GetPath(), DependencyCacheFolder)
}
20 changes: 0 additions & 20 deletions internal/charts/dependency_template_file.go

This file was deleted.

15 changes: 15 additions & 0 deletions internal/charts/values_file.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,18 @@ func readInValuesFile(filePath string) (chartutil.Values, yaml.Node) {
}
return vals, valueNodes
}

// GetContent implements PossibleDependencyFile.
func (d *ValuesFile) GetContent() string {

Check failure on line 64 in internal/charts/values_file.go

View workflow job for this annotation

GitHub Actions / lint (1.22.4, ubuntu-latest)

receiver-naming: receiver name d should be consistent with previous receiver name v for ValuesFile (revive)
yaml, err := yaml.Marshal(d.Values)
if err != nil {
logger.Error(fmt.Sprintf("Could not load values for file %s", d.URI.Filename()), err)
return ""
}
return string(yaml)
}

// GetPath implements PossibleDependencyFile.
func (d *ValuesFile) GetPath() string {

Check failure on line 74 in internal/charts/values_file.go

View workflow job for this annotation

GitHub Actions / lint (1.22.4, ubuntu-latest)

receiver-naming: receiver name d should be consistent with previous receiver name v for ValuesFile (revive)
return d.URI.Filename()
}
8 changes: 8 additions & 0 deletions internal/charts/values_file_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,11 @@ func TestReload(t *testing.T) {
assert.Equal(t, "baz", valuesFile.Values["foo"])
assert.NotEqual(t, yaml.Node{}, valuesFile.ValueNode)
}

func TestGetContent(t *testing.T) {
tempDir := t.TempDir()
valuesContent := `foo: bar\n`
_ = os.WriteFile(filepath.Join(tempDir, "values.yaml"), []byte(valuesContent), 0o644)
valuesFile := charts.NewValuesFile(filepath.Join(tempDir, "values.yaml"))
assert.Equal(t, valuesContent, valuesFile.GetContent())
}
22 changes: 18 additions & 4 deletions internal/handler/definition_chart_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package handler

import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
Expand All @@ -22,6 +23,7 @@ var (
)

type testCase struct {
// Must be content of a line in the file fileURI
templateLineWithMarker string
expectedFile string
expectedStartPosition lsp.Position
Expand All @@ -42,6 +44,12 @@ func TestDefinitionChart(t *testing.T) {
lsp.Position{Line: 35, Character: 0},
nil,
},
{
`{{ .Values.gl^obal.subchart }}`,
"values.yaml",
lsp.Position{Line: 7, Character: 0},
nil,
},
}

fileContent, err := os.ReadFile(fileURI.Filename())
Expand All @@ -51,18 +59,22 @@ func TestDefinitionChart(t *testing.T) {
lines := strings.Split(string(fileContent), "\n")
for _, tC := range testCases {
t.Run("Definition on "+tC.templateLineWithMarker, func(t *testing.T) {
pos := getPosition(tC, lines)
pos, found := getPosition(tC, lines)
if !found {
t.Fatal(fmt.Sprintf("%s is not in the file %s", tC.templateLineWithMarker, fileURI.Filename()))
}

documents := lsplocal.NewDocumentStore()

chart := charts.NewChart(rootUri, util.ValuesFilesConfig{})
chart := charts.NewChart(rootUri, util.DefaultConfig.ValuesFilesConfig)

chartStore := charts.NewChartStore(rootUri, charts.NewChart)
chartStore.Charts = map[uri.URI]*charts.Chart{rootUri: chart}
h := &langHandler{
chartStore: chartStore,
documents: documents,
yamllsConnector: &yamlls.Connector{},
helmlsConfig: util.DefaultConfig,
}

h.LoadDocsOnNewChart(chart)
Expand Down Expand Up @@ -90,18 +102,20 @@ func TestDefinitionChart(t *testing.T) {
}
}

func getPosition(tC testCase, lines []string) lsp.Position {
func getPosition(tC testCase, lines []string) (lsp.Position, bool) {
col := strings.Index(tC.templateLineWithMarker, "^")
buf := strings.Replace(tC.templateLineWithMarker, "^", "", 1)
line := uint32(0)
found := false

for i, v := range lines {
if strings.Contains(v, buf) {
found = true
line = uint32(i)
col = col + strings.Index(v, buf)
break
}
}
pos := lsp.Position{Line: line, Character: uint32(col)}
return pos
return pos, found
}
5 changes: 3 additions & 2 deletions internal/language_features/includes.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package languagefeatures
import (
lsp "go.lsp.dev/protocol"

"github.com/mrjosh/helm-ls/internal/charts"
lsplocal "github.com/mrjosh/helm-ls/internal/lsp"
"github.com/mrjosh/helm-ls/internal/protocol"
"github.com/mrjosh/helm-ls/internal/tree-sitter/gotemplate"
Expand Down Expand Up @@ -91,7 +92,7 @@ func (f *IncludesFeature) getReferenceLocations(includeName string) []lsp.Locati
locations = append(locations, util.RangeToLocation(doc.URI, referenceRange))
}
if len(locations) > 0 {
doc.SyncToDisk()
charts.SyncToDisk(doc)
}
}

Expand All @@ -106,7 +107,7 @@ func (f *IncludesFeature) getDefinitionLocations(includeName string) []lsp.Locat
locations = append(locations, util.RangeToLocation(doc.URI, referenceRange))
}
if len(locations) > 0 {
doc.SyncToDisk()
charts.SyncToDisk(doc)
}
}

Expand Down
9 changes: 8 additions & 1 deletion internal/language_features/template_context.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (

lsp "go.lsp.dev/protocol"

"github.com/mrjosh/helm-ls/internal/charts"
helmdocs "github.com/mrjosh/helm-ls/internal/documentation/helm"
lsplocal "github.com/mrjosh/helm-ls/internal/lsp"
"github.com/mrjosh/helm-ls/internal/protocol"
Expand Down Expand Up @@ -70,7 +71,13 @@ func (f *TemplateContextFeature) getDefinitionLocations(templateContext lsplocal
switch templateContext[0] {
case "Values":
for _, value := range f.Chart.ResolveValueFiles(templateContext.Tail(), f.ChartStore) {
locations = append(locations, value.ValuesFiles.GetPositionsForValue(value.Selector)...)
locs := value.ValuesFiles.GetPositionsForValue(value.Selector)
if len(locs) > 0 {
for _, valuesFile := range value.ValuesFiles.AllValuesFiles() {
charts.SyncToDisk(valuesFile)
}
}
locations = append(locations, locs...)
}
return locations
case "Chart":
Expand Down
25 changes: 6 additions & 19 deletions internal/lsp/document.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,8 @@ package lsp
import (
"bytes"
"fmt"
"os"
"path/filepath"
"strings"

"github.com/mrjosh/helm-ls/internal/charts"
"github.com/mrjosh/helm-ls/internal/util"
sitter "github.com/smacker/go-tree-sitter"
lsp "go.lsp.dev/protocol"
Expand Down Expand Up @@ -82,22 +79,12 @@ func (d *Document) getLines() []string {
return d.lines
}

// SyncToDisk writes the content of the document to disk if it is a dependency file.
// If it is a dependency file, it was read from a archive, so we need to write it back,
// to be able to open it in a editor when using go-to-definition or go-to-reference.
func (d *Document) SyncToDisk() {
if !d.IsDependencyFile() {
return
}
err := os.MkdirAll(filepath.Dir(d.Path), 0o755)
if err == nil {
err = os.WriteFile(d.Path, []byte(d.Content), 0o444)
}
if err != nil {
logger.Error(err.Error())
}
// GetContent implements PossibleDependencyFile.
func (d *Document) GetContent() string {
return d.Content
}

func (d *Document) IsDependencyFile() bool {
return strings.Contains(d.Path, charts.DependencyCacheFolder)
// GetPath implements PossibleDependencyFile.
func (d *Document) GetPath() string {
return d.Path
}
2 changes: 1 addition & 1 deletion internal/lsp/document_store.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ func (s *DocumentStore) DidOpen(params *lsp.DidOpenTextDocumentParams, helmlsCon
func (s *DocumentStore) Store(filename string, content []byte, helmlsConfig util.HelmlsConfiguration) {
ast := ParseAst(nil, string(content))
fileUri := uri.File(filename)
s.documents.Store(fileUri,
s.documents.Store(fileUri.Filename(),
&Document{
URI: fileUri,
Path: filename,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
global:
subchart: works

subchartWithoutGlobal: works
Loading

0 comments on commit 4350412

Please sign in to comment.