Skip to content

Revert "Revert "fix: Use SyscallConn for isTTY which is safe during f… #187

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions internal/entryhuman/entry.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"reflect"
"strconv"
"strings"
"syscall"
"time"
"unicode"

Expand Down Expand Up @@ -224,9 +225,25 @@ func isTTY(w io.Writer) bool {
if w == forceColorWriter {
return true
}
f, ok := w.(interface {
Fd() uintptr
})
// SyscallConn is safe during file close.
if sc, ok := w.(interface {
SyscallConn() (syscall.RawConn, error)
}); ok {
conn, err := sc.SyscallConn()
if err != nil {
return false
}
var isTerm bool
err = conn.Control(func(fd uintptr) {
isTerm = term.IsTerminal(int(fd))
})
if err != nil {
return false
}
return isTerm
}
// Fallback to unsafe Fd.
f, ok := w.(interface{ Fd() uintptr })
return ok && term.IsTerminal(int(f.Fd()))
}

Expand Down
28 changes: 28 additions & 0 deletions internal/entryhuman/entry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,34 @@ func TestEntry(t *testing.T) {
assert.Equal(t, "entry matches", string(wantByt), gotBuf.String())
})
}

t.Run("isTTY during file close", func(t *testing.T) {
t.Parallel()

tmpdir := t.TempDir()
f, err := os.CreateTemp(tmpdir, "slog")
if err != nil {
t.Fatal(err)
}
defer f.Close()

done := make(chan struct{}, 2)
go func() {
entryhuman.Fmt(new(bytes.Buffer), f, slog.SinkEntry{
Level: slog.LevelCritical,
Fields: slog.M(
slog.F("hey", "hi"),
),
})
done <- struct{}{}
}()
go func() {
_ = f.Close()
done <- struct{}{}
}()
<-done
<-done
})
}

func BenchmarkFmt(b *testing.B) {
Expand Down