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