Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: better error handling and linting based on golangci-lint #8

Merged
merged 6 commits into from
Nov 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@ jobs:
- uses: actions/setup-go@v5
with:
go-version: 1.23.1
- run: go test -v ./...
- name: Install slangroom-exec
run: make build
- name: Run test
run: go test -v ./...
release:
runs-on: ubuntu-latest
needs: test
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,6 @@
!Makefile

!contracts/**/*
!vendor/modules.txt
# ...even if they are in subdirectories
!*/
2 changes: 1 addition & 1 deletion .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ issues:
linters:
enable:
- bodyclose
- exportloopref
- copyloopvar
- goimports
- gosec
- nilerr
Expand Down
72 changes: 43 additions & 29 deletions cmd/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"embed"
"encoding/json"
"fmt"
"log"
"os"
"path/filepath"
"strings"
Expand All @@ -18,11 +19,9 @@ import (
var contracts embed.FS
var daemon bool

var extension string = ".slang"

// rootCmd is the base command when called without any subcommands.
// It initializes the command tree and is responsible for starting the Gemini CLI.
var extension = ".slang"

// runCmd is the base command when called without any subcommands.
func Execute(embeddedFiles embed.FS) {
contracts = embeddedFiles

Expand All @@ -31,7 +30,7 @@ func Execute(embeddedFiles embed.FS) {

// Execute the root command
if err := runCmd.Execute(); err != nil {
fmt.Println(err)
log.Println(err)
os.Exit(1)
}
}
Expand All @@ -48,15 +47,15 @@ var listCmd = &cobra.Command{
Use: "list [folder]",
Short: "List all contracts in the folder or list embedded contracts if no folder is specified",
Args: cobra.MaximumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
Run: func(_ *cobra.Command, args []string) {
if len(args) == 0 {
// If no folder argument is provided, list embedded files
fmt.Println("Listing embedded slangroom files:")

// If the daemon flag is set, start the HTTP server
if daemon {
if err := httpserver.StartHTTPServer("contracts", "", nil); err != nil {
fmt.Printf("Failed to start HTTP server: %v\n", err)
log.Printf("Failed to start HTTP server: %v\n", err)
os.Exit(1)
}
return
Expand All @@ -65,7 +64,7 @@ var listCmd = &cobra.Command{
fmt.Printf("Found file: %s (Path: %s)\n", strings.TrimSuffix(file.FileName, extension), file.Path)
})
if err != nil {
fmt.Println("Error:", err)
log.Println("Error:", err)
}
} else {
// If a folder argument is provided, list files in that folder
Expand All @@ -74,7 +73,7 @@ var listCmd = &cobra.Command{

if daemon {
if err := httpserver.StartHTTPServer(folder, "", nil); err != nil {
fmt.Printf("Failed to start HTTP server: %v\n", err)
log.Printf("Failed to start HTTP server: %v\n", err)
os.Exit(1)
}
return
Expand All @@ -85,7 +84,7 @@ var listCmd = &cobra.Command{
fmt.Printf("Found file: %s (Path: %s)\n", strings.TrimSuffix(file.FileName, extension), file.Path)
})
if err != nil {
fmt.Println("Error:", err)
log.Println("Error:", err)
}
}
},
Expand Down Expand Up @@ -128,19 +127,25 @@ func addEmbeddedFileCommands() {

metadataPath := filepath.Join(file.Dir, strings.TrimSuffix(file.FileName, filepath.Ext(file.FileName))+".metadata.json")
metadata, err := utils.LoadMetadata(&contracts, metadataPath)
if err == nil {
if err != nil && err.Error() != "metadata file not found" {
log.Printf("WARNING: error in metadata for contracts: %s\n", fileCmdName)
log.Println(err)
} else if err == nil {
isMetadata = true
// Set command description
fileCmd.Short = metadata.Description
argContents, flagContents = utils.ConfigureArgumentsAndFlags(fileCmd, metadata)
fileCmd.PreRunE = func(cmd *cobra.Command, args []string) error {
argContents, flagContents, err = utils.ConfigureArgumentsAndFlags(fileCmd, metadata)
if err != nil {
log.Printf("Failed to set arguments or flags: %v\n", err)
os.Exit(1)
}
fileCmd.PreRunE = func(cmd *cobra.Command, _ []string) error {
return utils.ValidateFlags(cmd, flagContents, argContents)
}

}

// Set the command's run function
fileCmd.Run = func(cmd *cobra.Command, args []string) {
fileCmd.Run = func(_ *cobra.Command, args []string) {
runFileCommand(file, args, metadata, argContents, isMetadata, relativePath)
}

Expand All @@ -149,7 +154,7 @@ func addEmbeddedFileCommands() {
})

if err != nil {
fmt.Println("Error adding embedded file commands:", err)
log.Println("Error adding embedded file commands:", err)
}
}

Expand All @@ -159,7 +164,7 @@ var runCmd = &cobra.Command{
Use: "gemini [folder]",
Short: "Execute a specific slangroom file in a dynamically specified folder",
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
Run: func(_ *cobra.Command, args []string) {
folder := args[0]
filePath := filepath.Join(args[1:]...)
input := slangroom.SlangroomInput{}
Expand All @@ -174,12 +179,17 @@ var runCmd = &cobra.Command{
if relativeFilePath == filePath {
found = true
input.Contract = file.Content
utils.LoadAdditionalData(filepath.Join(folder, file.Dir), filename, &input)
err := utils.LoadAdditionalData(filepath.Join(folder, file.Dir), filename, &input)

if err != nil {
log.Printf("Failed to load data from JSON file: %v\n", err)
os.Exit(1)
}

// Start HTTP server if daemon flag is set
if daemon {
if err := httpserver.StartHTTPServer(folder, filePath, nil); err != nil {
fmt.Printf("Failed to start HTTP server: %v\n", err)
log.Printf("Failed to start HTTP server: %v\n", err)
os.Exit(1)
}
return
Expand All @@ -188,29 +198,33 @@ var runCmd = &cobra.Command{
// Execute the slangroom file
res, err := slangroom.Exec(input)
if err != nil {
fmt.Println("Error:", err)
fmt.Println(res.Logs)
log.Println("Error:", err)
log.Println(res.Logs)
} else {
fmt.Println(res.Output)
}
}
})

if err != nil {
fmt.Println("Error:", err)
log.Println("Error:", err)
return
}

if !found {
fmt.Printf("File %s not found in folder %s\n", filePath, folder)
log.Printf("File %s not found in folder %s\n", filePath, folder)
}
},
}

func runFileCommand(file fouter.SlangFile, args []string, metadata *utils.CommandMetadata, argContents map[string]string, isMetadata bool, relativePath string) {
input := slangroom.SlangroomInput{Contract: file.Content}
filename := strings.TrimSuffix(file.FileName, extension)
utils.LoadAdditionalData(file.Dir, filename, &input)
err := utils.LoadAdditionalData(file.Dir, filename, &input)
if err != nil {
log.Printf("Failed to load data from JSON file: %v\n", err)
os.Exit(1)
}
if isMetadata {
for i, arg := range args {
if i < len(metadata.Arguments) {
Expand All @@ -220,12 +234,12 @@ func runFileCommand(file fouter.SlangFile, args []string, metadata *utils.Comman
// Convert argContents to JSON if needed
jsonData, err := json.Marshal(argContents)
if err != nil {
fmt.Println("Error encoding arguments to JSON:", err)
log.Println("Error encoding arguments to JSON:", err)
return
}
if input.Data != "" {
if input.Data, err = utils.MergeJSON(input.Data, string(jsonData)); err != nil {
fmt.Println("Error encoding arguments to JSON:", err)
log.Println("Error encoding arguments to JSON:", err)
os.Exit(1)
}
} else {
Expand All @@ -235,7 +249,7 @@ func runFileCommand(file fouter.SlangFile, args []string, metadata *utils.Comman
// Start HTTP server if daemon flag is set
if daemon {
if err := httpserver.StartHTTPServer("contracts", relativePath, &input); err != nil {
fmt.Printf("Failed to start HTTP server: %v\n", err)
log.Printf("Failed to start HTTP server: %v\n", err)
os.Exit(1)
}
return
Expand All @@ -244,8 +258,8 @@ func runFileCommand(file fouter.SlangFile, args []string, metadata *utils.Comman
// Execute the slangroom file
res, err := slangroom.Exec(input)
if err != nil {
fmt.Println("Error:", err)
fmt.Println(res.Logs)
log.Println("Error:", err)
log.Println(res.Logs)
} else {
fmt.Println(res.Output)
}
Expand Down
27 changes: 13 additions & 14 deletions cmd/cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (
)

func TestListCommand(t *testing.T) {

// Test listing embedded files
t.Run("List Embedded Files", func(t *testing.T) {
// Prepare the command without any arguments
Expand All @@ -31,11 +30,11 @@ func TestListCommand(t *testing.T) {
if !contains(output, "Listing embedded slangroom files:") {
t.Errorf("Expected output to contain 'Listing embedded slangroom files:', got %v", output)
}
if !contains(output, "Found file: hello.slang") {
t.Errorf("Expected output to contain 'Found file: hello.slang', got %v", output)
if !contains(output, "Found file: hello") {
t.Errorf("Expected output to contain 'Found file: hello', got %v", output)
}
if !contains(output, "Found file: test.slang") {
t.Errorf("Expected output to contain 'Found file: test.slang', got %v", output)
if !contains(output, "Found file: test") {
t.Errorf("Expected output to contain 'Found file: test', got %v", output)
}
})

Expand All @@ -45,12 +44,12 @@ func TestListCommand(t *testing.T) {
tempDir := t.TempDir()

// Create sample slangroom files for the folder
err := os.WriteFile(filepath.Join(tempDir, "file1.slang"), []byte("contract content 1"), 0644)
err := os.WriteFile(filepath.Join(tempDir, "file1.slang"), []byte("contract content 1"), 0600)
if err != nil {
t.Fatalf("Failed to create file1.slang: %v", err)
}

err = os.WriteFile(filepath.Join(tempDir, "file2.slang"), []byte("contract content 2"), 0644)
err = os.WriteFile(filepath.Join(tempDir, "file2.slang"), []byte("contract content 2"), 0600)
if err != nil {
t.Fatalf("Failed to create file2.slang: %v", err)
}
Expand All @@ -69,14 +68,14 @@ func TestListCommand(t *testing.T) {

// Verify the output for files in the folder
output := out.String()
if !contains(output, "Listing slangroom files in folder:") {
t.Errorf("Expected output to contain 'Listing slangroom files in folder:', got %v", output)
if !contains(output, "Listing contracts in folder:") {
t.Errorf("Expected output to contain 'Listing contracts in folder:', got %v", output)
}
if !contains(output, "Found file: file1.slang") {
t.Errorf("Expected output to contain 'Found file: file1.slang', got %v", output)
if !contains(output, "Found file: file1") {
t.Errorf("Expected output to contain 'Found file: file1', got %v", output)
}
if !contains(output, "Found file: file2.slang") {
t.Errorf("Expected output to contain 'Found file: file2.slang', got %v", output)
if !contains(output, "Found file: file2") {
t.Errorf("Expected output to contain 'Found file: file2', got %v", output)
}
})
}
Expand All @@ -88,7 +87,7 @@ func TestRunCommand(t *testing.T) {
// Write a sample slangroom file in the filesystem directory
content := `Given nothing
Then print the string 'Hello'`
err := os.WriteFile(filepath.Join(tempDir, "test.slang"), []byte(content), 0644)
err := os.WriteFile(filepath.Join(tempDir, "test.slang"), []byte(content), 0600)
if err != nil {
t.Fatalf("Failed to create test.slang: %v", err)
}
Expand Down
Loading