| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
package protocol |
| 6 |
|
| 7 |
import ( |
| 8 |
"bytes" |
| 9 |
"context" |
| 10 |
"sync" |
| 11 |
|
| 12 |
"golang.org/x/tools/internal/event" |
| 13 |
"golang.org/x/tools/internal/event/core" |
| 14 |
"golang.org/x/tools/internal/event/export" |
| 15 |
"golang.org/x/tools/internal/event/label" |
| 16 |
) |
| 17 |
|
| 18 |
type contextKey int |
| 19 |
|
| 20 |
const ( |
| 21 |
clientKey = contextKey(iota) |
| 22 |
) |
| 23 |
|
| 24 |
func WithClient(ctx context.Context, client Client) context.Context { |
| 25 |
return context.WithValue(ctx, clientKey, client) |
| 26 |
} |
| 27 |
|
| 28 |
func LogEvent(ctx context.Context, ev core.Event, lm label.Map, mt MessageType) context.Context { |
| 29 |
client, ok := ctx.Value(clientKey).(Client) |
| 30 |
if !ok { |
| 31 |
return ctx |
| 32 |
} |
| 33 |
buf := &bytes.Buffer{} |
| 34 |
p := export.Printer{} |
| 35 |
p.WriteEvent(buf, ev, lm) |
| 36 |
msg := &LogMessageParams{Type: mt, Message: buf.String()} |
| 37 |
|
| 38 |
if event.IsError(ev) { |
| 39 |
msg.Type = Error |
| 40 |
} |
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
startLogSenderOnce.Do(func() { |
| 45 |
go func() { |
| 46 |
for f := range logQueue { |
| 47 |
f() |
| 48 |
} |
| 49 |
}() |
| 50 |
}) |
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
ctx2 := context.WithoutCancel(ctx) |
| 56 |
logQueue <- func() { client.LogMessage(ctx2, msg) } |
| 57 |
|
| 58 |
return ctx |
| 59 |
} |
| 60 |
|
| 61 |
var ( |
| 62 |
startLogSenderOnce sync.Once |
| 63 |
logQueue = make(chan func(), 100) |
| 64 |
) |