Debian Codegraph @

common/herrors/line_number_extractors.go

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