gitee.com/mirrors/goreporter@v0.0.0-20180902115603-df1b20f7c5d0/linters/spellcheck/misspell/notwords.go (about)

     1  package misspell
     2  
     3  import (
     4  	"bytes"
     5  	"regexp"
     6  	"strings"
     7  )
     8  
     9  var reEmail = regexp.MustCompile(`[a-zA-Z0-9_.%+-]+@[a-zA-Z0-9-.]+\.[a-zA-Z]{2,6}[^a-zA-Z]`)
    10  var reHost = regexp.MustCompile(`[a-zA-Z0-9-.]+\.[a-zA-Z]+`)
    11  
    12  // RemovePath attempts to strip away embedded file system paths, e.g.
    13  //  /foo/bar or /static/myimg.png
    14  //
    15  //  TODO: windows style
    16  //
    17  func RemovePath(s string) string {
    18  	out := bytes.Buffer{}
    19  	var idx int
    20  	for len(s) > 0 {
    21  		if idx = strings.IndexByte(s, '/'); idx == -1 {
    22  			out.WriteString(s)
    23  			break
    24  		}
    25  
    26  		if idx > 0 {
    27  			idx--
    28  		}
    29  
    30  		var chclass string
    31  		switch s[idx] {
    32  		case '/', ' ', '\n', '\t', '\r':
    33  			chclass = " \n\r\t"
    34  		case '[':
    35  			chclass = "]\n"
    36  		case '(':
    37  			chclass = ")\n"
    38  		default:
    39  			out.WriteString(s[:idx+2])
    40  			s = s[idx+2:]
    41  			continue
    42  		}
    43  
    44  		endx := strings.IndexAny(s[idx+1:], chclass)
    45  		if endx != -1 {
    46  			out.WriteString(s[:idx+1])
    47  			out.Write(bytes.Repeat([]byte{' '}, endx))
    48  			s = s[idx+endx+1:]
    49  		} else {
    50  			out.WriteString(s)
    51  			break
    52  		}
    53  	}
    54  	return out.String()
    55  }
    56  
    57  // replaceWithBlanks returns a string with the same number of spaces as the input
    58  func replaceWithBlanks(s string) string {
    59  	return strings.Repeat(" ", len(s))
    60  }
    61  
    62  // RemoveEmail remove email-like strings, e.g. "nickg+junk@xfoobar.com", "nickg@xyz.abc123.biz"
    63  func RemoveEmail(s string) string {
    64  	return reEmail.ReplaceAllStringFunc(s, replaceWithBlanks)
    65  }
    66  
    67  // RemoveHost removes host-like strings "foobar.com" "abc123.fo1231.biz"
    68  func RemoveHost(s string) string {
    69  	return reHost.ReplaceAllStringFunc(s, replaceWithBlanks)
    70  }
    71  
    72  // RemoveNotWords blanks out all the not words
    73  func RemoveNotWords(s string) string {
    74  	// do most selective/specific first
    75  	return RemoveHost(RemoveEmail(RemovePath(StripURL(s))))
    76  }