-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathstrip.go
More file actions
74 lines (68 loc) · 1.66 KB
/
Copy pathstrip.go
File metadata and controls
74 lines (68 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package ansi
import (
"fmt"
"strings"
)
// An errorList is simply a list of errors.
type errorList []error
func (e errorList) Error() string {
if len(e) == 0 {
return ""
}
parts := make([]string, len(e))
for x, err := range e {
parts[x] = err.Error()
}
return strings.Join(parts, "\n")
}
func (e errorList) err() error {
switch len(e) {
case 0:
return nil
case 1:
return e[0]
default:
return e
}
}
// Strip returns in with all ANSI escape sequences stripped. An error is
// also returned if one or more of the stripped escape sequences are invalid.
//
// Strip uses the default (zero) Decoder, which treats bytes 0x80-0x9f as C1
// control introducers and is therefore not UTF-8 safe. To strip escape
// sequences from UTF-8 text without disturbing multibyte runes, use
// Decoder{UTF8: true}.Strip.
func Strip(in []byte) ([]byte, error) {
return Decoder{}.Strip(in)
}
// Strip returns in with all ANSI escape sequences stripped, decoding with the
// options in d. An error is also returned if one or more of the stripped
// escape sequences are invalid.
func (d Decoder) Strip(in []byte) ([]byte, error) {
var errs errorList
var out []string
var s *S
var err error
for len(in) > 0 {
in, s, err = d.Decode(in)
if s == nil {
if len(in) > 0 {
out = append(out, string(in))
}
break
}
if err != nil {
errs = append(errs, fmt.Errorf("%q: %v", s, err))
}
// If s.Type is "" then s represents plain text and not
// an escape sequence. We are only interested in plain
// text.
if s.Type == "" {
out = append(out, string(s.Code))
}
}
if len(out) > 0 {
return []byte(strings.Join(out, "")), errs.err()
}
return nil, errs.err()
}