File tree 2 files changed +49
-3
lines changed
2 files changed +49
-3
lines changed Original file line number Diff line number Diff line change @@ -12,6 +12,7 @@ import (
12
12
"reflect"
13
13
"strconv"
14
14
"strings"
15
+ "syscall"
15
16
"time"
16
17
"unicode"
17
18
@@ -225,9 +226,25 @@ func isTTY(w io.Writer) bool {
225
226
if w == forceColorWriter {
226
227
return true
227
228
}
228
- f , ok := w .(interface {
229
- Fd () uintptr
230
- })
229
+ // SyscallConn is safe during file close.
230
+ if sc , ok := w .(interface {
231
+ SyscallConn () (syscall.RawConn , error )
232
+ }); ok {
233
+ conn , err := sc .SyscallConn ()
234
+ if err != nil {
235
+ return false
236
+ }
237
+ var isTerm bool
238
+ err = conn .Control (func (fd uintptr ) {
239
+ isTerm = terminal .IsTerminal (int (fd ))
240
+ })
241
+ if err != nil {
242
+ return false
243
+ }
244
+ return isTerm
245
+ }
246
+ // Fallback to unsafe Fd.
247
+ f , ok := w .(interface { Fd () uintptr })
231
248
return ok && terminal .IsTerminal (int (f .Fd ()))
232
249
}
233
250
Original file line number Diff line number Diff line change 6
6
"flag"
7
7
"fmt"
8
8
"io"
9
+ "io/ioutil"
9
10
"os"
10
11
"testing"
11
12
"time"
@@ -178,6 +179,34 @@ func TestEntry(t *testing.T) {
178
179
assert .Equal (t , "entry matches" , string (wantByt ), gotBuf .String ())
179
180
})
180
181
}
182
+
183
+ t .Run ("isTTY during file close" , func (t * testing.T ) {
184
+ t .Parallel ()
185
+
186
+ tmpdir := t .TempDir ()
187
+ f , err := ioutil .TempFile (tmpdir , "slog" )
188
+ if err != nil {
189
+ t .Fatal (err )
190
+ }
191
+ defer f .Close ()
192
+
193
+ done := make (chan struct {}, 2 )
194
+ go func () {
195
+ entryhuman .Fmt (new (bytes.Buffer ), f , slog.SinkEntry {
196
+ Level : slog .LevelCritical ,
197
+ Fields : slog .M (
198
+ slog .F ("hey" , "hi" ),
199
+ ),
200
+ })
201
+ done <- struct {}{}
202
+ }()
203
+ go func () {
204
+ _ = f .Close ()
205
+ done <- struct {}{}
206
+ }()
207
+ <- done
208
+ <- done
209
+ })
181
210
}
182
211
183
212
func BenchmarkFmt (b * testing.B ) {
You can’t perform that action at this time.
0 commit comments