Skip to content

Commit

Permalink
feat: rework diagnostics
Browse files Browse the repository at this point in the history
  • Loading branch information
qvalentin committed May 11, 2024
1 parent 46aaa98 commit 5a1d672
Show file tree
Hide file tree
Showing 5 changed files with 155 additions and 86 deletions.
2 changes: 1 addition & 1 deletion internal/adapter/yamlls/documentSync.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ func (yamllsConnector Connector) DocumentDidChangeFullSync(doc *lsplocal.Documen
return
}

logger.Println("Sending DocumentDidChange with full sync, current content:", doc.Content)
logger.Debug("Sending DocumentDidChange with full sync, current content:", doc.Content)
trimmedText := lsplocal.TrimTemplate(doc.Ast.Copy(), doc.Content)

params.ContentChanges = []lsp.TextDocumentContentChangeEvent{
Expand Down
22 changes: 18 additions & 4 deletions internal/handler/text_document.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,16 @@ func (h *langHandler) DidOpen(ctx context.Context, params *lsp.DidOpenTextDocume
if err != nil {
logger.Error("Error getting chart info for file", doc.URI, err)
}
notification := lsplocal.GetDiagnosticsNotification(chart, doc)
notifications := lsplocal.GetDiagnosticsNotifications(chart, doc)

return h.client.PublishDiagnostics(ctx, notification)
defer func() {
for _, notification := range notifications {
logger.Println("Publishing", notification)
h.client.PublishDiagnostics(ctx, &notification)

Check failure on line 36 in internal/handler/text_document.go

View workflow job for this annotation

GitHub Actions / lint (1.21.5, ubuntu-latest)

Error return value of `h.client.PublishDiagnostics` is not checked (errcheck)
}
}()

return nil
}

func (h *langHandler) DidClose(ctx context.Context, params *lsp.DidCloseTextDocumentParams) (err error) {
Expand All @@ -48,9 +55,16 @@ func (h *langHandler) DidSave(ctx context.Context, params *lsp.DidSaveTextDocume
}

h.yamllsConnector.DocumentDidSave(doc, *params)
notification := lsplocal.GetDiagnosticsNotification(chart, doc)
notifications := lsplocal.GetDiagnosticsNotifications(chart, doc)

return h.client.PublishDiagnostics(ctx, notification)
defer func() {
for _, notification := range notifications {
logger.Println("Publishing", notification)
h.client.PublishDiagnostics(ctx, &notification)

Check failure on line 63 in internal/handler/text_document.go

View workflow job for this annotation

GitHub Actions / lint (1.21.5, ubuntu-latest)

Error return value of `h.client.PublishDiagnostics` is not checked (errcheck)
}
}()

return nil
}

func (h *langHandler) DidChange(ctx context.Context, params *lsp.DidChangeTextDocumentParams) (err error) {
Expand Down
161 changes: 82 additions & 79 deletions internal/lsp/lint.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package lsp

import (
"fmt"
"path/filepath"
"strconv"
"strings"

Expand All @@ -13,126 +14,128 @@ import (
lsp "go.lsp.dev/protocol"
"go.lsp.dev/uri"
"helm.sh/helm/v3/pkg/action"
// "helm.sh/helm/v3/pkg/lint/rules"

"helm.sh/helm/v3/pkg/chartutil"
"helm.sh/helm/v3/pkg/lint/support"
)

var logger = log.GetLogger()

func GetDiagnosticsNotification(chart *charts.Chart, doc *Document) *lsp.PublishDiagnosticsParams {
func GetDiagnosticsNotifications(chart *charts.Chart, doc *Document) []lsp.PublishDiagnosticsParams {
vals := chart.ValuesFiles.MainValuesFile.Values
if chart.ValuesFiles.OverlayValuesFile != nil {
vals = chartutil.CoalesceTables(chart.ValuesFiles.OverlayValuesFile.Values, chart.ValuesFiles.MainValuesFile.Values)
}

diagnostics := GetDiagnostics(doc.URI, vals)
doc.DiagnosticsCache.HelmDiagnostics = diagnostics

return &lsp.PublishDiagnosticsParams{
URI: doc.URI,
Diagnostics: doc.DiagnosticsCache.GetMergedDiagnostics(),
diagnostics := GetDiagnostics(chart.RootURI, vals)

// Update the diagnostics cache only for the currently opened document
// as it will also get diagnostics from yamlls
// if currentDocDiagnostics is empty it means that all issues in that file have been fixed
// we need to send this to the client
currentDocDiagnostics := diagnostics[string(doc.URI.Filename())]
doc.DiagnosticsCache.HelmDiagnostics = currentDocDiagnostics
diagnostics[string(doc.URI.Filename())] = doc.DiagnosticsCache.GetMergedDiagnostics()

result := []lsp.PublishDiagnosticsParams{}

for diagnosticsUri, diagnostics := range diagnostics {

Check failure on line 42 in internal/lsp/lint.go

View workflow job for this annotation

GitHub Actions / lint (1.21.5, ubuntu-latest)

var-naming: range var diagnosticsUri should be diagnosticsURI (revive)
result = append(result,
lsp.PublishDiagnosticsParams{
URI: uri.File(diagnosticsUri),
Diagnostics: diagnostics,
},
)
}

return result
}

// GetDiagnostics will run helm linter against the currect document URI using the given values
// GetDiagnostics will run helm linter against the chart root URI using the given values
// and converts the helm.support.Message to lsp.Diagnostics
func GetDiagnostics(uri uri.URI, vals chartutil.Values) []lsp.Diagnostic {
var (
filename = uri.Filename()
paths = strings.Split(filename, "/")
dir = strings.Join(paths, "/")
diagnostics = make([]lsp.Diagnostic, 0)
)

pathfile := ""

for i, p := range paths {
if p == "templates" {
dir = strings.Join(paths[0:i], "/")
pathfile = strings.Join(paths[i:], "/")
}
}
func GetDiagnostics(rootURI uri.URI, vals chartutil.Values) map[string][]lsp.Diagnostic {
diagnostics := map[string][]lsp.Diagnostic{}

client := action.NewLint()

result := client.Run([]string{dir}, vals)
logger.Println(fmt.Sprintf("helm lint: result for file %s : %s", uri, result.Messages))
result := client.Run([]string{rootURI.Filename()}, vals)

for _, msg := range result.Messages {
d, filename, err := GetDiagnosticFromLinterErr(msg)
if err != nil {
continue
}
if filename != pathfile {
continue
d, relativeFilePath, _ := GetDiagnosticFromLinterErr(msg)
absoluteFilePath := filepath.Join(rootURI.Filename(), string(relativeFilePath))
if d != nil {
diagnostics[absoluteFilePath] = append(diagnostics[absoluteFilePath], *d)
}
diagnostics = append(diagnostics, *d)
}
logger.Println(fmt.Sprintf("helm lint: result for file %s : %v", uri, diagnostics))
logger.Println(fmt.Sprintf("helm lint: result for chart %s : %v", rootURI.Filename(), diagnostics))

return diagnostics
}

func GetDiagnosticFromLinterErr(supMsg support.Message) (*lsp.Diagnostic, string, error) {
var (
err error
msg string
line = 1
severity lsp.DiagnosticSeverity
filename = getFilePathFromLinterErr(supMsg)
)

switch supMsg.Severity {
case support.ErrorSev:

severity = lsp.DiagnosticSeverityError

// if superr, ok := supMsg.Err.(*rules.YAMLToJSONParseError); ok {
severity := parseSeverity(supMsg)

// line = superr.Line
// msg = superr.Error()
//
// } else {

fileLine := util.BetweenStrings(supMsg.Error(), "(", ")")
fileLineArr := strings.Split(fileLine, ":")
if len(fileLineArr) < 2 {
return nil, filename, errors.Errorf("linter Err contains no position information")
}
lineStr := fileLineArr[1]
line, err = strconv.Atoi(lineStr)
if strings.HasPrefix(supMsg.Path, "templates") {
message, err := parseTemplatesMessage(supMsg, severity)
path := getFilePathFromLinterErr(supMsg)
if err != nil {
return nil, filename, err
return nil, "", err
}
msgStr := util.AfterStrings(supMsg.Error(), "):")
msg = strings.TrimSpace(msgStr)

// }

case support.WarningSev:

// severity = lsp.DiagnosticSeverityWarning
// if err, ok := supMsg.Err.(*rules.MetadataError); ok {
// line = 1
// msg = err.Details().Error()
// }
return &message, path, nil
}

case support.InfoSev:
message := string(supMsg.Err.Error())
// NOTE: The diagnostics may not be shown correctly in the Chart.yaml file in neovim
// because the lsp is not active for that file
if supMsg.Path == "Chart.yaml" || strings.Contains(message, "chart metadata") {
return &lsp.Diagnostic{
Severity: severity,
Source: "Helm lint",
Message: message,
}, "Chart.yaml", nil
}

severity = lsp.DiagnosticSeverityInformation
msg = supMsg.Err.Error()
return nil, "", nil
}

func parseTemplatesMessage(supMsg support.Message, severity lsp.DiagnosticSeverity) (lsp.Diagnostic, error) {
var err error
line := 1

Check failure on line 103 in internal/lsp/lint.go

View workflow job for this annotation

GitHub Actions / lint (1.21.5, ubuntu-latest)

ineffectual assignment to line (ineffassign)
fileLine := util.BetweenStrings(supMsg.Error(), "(", ")")
fileLineArr := strings.Split(fileLine, ":")
if len(fileLineArr) < 2 {
return lsp.Diagnostic{}, errors.Errorf("linter Err contains no position information")
}
lineStr := fileLineArr[1]
line, err = strconv.Atoi(lineStr)
if err != nil {
return lsp.Diagnostic{}, err
}
msgStr := util.AfterStrings(supMsg.Error(), "):")
msg := strings.TrimSpace(msgStr)

return &lsp.Diagnostic{
return lsp.Diagnostic{
Range: lsp.Range{
Start: lsp.Position{Line: uint32(line - 1)},
End: lsp.Position{Line: uint32(line - 1)},
},
Severity: severity,
Source: "Helm lint",
Message: msg,
}, filename, nil
}, nil
}

func parseSeverity(supMsg support.Message) lsp.DiagnosticSeverity {
var severity lsp.DiagnosticSeverity
switch supMsg.Severity {
case support.ErrorSev:
severity = lsp.DiagnosticSeverityError
case support.WarningSev:
severity = lsp.DiagnosticSeverityWarning
case support.InfoSev:
severity = lsp.DiagnosticSeverityInformation
}
return severity
}

func getFilePathFromLinterErr(msg support.Message) string {
Expand Down
53 changes: 52 additions & 1 deletion internal/lsp/lint_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,63 @@ package lsp
import (
"testing"

"github.com/mrjosh/helm-ls/internal/charts"
"github.com/stretchr/testify/assert"
"go.lsp.dev/uri"
"helm.sh/helm/v3/pkg/chartutil"
)

func TestLint(t *testing.T) {
diagnostics := GetDiagnostics(uri.File("../../testdata/example/templates/lint.yaml"), chartutil.Values{})
diagnostics := GetDiagnostics(uri.File("../../testdata/example"), chartutil.Values{})
assert.NotEmpty(t, diagnostics)
assert.Len(t, diagnostics, 2)
assert.Len(t, diagnostics[uri.File("../../testdata/example/Chart.yaml").Filename()], 2)
}

func TestLintNotifications(t *testing.T) {
chart := charts.Chart{
RootURI: uri.File("../../testdata/example"),
ValuesFiles: &charts.ValuesFiles{
MainValuesFile: &charts.ValuesFile{},
OverlayValuesFile: &charts.ValuesFile{},
AdditionalValuesFiles: []*charts.ValuesFile{},
},
}
diagnostics := GetDiagnosticsNotifications(&chart, &Document{URI: uri.File("../../testdata/example/templates/deployment-no-templates.yaml")})
assert.NotEmpty(t, diagnostics)
assert.Len(t, diagnostics, 3)

uris := []string{}
for _, notification := range diagnostics {
uris = append(uris, notification.URI.Filename())
}
assert.Contains(t, uris, uri.File("../../testdata/example/templates/deployment-no-templates.yaml").Filename())
for _, notification := range diagnostics {
if notification.URI.Filename() == uri.File("../../testdata/example/templates/deployment-no-templates.yaml").Filename() {
assert.Empty(t, notification.Diagnostics)
}
}
}

func TestLintNotificationsIncludesEmptyDiagnosticsForFixedIssues(t *testing.T) {
chart := charts.Chart{
RootURI: uri.File("../../testdata/example"),
ValuesFiles: &charts.ValuesFiles{
MainValuesFile: &charts.ValuesFile{},
OverlayValuesFile: &charts.ValuesFile{},
AdditionalValuesFiles: []*charts.ValuesFile{},
},
}
diagnostics := GetDiagnosticsNotifications(&chart, &Document{URI: uri.File("../../testdata/example/templates/deployment-no-templates.yaml")})

uris := []string{}
for _, notification := range diagnostics {
uris = append(uris, notification.URI.Filename())
}
assert.Contains(t, uris, uri.File("../../testdata/example/templates/deployment-no-templates.yaml").Filename())
for _, notification := range diagnostics {
if notification.URI.Filename() == uri.File("../../testdata/example/templates/deployment-no-templates.yaml").Filename() {
assert.Empty(t, notification.Diagnostics)
}
}
}
3 changes: 2 additions & 1 deletion internal/util/values.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,8 @@ func valuesLookup(values chartutil.Values, splittedVar []string) (chartutil.Valu

// PathValue takes a path that traverses a YAML structure and returns the value at the end of that path.
// The path starts at the root of the YAML structure and is comprised of YAML keys separated by periods.
// Given the following YAML data the value at path "chapter.one.title" is "Loomings".
// Given the following YAML data the value at path "chapter.one.title" is "Loomings". The path can also
// include array indexes as in "chapters[].title" which will use the first element of the array.
//
// chapter:
// one:
Expand Down

0 comments on commit 5a1d672

Please sign in to comment.