go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/data/text/color/strip.go (about) 1 // Copyright 2019 The LUCI Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package color 16 17 import ( 18 "bytes" 19 "io" 20 ) 21 22 // StripWriter strips all color codes. 23 type StripWriter struct { 24 io.Writer 25 } 26 27 var colorStart = []byte("\033[") 28 29 func (w *StripWriter) Write(p []byte) (n int, err error) { 30 for len(p) > 0 { 31 var toWrite []byte 32 start := bytes.Index(p, colorStart) 33 if start != -1 { 34 relEnd := bytes.IndexRune(p[start:], 'm') 35 if relEnd != -1 { 36 toWrite = p[:start] 37 p = p[start+relEnd+1:] 38 } 39 } 40 if toWrite == nil { 41 toWrite = p 42 p = nil 43 } 44 45 var wrote int 46 wrote, err = w.Writer.Write(toWrite) 47 n += wrote 48 if err != nil { 49 break 50 } 51 } 52 return 53 }