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