...

Source file src/edge-infra.dev/pkg/f8n/devinfra/repo/owners/policybot/policy/common/regexp.go

Documentation: edge-infra.dev/pkg/f8n/devinfra/repo/owners/policybot/policy/common

     1  // Copyright 2020 Palantir Technologies, Inc.
     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 common
    16  
    17  import (
    18  	"encoding/json"
    19  	"regexp"
    20  )
    21  
    22  // Regexp is a regexp.Regexp that only supports matching and can be
    23  // deserialized from a string.
    24  type Regexp struct {
    25  	r *regexp.Regexp
    26  }
    27  
    28  func NewRegexp(pattern string) (Regexp, error) {
    29  	r, err := regexp.Compile(pattern)
    30  	if err != nil {
    31  		return Regexp{}, err
    32  	}
    33  	return Regexp{r: r}, nil
    34  }
    35  
    36  func NewCompiledRegexp(r *regexp.Regexp) Regexp {
    37  	return Regexp{r: r}
    38  }
    39  
    40  func (r Regexp) Matches(s string) bool {
    41  	if r.r == nil {
    42  		return false
    43  	}
    44  	return r.r.MatchString(s)
    45  }
    46  
    47  func (r Regexp) String() string {
    48  	if r.r == nil {
    49  		return ""
    50  	}
    51  	return r.r.String()
    52  }
    53  
    54  func (r *Regexp) UnmarshalYAML(unmarshal func(interface{}) error) (err error) {
    55  	var pattern string
    56  	if err := unmarshal(&pattern); err != nil {
    57  		return err
    58  	}
    59  	*r, err = NewRegexp(pattern)
    60  	return err
    61  }
    62  
    63  func (r *Regexp) UnmarshalJSON(data []byte) (err error) {
    64  	var pattern string
    65  	if err := json.Unmarshal(data, &pattern); err != nil {
    66  		return err
    67  	}
    68  	*r, err = NewRegexp(pattern)
    69  	return err
    70  }
    71  
    72  func (r Regexp) MarshalYAML() (interface{}, error) {
    73  	return r.String(), nil
    74  }
    75  

View as plain text