github.com/drone/runner-go@v1.12.0/livelog/extractor/writer.go (about) 1 package extractor 2 3 import ( 4 "bytes" 5 "encoding/base64" 6 "encoding/json" 7 "io" 8 "os" 9 "regexp" 10 ) 11 12 var ( 13 prefix = []byte("\u001B]1338;") 14 suffix = []byte("\u001B]0m") 15 re = regexp.MustCompilePOSIX("\u001B]1338;((.*?)\u001B]0m)") 16 disableCards = os.Getenv("DRONE_FLAG_ENABLE_CARDS") == "false" 17 ) 18 19 type Writer struct { 20 base io.Writer 21 file []byte 22 chunked bool 23 } 24 25 func New(w io.Writer) *Writer { 26 return &Writer{w, nil, false} 27 } 28 29 func (e *Writer) Write(p []byte) (n int, err error) { 30 if disableCards { 31 return e.base.Write(p) 32 } 33 if bytes.HasPrefix(p, prefix) == false && e.chunked == false { 34 return e.base.Write(p) 35 } 36 n = len(p) 37 38 // if the data does not include the ansi suffix, 39 // it exceeds the size of the buffer and is chunked. 40 e.chunked = !bytes.Contains(p, suffix) 41 42 // trim the ansi prefix and suffix from the data, 43 // and also trim any spacing or newlines that could 44 // cause confusion. 45 p = bytes.TrimSpace(p) 46 p = bytes.TrimPrefix(p, prefix) 47 p = bytes.TrimSuffix(p, suffix) 48 49 e.file = append(e.file, p...) 50 return n, nil 51 } 52 53 func (e *Writer) File() ([]byte, bool) { 54 if len(e.file) == 0 { 55 return nil, false 56 } 57 data, err := base64.StdEncoding.DecodeString(string(e.file)) 58 if err != nil { 59 return nil, false 60 } 61 if isJSON(data) { 62 return data, true 63 } 64 return nil, false 65 } 66 67 func isJSON(data []byte) bool { 68 var js json.RawMessage 69 return json.Unmarshal(data, &js) == nil 70 }