Debian Codegraph @

parser/pageparser/pageparser.go

raw
1 // Copyright 2019 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 pageparser
15
16 import (
17 "bytes"
18 "errors"
19 "fmt"
20 "io"
21 "regexp"
22 "strings"
23
24 "github.com/gohugoio/hugo/common/hugio"
25 "github.com/gohugoio/hugo/parser/metadecoders"
26 )
27
28 // Result holds the parse result.
29 type Result interface {
30 // Iterator returns a new Iterator positioned at the beginning of the parse tree.
31 Iterator() *Iterator
32 // Input returns the input to Parse.
33 Input() []byte
34 }
35
36 var _ Result = (*pageLexer)(nil)
37
38 // ParseBytes parses the page in b according to the given Config.
39 func ParseBytes(b []byte, cfg Config) (Items, error) {
40 startLexer := lexIntroSection
41 if cfg.NoFrontMatter {
42 startLexer = lexMainSection
43 }
44 l, err := parseBytes(b, cfg, startLexer)
45 if err != nil {
46 return nil, err
47 }
48 return l.items, l.err
49 }
50
51 type ContentFrontMatter struct {
52 Content []byte
53 FrontMatter map[string]any
54 FrontMatterFormat metadecoders.Format
55 }
56
57 // ParseFrontMatterAndContent is a convenience method to extract front matter
58 // and content from a content page.
59 func ParseFrontMatterAndContent(r io.Reader) (ContentFrontMatter, error) {
60 var cf ContentFrontMatter
61
62 input, err := hugio.ReadAll(r)
63 if err != nil {
64 return cf, fmt.Errorf("failed to read page content: %w", err)
65 }
66
67 psr, err := ParseBytes(input, Config{})
68 if err != nil {
69 return cf, err
70 }
71
72 var frontMatterSource []byte
73
74 iter := NewIterator(psr)
75
76 walkFn := func(item Item) bool {
77 if frontMatterSource != nil {
78 // The rest is content.
79 cf.Content = input[item.low:]
80 // Done
81 return false
82 } else if item.IsFrontMatter() {
83 cf.FrontMatterFormat = FormatFromFrontMatterType(item.Type)
84 frontMatterSource = item.Val(input)
85 }
86 return true
87 }
88
89 iter.PeekWalk(walkFn)
90
91 cf.FrontMatter, err = metadecoders.Default.UnmarshalToMap(frontMatterSource, cf.FrontMatterFormat)
92 return cf, err
93 }
94
95 func FormatFromFrontMatterType(typ ItemType) metadecoders.Format {
96 switch typ {
97 case TypeFrontMatterJSON:
98 return metadecoders.JSON
99 case TypeFrontMatterORG:
100 return metadecoders.ORG
101 case TypeFrontMatterTOML:
102 return metadecoders.TOML
103 case TypeFrontMatterYAML:
104 return metadecoders.YAML
105 default:
106 return ""
107 }
108 }
109
110 // ParseMain parses starting with the main section. Used in tests.
111 func ParseMain(r io.Reader, cfg Config) (Result, error) {
112 return parseSection(r, cfg, lexMainSection)
113 }
114
115 func parseSection(r io.Reader, cfg Config, start stateFunc) (Result, error) {
116 b, err := io.ReadAll(r)
117 if err != nil {
118 return nil, fmt.Errorf("failed to read page content: %w", err)
119 }
120 return parseBytes(b, cfg, start)
121 }
122
123 func parseBytes(b []byte, cfg Config, start stateFunc) (*pageLexer, error) {
124 lexer := newPageLexer(b, start, cfg)
125 lexer.run()
126 return lexer, nil
127 }
128
129 // NewIterator creates a new Iterator.
130 func NewIterator(items Items) *Iterator {
131 return &Iterator{items: items, lastPos: -1}
132 }
133
134 // An Iterator has methods to iterate a parsed page with support going back
135 // if needed.
136 type Iterator struct {
137 items Items
138 lastPos int // position of the last item returned by nextItem
139 }
140
141 // consumes and returns the next item
142 func (t *Iterator) Next() Item {
143 t.lastPos++
144 return t.Current()
145 }
146
147 var errIndexOutOfBounds = Item{Type: tError, Err: errors.New("no more tokens")}
148
149 // Current will repeatably return the current item.
150 func (t *Iterator) Current() Item {
151 if t.lastPos >= len(t.items) {
152 return errIndexOutOfBounds
153 }
154 return t.items[t.lastPos]
155 }
156
157 // backs up one token.
158 func (t *Iterator) Backup() {
159 if t.lastPos < 0 {
160 panic("need to go forward before going back")
161 }
162 t.lastPos--
163 }
164
165 // Pos returns the current position in the input.
166 func (t *Iterator) Pos() int {
167 return t.lastPos
168 }
169
170 // check for non-error and non-EOF types coming next
171 func (t *Iterator) IsValueNext() bool {
172 i := t.Peek()
173 return i.Type != tError && i.Type != tEOF
174 }
175
176 // look at, but do not consume, the next item
177 // repeated, sequential calls will return the same item
178 func (t *Iterator) Peek() Item {
179 return t.items[t.lastPos+1]
180 }
181
182 // PeekWalk will feed the next items in the iterator to walkFn
183 // until it returns false.
184 func (t *Iterator) PeekWalk(walkFn func(item Item) bool) {
185 for i := t.lastPos + 1; i < len(t.items); i++ {
186 item := t.items[i]
187 if !walkFn(item) {
188 break
189 }
190 }
191 }
192
193 // Consume is a convenience method to consume the next n tokens,
194 // but back off Errors and EOF.
195 func (t *Iterator) Consume(cnt int) {
196 for range cnt {
197 token := t.Next()
198 if token.Type == tError || token.Type == tEOF {
199 t.Backup()
200 break
201 }
202 }
203 }
204
205 // LineNumber returns the current line number. Used for logging.
206 func (t *Iterator) LineNumber(source []byte) int {
207 return bytes.Count(source[:t.Current().low], lf) + 1
208 }
209
210 // IsProbablySourceOfItems returns true if the given source looks like original
211 // source of the items.
212 // There may be some false positives, but that is highly unlikely and good enough
213 // for the planned purpose.
214 // It will also return false if the last item is not EOF (error situations) and
215 // true if both source and items are empty.
216 func IsProbablySourceOfItems(source []byte, items Items) bool {
217 if len(source) == 0 && len(items) == 0 {
218 return false
219 }
220 if len(items) == 0 {
221 return false
222 }
223
224 last := items[len(items)-1]
225 if last.Type != tEOF {
226 return false
227 }
228
229 if last.Pos() != len(source) {
230 return false
231 }
232
233 for _, item := range items {
234 if item.Type == tError {
235 return false
236 }
237 if item.Type == tEOF {
238 return true
239 }
240
241 if item.Pos() >= len(source) {
242 return false
243 }
244
245 if item.firstByte != source[item.Pos()] {
246 return false
247 }
248 }
249
250 return true
251 }
252
253 var hasShortcodeRe = regexp.MustCompile(`{{[%,<][^\/]`)
254
255 // HasShortcode returns true if the given string contains a shortcode.
256 func HasShortcode(s string) bool {
257 // Fast path for the common case.
258 if !strings.Contains(s, "{{") {
259 return false
260 }
261 return hasShortcodeRe.MatchString(s)
262 }