refactor: use context for automatic lsp process cleanup

Nacho Vazquez created

Change summary

cmd/root.go              |  1 -
internal/app/services.go | 18 +-----------------
internal/lsp/client.go   |  4 ++--
3 files changed, 3 insertions(+), 20 deletions(-)

Detailed changes

cmd/root.go 🔗

@@ -48,7 +48,6 @@ var rootCmd = &cobra.Command{
 		ctx := context.Background()
 
 		app := app.New(ctx, conn)
-		defer app.Close()
 		logging.Info("Starting termai...")
 		zone.NewGlobal()
 		tui := tea.NewProgram(

internal/app/services.go 🔗

@@ -3,7 +3,6 @@ package app
 import (
 	"context"
 	"database/sql"
-	"log/slog"
 
 	"github.com/kujtimiihoxha/termai/internal/config"
 	"github.com/kujtimiihoxha/termai/internal/db"
@@ -23,8 +22,6 @@ type App struct {
 	Permissions permission.Service
 
 	LSPClients map[string]*lsp.Client
-
-	ceanups []func()
 }
 
 func New(ctx context.Context, conn *sql.DB) *App {
@@ -44,10 +41,7 @@ func New(ctx context.Context, conn *sql.DB) *App {
 	}
 
 	for name, client := range cfg.LSP {
-		lspClient, err := lsp.NewClient(client.Command, client.Args...)
-		app.ceanups = append(app.ceanups, func() {
-			lspClient.Close()
-		})
+		lspClient, err := lsp.NewClient(ctx, client.Command, client.Args...)
 		workspaceWatcher := watcher.NewWorkspaceWatcher(lspClient)
 		if err != nil {
 			logging.Error("Failed to create LSP client for", name, err)
@@ -64,13 +58,3 @@ func New(ctx context.Context, conn *sql.DB) *App {
 	}
 	return app
 }
-
-func (a *App) Close() {
-	for _, cleanup := range a.ceanups {
-		cleanup()
-	}
-	for _, client := range a.LSPClients {
-		client.Close()
-	}
-	slog.Info("App closed")
-}

internal/lsp/client.go 🔗

@@ -48,8 +48,8 @@ type Client struct {
 	openFilesMu sync.RWMutex
 }
 
-func NewClient(command string, args ...string) (*Client, error) {
-	cmd := exec.Command(command, args...)
+func NewClient(ctx context.Context, command string, args ...string) (*Client, error) {
+	cmd := exec.CommandContext(ctx, command, args...)
 	// Copy env
 	cmd.Env = os.Environ()