line_number_extractors.go (1583B)
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 21 var lineNumberExtractors = []lineNumberExtractor{ 22 // Template/shortcode parse errors 23 newLineNumberErrHandlerFromRegexp(`:(\d+):(\d*):`), 24 newLineNumberErrHandlerFromRegexp(`:(\d+):`), 25 26 // YAML parse errors 27 newLineNumberErrHandlerFromRegexp(`line (\d+):`), 28 29 // i18n bundle errors 30 newLineNumberErrHandlerFromRegexp(`\((\d+),\s(\d*)`), 31 } 32 33 type lineNumberExtractor func(e error) (int, int) 34 35 func newLineNumberErrHandlerFromRegexp(expression string) lineNumberExtractor { 36 re := regexp.MustCompile(expression) 37 return extractLineNo(re) 38 } 39 40 func extractLineNo(re *regexp.Regexp) lineNumberExtractor { 41 return func(e error) (int, int) { 42 if e == nil { 43 panic("no error") 44 } 45 col := 1 46 s := e.Error() 47 m := re.FindStringSubmatch(s) 48 if len(m) >= 2 { 49 lno, _ := strconv.Atoi(m[1]) 50 if len(m) > 2 { 51 col, _ = strconv.Atoi(m[2]) 52 } 53 54 if col <= 0 { 55 col = 1 56 } 57 58 return lno, col 59 } 60 61 return 0, col 62 } 63 }