fix logs and add cancellation

This commit is contained in:
Kujtim Hoxha
2025-04-10 13:29:44 +02:00
parent 0b007b9c77
commit 36f201d5d3
23 changed files with 343 additions and 283 deletions

View File

@@ -18,8 +18,6 @@ import (
"github.com/kujtimiihoxha/termai/internal/lsp/protocol"
)
var logger = logging.Get()
type Client struct {
Cmd *exec.Cmd
stdin io.WriteCloser
@@ -377,7 +375,7 @@ func (c *Client) CloseFile(ctx context.Context, filepath string) error {
}
if cnf.Debug {
logger.Debug("Closing file", "file", filepath)
logging.Debug("Closing file", "file", filepath)
}
if err := c.Notify(ctx, "textDocument/didClose", params); err != nil {
return err
@@ -416,12 +414,12 @@ func (c *Client) CloseAllFiles(ctx context.Context) {
for _, filePath := range filesToClose {
err := c.CloseFile(ctx, filePath)
if err != nil && cnf.Debug {
logger.Warn("Error closing file", "file", filePath, "error", err)
logging.Warn("Error closing file", "file", filePath, "error", err)
}
}
if cnf.Debug {
logger.Debug("Closed all files", "files", filesToClose)
logging.Debug("Closed all files", "files", filesToClose)
}
}

View File

@@ -4,6 +4,7 @@ import (
"encoding/json"
"github.com/kujtimiihoxha/termai/internal/config"
"github.com/kujtimiihoxha/termai/internal/logging"
"github.com/kujtimiihoxha/termai/internal/lsp/protocol"
"github.com/kujtimiihoxha/termai/internal/lsp/util"
)
@@ -17,7 +18,7 @@ func HandleWorkspaceConfiguration(params json.RawMessage) (any, error) {
func HandleRegisterCapability(params json.RawMessage) (any, error) {
var registerParams protocol.RegistrationParams
if err := json.Unmarshal(params, &registerParams); err != nil {
logger.Error("Error unmarshaling registration params", "error", err)
logging.Error("Error unmarshaling registration params", "error", err)
return nil, err
}
@@ -27,13 +28,13 @@ func HandleRegisterCapability(params json.RawMessage) (any, error) {
// Parse the registration options
optionsJSON, err := json.Marshal(reg.RegisterOptions)
if err != nil {
logger.Error("Error marshaling registration options", "error", err)
logging.Error("Error marshaling registration options", "error", err)
continue
}
var options protocol.DidChangeWatchedFilesRegistrationOptions
if err := json.Unmarshal(optionsJSON, &options); err != nil {
logger.Error("Error unmarshaling registration options", "error", err)
logging.Error("Error unmarshaling registration options", "error", err)
continue
}
@@ -53,7 +54,7 @@ func HandleApplyEdit(params json.RawMessage) (any, error) {
err := util.ApplyWorkspaceEdit(edit.Edit)
if err != nil {
logger.Error("Error applying workspace edit", "error", err)
logging.Error("Error applying workspace edit", "error", err)
return protocol.ApplyWorkspaceEditResult{Applied: false, FailureReason: err.Error()}, nil
}
@@ -88,7 +89,7 @@ func HandleServerMessage(params json.RawMessage) {
}
if err := json.Unmarshal(params, &msg); err == nil {
if cnf.Debug {
logger.Debug("Server message", "type", msg.Type, "message", msg.Message)
logging.Debug("Server message", "type", msg.Type, "message", msg.Message)
}
}
}
@@ -96,7 +97,7 @@ func HandleServerMessage(params json.RawMessage) {
func HandleDiagnostics(client *Client, params json.RawMessage) {
var diagParams protocol.PublishDiagnosticsParams
if err := json.Unmarshal(params, &diagParams); err != nil {
logger.Error("Error unmarshaling diagnostics params", "error", err)
logging.Error("Error unmarshaling diagnostics params", "error", err)
return
}

View File

@@ -9,6 +9,7 @@ import (
"strings"
"github.com/kujtimiihoxha/termai/internal/config"
"github.com/kujtimiihoxha/termai/internal/logging"
)
// Write writes an LSP message to the given writer
@@ -20,7 +21,7 @@ func WriteMessage(w io.Writer, msg *Message) error {
cnf := config.Get()
if cnf.Debug {
logger.Debug("Sending message to server", "method", msg.Method, "id", msg.ID)
logging.Debug("Sending message to server", "method", msg.Method, "id", msg.ID)
}
_, err = fmt.Fprintf(w, "Content-Length: %d\r\n\r\n", len(data))
@@ -49,7 +50,7 @@ func ReadMessage(r *bufio.Reader) (*Message, error) {
line = strings.TrimSpace(line)
if cnf.Debug {
logger.Debug("Received header", "line", line)
logging.Debug("Received header", "line", line)
}
if line == "" {
@@ -65,7 +66,7 @@ func ReadMessage(r *bufio.Reader) (*Message, error) {
}
if cnf.Debug {
logger.Debug("Content-Length", "length", contentLength)
logging.Debug("Content-Length", "length", contentLength)
}
// Read content
@@ -76,7 +77,7 @@ func ReadMessage(r *bufio.Reader) (*Message, error) {
}
if cnf.Debug {
logger.Debug("Received content", "content", string(content))
logging.Debug("Received content", "content", string(content))
}
// Parse message
@@ -95,7 +96,7 @@ func (c *Client) handleMessages() {
msg, err := ReadMessage(c.stdout)
if err != nil {
if cnf.Debug {
logger.Error("Error reading message", "error", err)
logging.Error("Error reading message", "error", err)
}
return
}
@@ -103,7 +104,7 @@ func (c *Client) handleMessages() {
// Handle server->client request (has both Method and ID)
if msg.Method != "" && msg.ID != 0 {
if cnf.Debug {
logger.Debug("Received request from server", "method", msg.Method, "id", msg.ID)
logging.Debug("Received request from server", "method", msg.Method, "id", msg.ID)
}
response := &Message{
@@ -143,7 +144,7 @@ func (c *Client) handleMessages() {
// Send response back to server
if err := WriteMessage(c.stdin, response); err != nil {
logger.Error("Error sending response to server", "error", err)
logging.Error("Error sending response to server", "error", err)
}
continue
@@ -157,11 +158,11 @@ func (c *Client) handleMessages() {
if ok {
if cnf.Debug {
logger.Debug("Handling notification", "method", msg.Method)
logging.Debug("Handling notification", "method", msg.Method)
}
go handler(msg.Params)
} else if cnf.Debug {
logger.Debug("No handler for notification", "method", msg.Method)
logging.Debug("No handler for notification", "method", msg.Method)
}
continue
}
@@ -174,12 +175,12 @@ func (c *Client) handleMessages() {
if ok {
if cnf.Debug {
logger.Debug("Received response for request", "id", msg.ID)
logging.Debug("Received response for request", "id", msg.ID)
}
ch <- msg
close(ch)
} else if cnf.Debug {
logger.Debug("No handler for response", "id", msg.ID)
logging.Debug("No handler for response", "id", msg.ID)
}
}
}
@@ -191,7 +192,7 @@ func (c *Client) Call(ctx context.Context, method string, params any, result any
id := c.nextID.Add(1)
if cnf.Debug {
logger.Debug("Making call", "method", method, "id", id)
logging.Debug("Making call", "method", method, "id", id)
}
msg, err := NewRequest(id, method, params)
@@ -217,14 +218,14 @@ func (c *Client) Call(ctx context.Context, method string, params any, result any
}
if cnf.Debug {
logger.Debug("Request sent", "method", method, "id", id)
logging.Debug("Request sent", "method", method, "id", id)
}
// Wait for response
resp := <-ch
if cnf.Debug {
logger.Debug("Received response", "id", id)
logging.Debug("Received response", "id", id)
}
if resp.Error != nil {
@@ -250,7 +251,7 @@ func (c *Client) Call(ctx context.Context, method string, params any, result any
func (c *Client) Notify(ctx context.Context, method string, params any) error {
cnf := config.Get()
if cnf.Debug {
logger.Debug("Sending notification", "method", method)
logging.Debug("Sending notification", "method", method)
}
msg, err := NewNotification(method, params)

View File

@@ -16,8 +16,6 @@ import (
"github.com/kujtimiihoxha/termai/internal/lsp/protocol"
)
var logger = logging.Get()
// WorkspaceWatcher manages LSP file watching
type WorkspaceWatcher struct {
client *lsp.Client
@@ -53,7 +51,7 @@ func (w *WorkspaceWatcher) AddRegistrations(ctx context.Context, id string, watc
// Print detailed registration information for debugging
if cnf.Debug {
logger.Debug("Adding file watcher registrations",
logging.Debug("Adding file watcher registrations",
"id", id,
"watchers", len(watchers),
"total", len(w.registrations),
@@ -61,26 +59,26 @@ func (w *WorkspaceWatcher) AddRegistrations(ctx context.Context, id string, watc
)
for i, watcher := range watchers {
logger.Debug("Registration", "index", i+1)
logging.Debug("Registration", "index", i+1)
// Log the GlobPattern
switch v := watcher.GlobPattern.Value.(type) {
case string:
logger.Debug("GlobPattern", "pattern", v)
logging.Debug("GlobPattern", "pattern", v)
case protocol.RelativePattern:
logger.Debug("GlobPattern", "pattern", v.Pattern)
logging.Debug("GlobPattern", "pattern", v.Pattern)
// Log BaseURI details
switch u := v.BaseURI.Value.(type) {
case string:
logger.Debug("BaseURI", "baseURI", u)
logging.Debug("BaseURI", "baseURI", u)
case protocol.DocumentUri:
logger.Debug("BaseURI", "baseURI", u)
logging.Debug("BaseURI", "baseURI", u)
default:
logger.Debug("BaseURI", "baseURI", u)
logging.Debug("BaseURI", "baseURI", u)
}
default:
logger.Debug("GlobPattern", "unknown type", fmt.Sprintf("%T", v))
logging.Debug("GlobPattern", "unknown type", fmt.Sprintf("%T", v))
}
// Log WatchKind
@@ -89,7 +87,7 @@ func (w *WorkspaceWatcher) AddRegistrations(ctx context.Context, id string, watc
watchKind = *watcher.Kind
}
logger.Debug("WatchKind", "kind", watchKind)
logging.Debug("WatchKind", "kind", watchKind)
// Test match against some example paths
testPaths := []string{
@@ -99,7 +97,7 @@ func (w *WorkspaceWatcher) AddRegistrations(ctx context.Context, id string, watc
for _, testPath := range testPaths {
isMatch := w.matchesPattern(testPath, watcher.GlobPattern)
logger.Debug("Test path", "path", testPath, "matches", isMatch)
logging.Debug("Test path", "path", testPath, "matches", isMatch)
}
}
}
@@ -119,7 +117,7 @@ func (w *WorkspaceWatcher) AddRegistrations(ctx context.Context, id string, watc
if d.IsDir() {
if path != w.workspacePath && shouldExcludeDir(path) {
if cnf.Debug {
logger.Debug("Skipping excluded directory", "path", path)
logging.Debug("Skipping excluded directory", "path", path)
}
return filepath.SkipDir
}
@@ -139,7 +137,7 @@ func (w *WorkspaceWatcher) AddRegistrations(ctx context.Context, id string, watc
elapsedTime := time.Since(startTime)
if cnf.Debug {
logger.Debug("Workspace scan complete",
logging.Debug("Workspace scan complete",
"filesOpened", filesOpened,
"elapsedTime", elapsedTime.Seconds(),
"workspacePath", w.workspacePath,
@@ -147,7 +145,7 @@ func (w *WorkspaceWatcher) AddRegistrations(ctx context.Context, id string, watc
}
if err != nil && cnf.Debug {
logger.Debug("Error scanning workspace for files to open", "error", err)
logging.Debug("Error scanning workspace for files to open", "error", err)
}
}()
}
@@ -164,7 +162,7 @@ func (w *WorkspaceWatcher) WatchWorkspace(ctx context.Context, workspacePath str
watcher, err := fsnotify.NewWatcher()
if err != nil {
logger.Error("Error creating watcher", "error", err)
logging.Error("Error creating watcher", "error", err)
}
defer watcher.Close()
@@ -178,7 +176,7 @@ func (w *WorkspaceWatcher) WatchWorkspace(ctx context.Context, workspacePath str
if d.IsDir() && path != workspacePath {
if shouldExcludeDir(path) {
if cnf.Debug {
logger.Debug("Skipping excluded directory", "path", path)
logging.Debug("Skipping excluded directory", "path", path)
}
return filepath.SkipDir
}
@@ -188,14 +186,14 @@ func (w *WorkspaceWatcher) WatchWorkspace(ctx context.Context, workspacePath str
if d.IsDir() {
err = watcher.Add(path)
if err != nil {
logger.Error("Error watching path", "path", path, "error", err)
logging.Error("Error watching path", "path", path, "error", err)
}
}
return nil
})
if err != nil {
logger.Error("Error walking workspace", "error", err)
logging.Error("Error walking workspace", "error", err)
}
// Event loop
@@ -217,7 +215,7 @@ func (w *WorkspaceWatcher) WatchWorkspace(ctx context.Context, workspacePath str
// Skip excluded directories
if !shouldExcludeDir(event.Name) {
if err := watcher.Add(event.Name); err != nil {
logger.Error("Error adding directory to watcher", "path", event.Name, "error", err)
logging.Error("Error adding directory to watcher", "path", event.Name, "error", err)
}
}
} else {
@@ -232,7 +230,7 @@ func (w *WorkspaceWatcher) WatchWorkspace(ctx context.Context, workspacePath str
// Debug logging
if cnf.Debug {
matched, kind := w.isPathWatched(event.Name)
logger.Debug("File event",
logging.Debug("File event",
"path", event.Name,
"operation", event.Op.String(),
"watched", matched,
@@ -277,7 +275,7 @@ func (w *WorkspaceWatcher) WatchWorkspace(ctx context.Context, workspacePath str
if !ok {
return
}
logger.Error("Error watching file", "error", err)
logging.Error("Error watching file", "error", err)
}
}
}
@@ -402,7 +400,7 @@ func matchesSimpleGlob(pattern, path string) bool {
// Fall back to simple matching for simpler patterns
matched, err := filepath.Match(pattern, path)
if err != nil {
logger.Error("Error matching pattern", "pattern", pattern, "path", path, "error", err)
logging.Error("Error matching pattern", "pattern", pattern, "path", path, "error", err)
return false
}
@@ -413,7 +411,7 @@ func matchesSimpleGlob(pattern, path string) bool {
func (w *WorkspaceWatcher) matchesPattern(path string, pattern protocol.GlobPattern) bool {
patternInfo, err := pattern.AsPattern()
if err != nil {
logger.Error("Error parsing pattern", "pattern", pattern, "error", err)
logging.Error("Error parsing pattern", "pattern", pattern, "error", err)
return false
}
@@ -438,7 +436,7 @@ func (w *WorkspaceWatcher) matchesPattern(path string, pattern protocol.GlobPatt
// Make path relative to basePath for matching
relPath, err := filepath.Rel(basePath, path)
if err != nil {
logger.Error("Error getting relative path", "path", path, "basePath", basePath, "error", err)
logging.Error("Error getting relative path", "path", path, "basePath", basePath, "error", err)
return false
}
relPath = filepath.ToSlash(relPath)
@@ -479,14 +477,14 @@ func (w *WorkspaceWatcher) handleFileEvent(ctx context.Context, uri string, chan
if changeType == protocol.FileChangeType(protocol.Changed) && w.client.IsFileOpen(filePath) {
err := w.client.NotifyChange(ctx, filePath)
if err != nil {
logger.Error("Error notifying change", "error", err)
logging.Error("Error notifying change", "error", err)
}
return
}
// Notify LSP server about the file event using didChangeWatchedFiles
if err := w.notifyFileEvent(ctx, uri, changeType); err != nil {
logger.Error("Error notifying LSP server about file event", "error", err)
logging.Error("Error notifying LSP server about file event", "error", err)
}
}
@@ -494,7 +492,7 @@ func (w *WorkspaceWatcher) handleFileEvent(ctx context.Context, uri string, chan
func (w *WorkspaceWatcher) notifyFileEvent(ctx context.Context, uri string, changeType protocol.FileChangeType) error {
cnf := config.Get()
if cnf.Debug {
logger.Debug("Notifying file event",
logging.Debug("Notifying file event",
"uri", uri,
"changeType", changeType,
)
@@ -618,7 +616,7 @@ func shouldExcludeFile(filePath string) bool {
// Skip large files
if info.Size() > maxFileSize {
if cnf.Debug {
logger.Debug("Skipping large file",
logging.Debug("Skipping large file",
"path", filePath,
"size", info.Size(),
"maxSize", maxFileSize,
@@ -651,7 +649,7 @@ func (w *WorkspaceWatcher) openMatchingFile(ctx context.Context, path string) {
if watched, _ := w.isPathWatched(path); watched {
// Don't need to check if it's already open - the client.OpenFile handles that
if err := w.client.OpenFile(ctx, path); err != nil && cnf.Debug {
logger.Error("Error opening file", "path", path, "error", err)
logging.Error("Error opening file", "path", path, "error", err)
}
}
}