github.com/graemephi/kahugo@v0.62.3-0.20211121071557-d78c0423784d/common/herrors/line_number_extractors.go (about) 1 // Copyright 2018 The Hugo Authors. All rights reserved. 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 // http://www.apache.org/licenses/LICENSE-2.0 7 // 8 // Unless required by applicable law or agreed to in writing, software 9 // distributed under the License is distributed on an "AS IS" BASIS, 10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package herrors 15 16 import ( 17 "regexp" 18 "strconv" 19 20 "github.com/pkg/errors" 21 22 "github.com/pelletier/go-toml/v2" 23 ) 24 25 var lineNumberExtractors = []lineNumberExtractor{ 26 // Template/shortcode parse errors 27 newLineNumberErrHandlerFromRegexp(".*:(\\d+):(\\d*):"), 28 newLineNumberErrHandlerFromRegexp(".*:(\\d+):"), 29 30 // TOML parse errors 31 tomlLineNumberExtractor, 32 // YAML parse errors 33 newLineNumberErrHandlerFromRegexp("line (\\d+):"), 34 35 // i18n bundle errors 36 newLineNumberErrHandlerFromRegexp("\\((\\d+),\\s(\\d*)"), 37 } 38 39 type lineNumberExtractor func(e error) (int, int) 40 41 var tomlLineNumberExtractor = func(e error) (int, int) { 42 e = errors.Cause(e) 43 if terr, ok := e.(*toml.DecodeError); ok { 44 return terr.Position() 45 } 46 return -1, -1 47 } 48 49 func newLineNumberErrHandlerFromRegexp(expression string) lineNumberExtractor { 50 re := regexp.MustCompile(expression) 51 return extractLineNo(re) 52 } 53 54 func extractLineNo(re *regexp.Regexp) lineNumberExtractor { 55 return func(e error) (int, int) { 56 if e == nil { 57 panic("no error") 58 } 59 col := 1 60 s := e.Error() 61 m := re.FindStringSubmatch(s) 62 if len(m) >= 2 { 63 lno, _ := strconv.Atoi(m[1]) 64 if len(m) > 2 { 65 col, _ = strconv.Atoi(m[2]) 66 } 67 68 if col <= 0 { 69 col = 1 70 } 71 72 return lno, col 73 } 74 75 return -1, col 76 } 77 }