From 663baf92df7babdf3d1a587594d6301cc5c139ad Mon Sep 17 00:00:00 2001 From: JP Appel Date: Tue, 8 Oct 2024 11:08:00 -0400 Subject: Add middleware to strip ansi escape sequences --- api/docker.go | 40 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 38 insertions(+), 2 deletions(-) (limited to 'api/docker.go') diff --git a/api/docker.go b/api/docker.go index 248880e..0968a11 100644 --- a/api/docker.go +++ b/api/docker.go @@ -1,10 +1,12 @@ package api import ( + "bufio" "context" "fmt" "io" "log/slog" + "regexp" "time" "github.com/docker/docker/api/types/container" @@ -13,6 +15,41 @@ import ( const vttContainerId string = "foundry-foundry-1" +// Strip ansi control characters from source +// +// The source reader is automatically closed when stripped reader is +func StripAnsi(source io.ReadCloser) io.ReadCloser { + + regex := regexp.MustCompile(`\x1b[[0-9;]*m`) + reader, writer := io.Pipe() + + go func() { + bufReader := bufio.NewReader(source) + defer source.Close() + defer writer.Close() + + cleanSource: + for { + line, err := bufReader.ReadBytes('\n') + switch { + case err == io.EOF: + if len(line) > 0 { + cleaned := regex.ReplaceAll(line, []byte("")) + writer.Write(cleaned) + } + break cleanSource + case err != nil: + panic(err) + default: + cleaned := regex.ReplaceAll(line, []byte("")) + writer.Write(cleaned) + } + } + }() + + return reader +} + func stopVtt(ctx context.Context) error { apiClient, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation()) if err != nil { @@ -42,7 +79,6 @@ func vttLogs(ctx context.Context, lines uint) (io.ReadCloser, error) { opts := container.LogsOptions{ ShowStdout: true, ShowStderr: true, - Timestamps: true, } if lines != 0 { opts.Tail = fmt.Sprint(lines) @@ -55,7 +91,7 @@ func vttLogs(ctx context.Context, lines uint) (io.ReadCloser, error) { return nil, err } - return r, nil + return StripAnsi(r), nil } func vttStatus(ctx context.Context) ServerStatus { -- cgit v1.2.3