client.go

  1package lsp
  2
  3import (
  4	"context"
  5	"encoding/json"
  6	"fmt"
  7	"log/slog"
  8	"maps"
  9	"os"
 10	"path/filepath"
 11	"strings"
 12	"sync/atomic"
 13	"time"
 14
 15	"github.com/charmbracelet/crush/internal/config"
 16	"github.com/charmbracelet/crush/internal/csync"
 17	"github.com/charmbracelet/crush/internal/fsext"
 18	powernap "github.com/charmbracelet/x/powernap/pkg/lsp"
 19	"github.com/charmbracelet/x/powernap/pkg/lsp/protocol"
 20	"github.com/charmbracelet/x/powernap/pkg/transport"
 21)
 22
 23type Client struct {
 24	client *powernap.Client
 25	name   string
 26
 27	// File types this LSP server handles (e.g., .go, .rs, .py)
 28	fileTypes []string
 29
 30	// Configuration for this LSP client
 31	config config.LSPConfig
 32
 33	// Diagnostic change callback
 34	onDiagnosticsChanged func(name string, count int)
 35
 36	// Diagnostic cache
 37	diagnostics *csync.VersionedMap[protocol.DocumentURI, []protocol.Diagnostic]
 38
 39	// Files are currently opened by the LSP
 40	openFiles *csync.Map[string, *OpenFileInfo]
 41
 42	// Server state
 43	serverState atomic.Value
 44}
 45
 46// New creates a new LSP client using the powernap implementation.
 47func New(ctx context.Context, name string, config config.LSPConfig) (*Client, error) {
 48	// Convert working directory to file URI
 49	workDir, err := os.Getwd()
 50	if err != nil {
 51		return nil, fmt.Errorf("failed to get working directory: %w", err)
 52	}
 53
 54	rootURI := string(protocol.URIFromPath(workDir))
 55
 56	// Create powernap client config
 57	clientConfig := powernap.ClientConfig{
 58		Command: config.Command,
 59		Args:    config.Args,
 60		RootURI: rootURI,
 61		Environment: func() map[string]string {
 62			env := make(map[string]string)
 63			maps.Copy(env, config.Env)
 64			return env
 65		}(),
 66		Settings:    config.Options,
 67		InitOptions: config.InitOptions,
 68		WorkspaceFolders: []protocol.WorkspaceFolder{
 69			{
 70				URI:  rootURI,
 71				Name: filepath.Base(workDir),
 72			},
 73		},
 74	}
 75
 76	// Create the powernap client
 77	powernapClient, err := powernap.NewClient(clientConfig)
 78	if err != nil {
 79		return nil, fmt.Errorf("failed to create powernap client: %w", err)
 80	}
 81
 82	client := &Client{
 83		client:      powernapClient,
 84		name:        name,
 85		fileTypes:   config.FileTypes,
 86		diagnostics: csync.NewVersionedMap[protocol.DocumentURI, []protocol.Diagnostic](),
 87		openFiles:   csync.NewMap[string, *OpenFileInfo](),
 88		config:      config,
 89	}
 90
 91	// Initialize server state
 92	client.serverState.Store(StateStarting)
 93
 94	return client, nil
 95}
 96
 97// Initialize initializes the LSP client and returns the server capabilities.
 98func (c *Client) Initialize(ctx context.Context, workspaceDir string) (*protocol.InitializeResult, error) {
 99	if err := c.client.Initialize(ctx, false); err != nil {
100		return nil, fmt.Errorf("failed to initialize powernap client: %w", err)
101	}
102
103	// Convert powernap capabilities to protocol capabilities
104	caps := c.client.GetCapabilities()
105	protocolCaps := protocol.ServerCapabilities{
106		TextDocumentSync: caps.TextDocumentSync,
107		CompletionProvider: func() *protocol.CompletionOptions {
108			if caps.CompletionProvider != nil {
109				return &protocol.CompletionOptions{
110					TriggerCharacters:   caps.CompletionProvider.TriggerCharacters,
111					AllCommitCharacters: caps.CompletionProvider.AllCommitCharacters,
112					ResolveProvider:     caps.CompletionProvider.ResolveProvider,
113				}
114			}
115			return nil
116		}(),
117	}
118
119	result := &protocol.InitializeResult{
120		Capabilities: protocolCaps,
121	}
122
123	c.RegisterServerRequestHandler("workspace/applyEdit", HandleApplyEdit)
124	c.RegisterServerRequestHandler("workspace/configuration", HandleWorkspaceConfiguration)
125	c.RegisterServerRequestHandler("client/registerCapability", HandleRegisterCapability)
126	c.RegisterNotificationHandler("window/showMessage", HandleServerMessage)
127	c.RegisterNotificationHandler("textDocument/publishDiagnostics", func(_ context.Context, _ string, params json.RawMessage) {
128		HandleDiagnostics(c, params)
129	})
130
131	return result, nil
132}
133
134// Close closes the LSP client.
135func (c *Client) Close(ctx context.Context) error {
136	// Try to close all open files first
137	ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
138	defer cancel()
139
140	c.CloseAllFiles(ctx)
141
142	// Shutdown and exit the client
143	if err := c.client.Shutdown(ctx); err != nil {
144		slog.Warn("Failed to shutdown LSP client", "error", err)
145	}
146
147	return c.client.Exit()
148}
149
150// ServerState represents the state of an LSP server
151type ServerState int
152
153const (
154	StateStarting ServerState = iota
155	StateReady
156	StateError
157	StateDisabled
158)
159
160func (s ServerState) MarshalText() ([]byte, error) {
161	switch s {
162	case StateStarting:
163		return []byte("starting"), nil
164	case StateReady:
165		return []byte("ready"), nil
166	case StateError:
167		return []byte("error"), nil
168	case StateDisabled:
169		return []byte("disabled"), nil
170	default:
171		return nil, fmt.Errorf("unknown server state: %d", s)
172	}
173}
174
175func (s *ServerState) UnmarshalText(data []byte) error {
176	switch strings.ToLower(string(data)) {
177	case "starting":
178		*s = StateStarting
179	case "ready":
180		*s = StateReady
181	case "error":
182		*s = StateError
183	case "disabled":
184		*s = StateDisabled
185	default:
186		return fmt.Errorf("unknown server state: %s", data)
187	}
188	return nil
189}
190
191// GetServerState returns the current state of the LSP server
192func (c *Client) GetServerState() ServerState {
193	if val := c.serverState.Load(); val != nil {
194		return val.(ServerState)
195	}
196	return StateStarting
197}
198
199// SetServerState sets the current state of the LSP server
200func (c *Client) SetServerState(state ServerState) {
201	c.serverState.Store(state)
202}
203
204// GetName returns the name of the LSP client
205func (c *Client) GetName() string {
206	return c.name
207}
208
209// SetDiagnosticsCallback sets the callback function for diagnostic changes
210func (c *Client) SetDiagnosticsCallback(callback func(name string, count int)) {
211	c.onDiagnosticsChanged = callback
212}
213
214// WaitForServerReady waits for the server to be ready
215func (c *Client) WaitForServerReady(ctx context.Context) error {
216	cfg := config.Get()
217
218	// Set initial state
219	c.SetServerState(StateStarting)
220
221	// Create a context with timeout
222	ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
223	defer cancel()
224
225	// Try to ping the server with a simple request
226	ticker := time.NewTicker(500 * time.Millisecond)
227	defer ticker.Stop()
228
229	if cfg != nil && cfg.Options.DebugLSP {
230		slog.Debug("Waiting for LSP server to be ready...")
231	}
232
233	c.openKeyConfigFiles(ctx)
234
235	for {
236		select {
237		case <-ctx.Done():
238			c.SetServerState(StateError)
239			return fmt.Errorf("timeout waiting for LSP server to be ready")
240		case <-ticker.C:
241			// Check if client is running
242			if !c.client.IsRunning() {
243				if cfg != nil && cfg.Options.DebugLSP {
244					slog.Debug("LSP server not ready yet", "server", c.name)
245				}
246				continue
247			}
248
249			// Server is ready
250			c.SetServerState(StateReady)
251			if cfg != nil && cfg.Options.DebugLSP {
252				slog.Debug("LSP server is ready")
253			}
254			return nil
255		}
256	}
257}
258
259// OpenFileInfo contains information about an open file
260type OpenFileInfo struct {
261	Version int32
262	URI     protocol.DocumentURI
263}
264
265// HandlesFile checks if this LSP client handles the given file based on its extension.
266func (c *Client) HandlesFile(path string) bool {
267	// If no file types are specified, handle all files (backward compatibility)
268	if len(c.fileTypes) == 0 {
269		return true
270	}
271
272	name := strings.ToLower(filepath.Base(path))
273	for _, filetype := range c.fileTypes {
274		suffix := strings.ToLower(filetype)
275		if !strings.HasPrefix(suffix, ".") {
276			suffix = "." + suffix
277		}
278		if strings.HasSuffix(name, suffix) {
279			slog.Debug("handles file", "name", c.name, "file", name, "filetype", filetype)
280			return true
281		}
282	}
283	slog.Debug("doesn't handle file", "name", c.name, "file", name)
284	return false
285}
286
287// OpenFile opens a file in the LSP server.
288func (c *Client) OpenFile(ctx context.Context, filepath string) error {
289	if !c.HandlesFile(filepath) {
290		return nil
291	}
292
293	uri := string(protocol.URIFromPath(filepath))
294
295	if _, exists := c.openFiles.Get(uri); exists {
296		return nil // Already open
297	}
298
299	// Skip files that do not exist or cannot be read
300	content, err := os.ReadFile(filepath)
301	if err != nil {
302		return fmt.Errorf("error reading file: %w", err)
303	}
304
305	// Notify the server about the opened document
306	if err = c.client.NotifyDidOpenTextDocument(ctx, uri, string(DetectLanguageID(uri)), 1, string(content)); err != nil {
307		return err
308	}
309
310	c.openFiles.Set(uri, &OpenFileInfo{
311		Version: 1,
312		URI:     protocol.DocumentURI(uri),
313	})
314
315	return nil
316}
317
318// NotifyChange notifies the server about a file change.
319func (c *Client) NotifyChange(ctx context.Context, filepath string) error {
320	uri := string(protocol.URIFromPath(filepath))
321
322	content, err := os.ReadFile(filepath)
323	if err != nil {
324		return fmt.Errorf("error reading file: %w", err)
325	}
326
327	fileInfo, isOpen := c.openFiles.Get(uri)
328	if !isOpen {
329		return fmt.Errorf("cannot notify change for unopened file: %s", filepath)
330	}
331
332	// Increment version
333	fileInfo.Version++
334
335	// Create change event
336	changes := []protocol.TextDocumentContentChangeEvent{
337		{
338			Value: protocol.TextDocumentContentChangeWholeDocument{
339				Text: string(content),
340			},
341		},
342	}
343
344	return c.client.NotifyDidChangeTextDocument(ctx, uri, int(fileInfo.Version), changes)
345}
346
347// CloseFile closes a file in the LSP server.
348//
349// NOTE: this is only ever called on LSP shutdown.
350func (c *Client) CloseFile(ctx context.Context, filepath string) error {
351	cfg := config.Get()
352	uri := string(protocol.URIFromPath(filepath))
353
354	if _, exists := c.openFiles.Get(uri); !exists {
355		return nil // Already closed
356	}
357
358	if cfg.Options.DebugLSP {
359		slog.Debug("Closing file", "file", filepath)
360	}
361
362	if err := c.client.NotifyDidCloseTextDocument(ctx, uri); err != nil {
363		return err
364	}
365
366	c.openFiles.Del(uri)
367
368	return nil
369}
370
371// IsFileOpen checks if a file is currently open.
372func (c *Client) IsFileOpen(filepath string) bool {
373	uri := string(protocol.URIFromPath(filepath))
374	_, exists := c.openFiles.Get(uri)
375	return exists
376}
377
378// CloseAllFiles closes all currently open files.
379func (c *Client) CloseAllFiles(ctx context.Context) {
380	cfg := config.Get()
381	filesToClose := make([]string, 0, c.openFiles.Len())
382
383	// First collect all URIs that need to be closed
384	for uri := range c.openFiles.Seq2() {
385		// Convert URI back to file path using proper URI handling
386		filePath, err := protocol.DocumentURI(uri).Path()
387		if err != nil {
388			slog.Error("Failed to convert URI to path for file closing", "uri", uri, "error", err)
389			continue
390		}
391		filesToClose = append(filesToClose, filePath)
392	}
393
394	// Then close them all
395	for _, filePath := range filesToClose {
396		err := c.CloseFile(ctx, filePath)
397		if err != nil && cfg != nil && cfg.Options.DebugLSP {
398			slog.Warn("Error closing file", "file", filePath, "error", err)
399		}
400	}
401
402	if cfg != nil && cfg.Options.DebugLSP {
403		slog.Debug("Closed all files", "files", filesToClose)
404	}
405}
406
407// GetFileDiagnostics returns diagnostics for a specific file.
408func (c *Client) GetFileDiagnostics(uri protocol.DocumentURI) []protocol.Diagnostic {
409	diags, _ := c.diagnostics.Get(uri)
410	return diags
411}
412
413// GetDiagnostics returns all diagnostics for all files.
414func (c *Client) GetDiagnostics() map[protocol.DocumentURI][]protocol.Diagnostic {
415	return maps.Collect(c.diagnostics.Seq2())
416}
417
418// OpenFileOnDemand opens a file only if it's not already open.
419func (c *Client) OpenFileOnDemand(ctx context.Context, filepath string) error {
420	// Check if the file is already open
421	if c.IsFileOpen(filepath) {
422		return nil
423	}
424
425	// Open the file
426	return c.OpenFile(ctx, filepath)
427}
428
429// GetDiagnosticsForFile ensures a file is open and returns its diagnostics.
430func (c *Client) GetDiagnosticsForFile(ctx context.Context, filepath string) ([]protocol.Diagnostic, error) {
431	documentURI := protocol.URIFromPath(filepath)
432
433	// Make sure the file is open
434	if !c.IsFileOpen(filepath) {
435		if err := c.OpenFile(ctx, filepath); err != nil {
436			return nil, fmt.Errorf("failed to open file for diagnostics: %w", err)
437		}
438
439		// Give the LSP server a moment to process the file
440		time.Sleep(100 * time.Millisecond)
441	}
442
443	// Get diagnostics
444	diagnostics, _ := c.diagnostics.Get(documentURI)
445
446	return diagnostics, nil
447}
448
449// ClearDiagnosticsForURI removes diagnostics for a specific URI from the cache.
450func (c *Client) ClearDiagnosticsForURI(uri protocol.DocumentURI) {
451	c.diagnostics.Del(uri)
452}
453
454// RegisterNotificationHandler registers a notification handler.
455func (c *Client) RegisterNotificationHandler(method string, handler transport.NotificationHandler) {
456	c.client.RegisterNotificationHandler(method, handler)
457}
458
459// RegisterServerRequestHandler handles server requests.
460func (c *Client) RegisterServerRequestHandler(method string, handler transport.Handler) {
461	c.client.RegisterHandler(method, handler)
462}
463
464// DidChangeWatchedFiles sends a workspace/didChangeWatchedFiles notification to the server.
465func (c *Client) DidChangeWatchedFiles(ctx context.Context, params protocol.DidChangeWatchedFilesParams) error {
466	return c.client.NotifyDidChangeWatchedFiles(ctx, params.Changes)
467}
468
469// openKeyConfigFiles opens important configuration files that help initialize the server.
470func (c *Client) openKeyConfigFiles(ctx context.Context) {
471	wd, err := os.Getwd()
472	if err != nil {
473		return
474	}
475
476	// Try to open each file, ignoring errors if they don't exist
477	for _, file := range c.config.RootMarkers {
478		file = filepath.Join(wd, file)
479		if _, err := os.Stat(file); err == nil {
480			// File exists, try to open it
481			if err := c.OpenFile(ctx, file); err != nil {
482				slog.Debug("Failed to open key config file", "file", file, "error", err)
483			} else {
484				slog.Debug("Opened key config file for initialization", "file", file)
485			}
486		}
487	}
488}
489
490// WaitForDiagnostics waits until diagnostics change or the timeout is reached.
491func (c *Client) WaitForDiagnostics(ctx context.Context, d time.Duration) {
492	ticker := time.NewTicker(200 * time.Millisecond)
493	defer ticker.Stop()
494	timeout := time.After(d)
495	pv := c.diagnostics.Version()
496	for {
497		select {
498		case <-ctx.Done():
499			return
500		case <-timeout:
501			return
502		case <-ticker.C:
503			if pv != c.diagnostics.Version() {
504				return
505			}
506		}
507	}
508}
509
510// HasRootMarkers checks if any of the specified root marker patterns exist in the given directory.
511// Uses glob patterns to match files, allowing for more flexible matching.
512func HasRootMarkers(dir string, rootMarkers []string) bool {
513	if len(rootMarkers) == 0 {
514		return true
515	}
516	for _, pattern := range rootMarkers {
517		// Use fsext.GlobWithDoubleStar to find matches
518		matches, _, err := fsext.GlobWithDoubleStar(pattern, dir, 1)
519		if err == nil && len(matches) > 0 {
520			return true
521		}
522	}
523	return false
524}