golang.org/x/build@v0.0.0-20240506185731-218518f32b70/cmd/greplogs/flags.go (about) 1 // Copyright 2015 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package main 6 7 import ( 8 "fmt" 9 "regexp" 10 "sort" 11 "strings" 12 ) 13 14 type regexpList []*regexp.Regexp 15 16 func (x *regexpList) String() string { 17 s := "" 18 for i, r := range *x { 19 if i != 0 { 20 s += "," 21 } 22 s += r.String() 23 } 24 return s 25 } 26 27 func (x *regexpList) Set(s string) error { 28 re, err := regexp.Compile("(?m)" + s) 29 if err != nil { 30 // Get an error without our modifications. 31 _, err2 := regexp.Compile(s) 32 if err2 != nil { 33 err = err2 34 } 35 return err 36 } 37 *x = append(*x, re) 38 return nil 39 } 40 41 func (x *regexpList) AllMatch(data []byte) bool { 42 for _, r := range *x { 43 if !r.Match(data) { 44 return false 45 } 46 } 47 return true 48 } 49 50 func (x *regexpList) AnyMatchString(data string) bool { 51 for _, r := range *x { 52 if r.MatchString(data) { 53 return true 54 } 55 } 56 return false 57 } 58 59 func (x *regexpList) Matches(data []byte) [][]int { 60 matches := [][]int{} 61 for _, r := range *x { 62 matches = append(matches, r.FindAllSubmatchIndex(data, -1)...) 63 } 64 return matches 65 } 66 67 type regexpMap map[string]*regexp.Regexp 68 69 func (x *regexpMap) Set(s string) error { 70 if *x == nil { 71 *x = regexpMap{} 72 } 73 k, v, ok := strings.Cut(s, "=") 74 if !ok { 75 return fmt.Errorf("missing key, expected key=value in %q", s) 76 } 77 re, err := regexp.Compile("(?m)" + v) 78 if err != nil { 79 // Get an error without our modifications. 80 _, err2 := regexp.Compile(v) 81 if err2 != nil { 82 err = err2 83 } 84 return err 85 } 86 (*x)[k] = re 87 return nil 88 } 89 90 func (x *regexpMap) String() string { 91 var result []string 92 for k, v := range *x { 93 result = append(result, fmt.Sprintf("%v=%v", k, v)) 94 } 95 return strings.Join(result, ",") 96 } 97 98 func (x *regexpMap) Matches(data []byte) []string { 99 var matches []string 100 for k, r := range *x { 101 if r.Match(data) { 102 matches = append(matches, k) 103 } 104 } 105 sort.Strings(matches) 106 return matches 107 }