github.com/hpcng/singularity@v3.1.1+incompatible/pkg/util/copy/buffer.go (about) 1 // Copyright (c) 2018, Sylabs Inc. All rights reserved. 2 // This software is licensed under a 3-clause BSD license. Please consult the 3 // LICENSE.md file distributed with the sources of this project regarding your 4 // rights to use or distribute this software. 5 6 package copy 7 8 import ( 9 "bytes" 10 "sync" 11 ) 12 13 // TerminalBuffer captures the last line displayed on terminal. 14 type TerminalBuffer struct { 15 data []byte 16 mutex sync.Mutex 17 } 18 19 // NewTerminalBuffer returns an instantiated TerminalBuffer. 20 func NewTerminalBuffer() *TerminalBuffer { 21 b := &TerminalBuffer{} 22 b.data = make([]byte, 0) 23 return b 24 } 25 26 // Write implements the write interface to store last terminal line. 27 func (b *TerminalBuffer) Write(p []byte) (n int, err error) { 28 b.mutex.Lock() 29 defer b.mutex.Unlock() 30 31 if bytes.IndexByte(p, '\n') >= 0 { 32 b.data = nil 33 } else { 34 b.data = append(b.data, p...) 35 } 36 37 return len(p), nil 38 } 39 40 // Line returns the last terminal line. 41 func (b *TerminalBuffer) Line() []byte { 42 b.mutex.Lock() 43 defer b.mutex.Unlock() 44 // return a copy to avoid lock exposure 45 tmp := make([]byte, len(b.data)) 46 copy(tmp, b.data) 47 return tmp 48 }