Skip to content
New issue

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

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

Already on GitHub? # to your account

feat: run cadinal editor on dev mode #53

Merged
merged 1 commit into from
Apr 1, 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
72 changes: 72 additions & 0 deletions cmd/world/cardinal/dev.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,36 @@ import (
"errors"
"fmt"
"net"
"net/http"
"os"
"os/exec"
"os/signal"
"path/filepath"
"runtime"
"syscall"
"time"

"github.com/argus-labs/fresh/runner"
"github.com/charmbracelet/lipgloss"
"github.com/magefile/mage/sh"
"github.com/spf13/cobra"

"pkg.world.dev/world-cli/common/logger"
"pkg.world.dev/world-cli/common/teacmd"
"pkg.world.dev/world-cli/tea/style"
)

const (
CardinalPort = "4040"
RedisPort = "6379"

// Cardinal Editor Port Range
cePortStart = 3000
cePortEnd = 4000

// Cardinal Editor Server Config
ceReadTimeout = 5 * time.Second

// flagWatch : Flag for hot reload support
flagWatch = "watch"
)
Expand All @@ -45,13 +56,31 @@ var devCmd = &cobra.Command{
startingMessage += " with hot reload support"
}

// Find an unused port for the Cardinal Editor
cardinalEditorPort, findPortError := findUnusedPort(cePortStart, cePortEnd)

fmt.Print(style.CLIHeader("Cardinal", startingMessage), "\n")
fmt.Println(style.BoldText.Render("Press Ctrl+C to stop"))
fmt.Println()
fmt.Printf("Redis: localhost:%s\n", RedisPort)
fmt.Printf("Cardinal: localhost:%s\n", CardinalPort)
if findPortError == nil {
fmt.Printf("Cardinal Editor: localhost:%d\n", cardinalEditorPort)
} else {
fmt.Println("Cardinal Editor: Failed to find an unused port")
}
fmt.Println()

// Run Cardinal Editor
// Cardinal will not blocking the process if it's failed to run
go func() {
err := runCardinalEditor(cardinalEditorPort)
if err != nil {
cmdStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("11"))
fmt.Println(cmdStyle.Render("Warning: Failed to run Cardinal Editor"))
}
}()

// Run Redis container
err := runRedis()
if err != nil {
Expand Down Expand Up @@ -236,3 +265,46 @@ func cleanup() error {

return nil
}

// runCardinalEditor runs the Cardinal Editor
func runCardinalEditor(port int) error {
workingDir, err := os.Getwd()
if err != nil {
return err
}
cardinalEditorDir := filepath.Join(workingDir, teacmd.TargetEditorDir)

// TODO: Check the version of cardinal and match it with cardinal editor version

// Check if the Cardinal Editor directory exists
if _, err := os.Stat(cardinalEditorDir); os.IsNotExist(err) {
// TODO: setup cardinal editor
return errors.New("cardinal editor dir is not found")
}

// Serve cardinal editor dir
fs := http.FileServer(http.Dir(cardinalEditorDir))
http.Handle("/", fs)

// Create a new HTTP server
server := &http.Server{
Addr: fmt.Sprintf(":%d", port),
ReadTimeout: ceReadTimeout,
}

// Start the server
return server.ListenAndServe()
}

// findUnusedPort finds an unused port in the range [start, end]
func findUnusedPort(start, end int) (int, error) {
for port := start; port <= end; port++ {
address := fmt.Sprintf(":%d", port)
listener, err := net.Listen("tcp", address)
if err == nil {
listener.Close()
return port, nil
}
}
return 0, fmt.Errorf("no available port in the range %d-%d", start, end)
}
6 changes: 6 additions & 0 deletions cmd/world/root/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package root
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
Expand Down Expand Up @@ -88,6 +89,11 @@ func checkLatestVersion() error {
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
logger.Debug(eris.Wrap(errors.New("status is not 200"), "error fetching the latest release"))
return nil
}

// Unmarshal the response body into the Release structure
var release Release
bodyBytes, err := io.ReadAll(resp.Body)
Expand Down
7 changes: 4 additions & 3 deletions common/teacmd/editor.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,10 @@ import (
)

const (
TargetEditorDir = ".editor"

latestReleaseURL = "https://api.github.com/repos/Argus-Labs/cardinal-editor/releases/latest"
httpTimeout = 2 * time.Second
targetEditorDir = ".editor"
cardinalProjectIDPlaceholder = "__CARDINAL_PROJECT_ID__"
)

Expand All @@ -46,15 +47,15 @@ func SetupCardinalEditor() error {
}

// rename version tag dir to .editor
err = copyDir(editorDir, targetEditorDir)
err = copyDir(editorDir, TargetEditorDir)
if err != nil {
return err
}

// rename project id
// "ce" prefix is added because guids can start with numbers, which is not allowed in js
projectID := "ce" + strippedGUID()
err = replaceProjectIDs(targetEditorDir, projectID)
err = replaceProjectIDs(TargetEditorDir, projectID)
if err != nil {
return err
}
Expand Down