Skip to content

Commit

Permalink
lsp: Add test for server templating
Browse files Browse the repository at this point in the history
Signed-off-by: Charlie Egan <charlie@styra.com>
  • Loading branch information
charlieegan3 committed Sep 4, 2024
1 parent 38379ae commit 197295c
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 2 deletions.
2 changes: 1 addition & 1 deletion internal/lsp/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -1757,7 +1757,7 @@ func (l *LanguageServer) handleTextDocumentFormatting(
}

// if the file is empty, then the formatters will fail, so we template
// intstead
// instead
if oldContent == "" {
newContent, err := l.templateContentsForFile(params.TextDocument.URI)
if err != nil {
Expand Down
58 changes: 58 additions & 0 deletions internal/lsp/server_template_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package lsp

import (
"os"
"path/filepath"
"testing"

"github.com/styrainc/regal/internal/lsp/clients"
"github.com/styrainc/regal/internal/lsp/uri"
)

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

s := NewLanguageServer(
&LanguageServerOptions{
ErrorLog: os.Stderr,
},
)

td := t.TempDir()

filePath := filepath.Join(td, "foo/bar/baz.rego")
regalPath := filepath.Join(td, ".regal/config.yaml")

initialState := map[string]string{
filePath: "",
regalPath: "",
}

// create the initial state needed for the regal config root detection
for file := range initialState {
fileDir := filepath.Dir(file)

err := os.MkdirAll(fileDir, 0o755)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}

err = os.WriteFile(file, []byte(""), 0o600)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
}

fileURI := uri.FromPath(clients.IdentifierGeneric, filePath)

s.cache.SetFileContents(fileURI, "")

newContents, err := s.templateContentsForFile(fileURI)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}

if newContents != "package foo.bar\n\nimport rego.v1\n" {
t.Fatalf("unexpected contents: %v", newContents)
}
}
6 changes: 5 additions & 1 deletion pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,11 @@ func FindBundleRootDirectories(path string) ([]string, error) {

// This will traverse the tree **downwards** searching for .regal directories
// Not using rio.WalkFiles here as we're specifically looking for directories
if err := filepath.WalkDir(path, func(path string, info os.DirEntry, _ error) error {
if err := filepath.WalkDir(path, func(path string, info os.DirEntry, err error) error {
if err != nil {
return fmt.Errorf("failed to walk path: %w", err)
}

if info.IsDir() && info.Name() == regalDirName {
// Opening files as part of walking is generally not a good idea...
// but I think we can assume the number of .regal directories in a project
Expand Down

0 comments on commit 197295c

Please sign in to comment.