Skip to content

Commit

Permalink
lsp: Rename correctly when conflicting (StyraInc#1334)
Browse files Browse the repository at this point in the history
* lsp: Rename correctly when conflicting

This updates the server's rename quick action to use the same name
generation conflict resolution logic as the fixer.

This is done by allowing the server's cache to be used as a new file
provider and consolidating the logic for generating changes required for
the templating worker and command worker.

This also changes the inlay hints to exit early if the file is not
parsed. This reduces errors in the server logs when working with empty
files.

Signed-off-by: Charlie Egan <[email protected]>

* chore: Use strings for fixing file content

Signed-off-by: Charlie Egan <[email protected]>

* lsp: pass version lookup to ToInput

Signed-off-by: Charlie Egan <[email protected]>

* fixer: Add test to show fixes after rename

Signed-off-by: Charlie Egan <[email protected]>

* rules: VersionsMap for all instances of input

This adapts the LSP and fixer to use the versionsMap functionality in
the same way as the linter.

Signed-off-by: Charlie Egan <[email protected]>

---------

Signed-off-by: Charlie Egan <[email protected]>
  • Loading branch information
charlieegan3 authored Jan 15, 2025
1 parent 954df8c commit faa9c52
Show file tree
Hide file tree
Showing 28 changed files with 1,072 additions and 511 deletions.
10 changes: 8 additions & 2 deletions cmd/fix.go
Original file line number Diff line number Diff line change
Expand Up @@ -270,9 +270,15 @@ func fix(args []string, params *fixCommandParams) error {
return fmt.Errorf("could not find potential roots: %w", err)
}

versionsMap, err := config.AllRegoVersions(regalDir.Name(), &userConfig)
if err != nil {
return fmt.Errorf("failed to get all Rego versions: %w", err)
}

f := fixer.NewFixer()
f.RegisterRoots(roots...)
f.RegisterFixes(fixes.NewDefaultFixes()...)
f.SetRegoVersionsMap(versionsMap)

if !slices.Contains([]string{"error", "rename"}, params.conflictMode) {
return fmt.Errorf("invalid conflict mode: %s, expected 'error' or 'rename'", params.conflictMode)
Expand Down Expand Up @@ -393,7 +399,7 @@ please run fix from a clean state to support the use of git to undo, or use --fo
return fmt.Errorf("failed to get file %s: %w", file, err)
}

fmt.Fprintln(outputWriter, string(fc))
fmt.Fprintln(outputWriter, fc)
fmt.Fprintln(outputWriter, "----------")
}

Expand Down Expand Up @@ -438,7 +444,7 @@ please run fix from a clean state to support the use of git to undo, or use --fo
return fmt.Errorf("failed to create directory for file %s: %w", file, err)
}

if err = os.WriteFile(file, fc, fileMode); err != nil {
if err = os.WriteFile(file, []byte(fc), fileMode); err != nil {
return fmt.Errorf("failed to write file %s: %w", file, err)
}
}
Expand Down
10 changes: 6 additions & 4 deletions cmd/lint.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,9 +118,10 @@ func init() {
warningsFound := 0

for _, violation := range rep.Violations {
if violation.Level == "error" {
switch violation.Level {
case "error":
errorsFound++
} else if violation.Level == "warning" {
case "warning":
warningsFound++
}
}
Expand Down Expand Up @@ -407,7 +408,8 @@ func getWriterForOutputFile(filename string) (io.Writer, error) {

func formatError(format string, err error) error {
// currently, JSON and SARIF will get the same generic JSON error format
if format == formatJSON || format == formatSarif {
switch format {
case formatJSON, formatSarif:
bs, err := json.MarshalIndent(map[string]interface{}{
"errors": []string{err.Error()},
}, "", " ")
Expand All @@ -416,7 +418,7 @@ func formatError(format string, err error) error {
}

return fmt.Errorf("%s", string(bs))
} else if format == formatJunit {
case formatJunit:
testSuites := junit.Testsuites{
Name: "regal",
}
Expand Down
4 changes: 2 additions & 2 deletions e2e/cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,7 @@ func TestLintV0WithRegoV1ImportViolations(t *testing.T) {
expectExitCode(t, err, 3, &stdout, &stderr)

if exp, act := "", stderr.String(); exp != act {
t.Errorf("expected stderr %q, got %q", exp, act)
t.Errorf("expected stderr:\n%s\ngot\n%s", exp, act)
}

var rep report.Report
Expand Down Expand Up @@ -865,7 +865,7 @@ project:
- path: v0
rego-version: 0
- path: v1
rego-version: 0
rego-version: 1
`,
"foo/main.rego": `package wow
Expand Down
47 changes: 47 additions & 0 deletions internal/lsp/cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,53 @@ func (c *Cache) SetModule(fileURI string, module *ast.Module) {
c.modules.Set(fileURI, module)
}

func (c *Cache) Rename(oldKey, newKey string) {
if content, ok := c.fileContents.Get(oldKey); ok {
c.fileContents.Set(newKey, content)
c.fileContents.Delete(oldKey)
}

if content, ok := c.ignoredFileContents.Get(oldKey); ok {
c.ignoredFileContents.Set(newKey, content)
c.ignoredFileContents.Delete(oldKey)
}

if module, ok := c.modules.Get(oldKey); ok {
c.modules.Set(newKey, module)
c.modules.Delete(oldKey)
}

if aggregates, ok := c.aggregateData.Get(oldKey); ok {
c.aggregateData.Set(newKey, aggregates)
c.aggregateData.Delete(oldKey)
}

if diagnostics, ok := c.diagnosticsFile.Get(oldKey); ok {
c.diagnosticsFile.Set(newKey, diagnostics)
c.diagnosticsFile.Delete(oldKey)
}

if parseErrors, ok := c.diagnosticsParseErrors.Get(oldKey); ok {
c.diagnosticsParseErrors.Set(newKey, parseErrors)
c.diagnosticsParseErrors.Delete(oldKey)
}

if builtinPositions, ok := c.builtinPositionsFile.Get(oldKey); ok {
c.builtinPositionsFile.Set(newKey, builtinPositions)
c.builtinPositionsFile.Delete(oldKey)
}

if keywordLocations, ok := c.keywordLocationsFile.Get(oldKey); ok {
c.keywordLocationsFile.Set(newKey, keywordLocations)
c.keywordLocationsFile.Delete(oldKey)
}

if refs, ok := c.fileRefs.Get(oldKey); ok {
c.fileRefs.Set(newKey, refs)
c.fileRefs.Delete(oldKey)
}
}

// SetFileAggregates will only set aggregate data for the provided URI. Even if
// data for other files is provided, only the specified URI is updated.
func (c *Cache) SetFileAggregates(fileURI string, data map[string][]report.Aggregate) {
Expand Down
27 changes: 27 additions & 0 deletions internal/lsp/cache/cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"reflect"
"testing"

"github.com/open-policy-agent/opa/v1/ast"

"github.com/styrainc/regal/internal/lsp/types"
"github.com/styrainc/regal/pkg/report"
)
Expand Down Expand Up @@ -159,3 +161,28 @@ func TestPartialDiagnosticsUpdate(t *testing.T) {
t.Fatalf("unexpected diagnostics: %v", foundDiags)
}
}

func TestCacheRename(t *testing.T) {
t.Parallel()

c := NewCache()

c.SetFileContents("file:///tmp/foo.rego", "package foo")
c.SetModule("file:///tmp/foo.rego", &ast.Module{})

c.Rename("file:///tmp/foo.rego", "file:///tmp/bar.rego")

_, ok := c.GetFileContents("file:///tmp/foo.rego")
if ok {
t.Fatalf("expected foo.rego to be removed")
}

contents, ok := c.GetFileContents("file:///tmp/bar.rego")
if !ok {
t.Fatalf("expected bar.rego to be present")
}

if contents != "package foo" {
t.Fatalf("unexpected contents: %s", contents)
}
}
Loading

0 comments on commit faa9c52

Please sign in to comment.