MCPcopy Create free account
hub / github.com/cli/cli / scanMarkdownRefs

Function scanMarkdownRefs

internal/attachments/references.go:245–302  ·  view source on GitHub ↗

scanMarkdownRefs finds every place the markdown names one of the attached files.

(md, markdownDir string, attachmentArgs []attachmentArg)

Source from the content-addressed store, hash-verified

243// scanMarkdownRefs finds every place the markdown names one of the attached
244// files.
245func scanMarkdownRefs(md, markdownDir string, attachmentArgs []attachmentArg) ([]attachmentRef, error) {
246 byPath, err := attachmentArgsByPath(attachmentArgs)
247 if err != nil {
248 return nil, err
249 }
250
251 src := []byte(md)
252 doc := goldmark.New().Parser().Parse(text.NewReader(src))
253 defs := linkReferenceDefinitions(doc, len(src))
254
255 var refs []attachmentRef
256
257 err = ast.Walk(doc, func(n ast.Node, entering bool) (ast.WalkStatus, error) {
258 if !entering {
259 return ast.WalkContinue, nil
260 }
261
262 dest, isEmbed, ok := linkDestination(n)
263 if !ok {
264 return ast.WalkContinue, nil
265 }
266 idx, ok := attachmentArgForDestination(dest, markdownDir, byPath)
267 if !ok {
268 return ast.WalkContinue, nil
269 }
270
271 // The nearest block ancestor is what carries position information.
272 var block ast.Node
273 for p := n.Parent(); p != nil; p = p.Parent() {
274 if p.Type() == ast.TypeBlock {
275 block = p
276 break
277 }
278 }
279 _, hi, ok := blockRange(block, len(src))
280 if !ok {
281 return ast.WalkContinue, nil
282 }
283
284 if ranges, ok := inlineRanges(src, n, hi); ok {
285 refs = append(refs, attachmentRef{attachmentArg: idx, isEmbed: isEmbed, ranges: ranges, block: block})
286 return ast.WalkContinue, nil
287 }
288
289 // No destination beside the reference means a reference-style link. Every
290 // definition carrying this destination is rewritten, since a node
291 // records no label to tell them apart and a spare definition renders
292 // nothing.
293 if matches := defs[comparableDestination(dest)]; len(matches) > 0 {
294 refs = append(refs, attachmentRef{attachmentArg: idx, isEmbed: isEmbed, defs: matches})
295 }
296 return ast.WalkContinue, nil
297 })
298 if err != nil {
299 return nil, err
300 }
301 return refs, nil
302}

Callers 1

newAttachableMarkdownFunction · 0.85

Calls 8

attachmentArgsByPathFunction · 0.85
linkReferenceDefinitionsFunction · 0.85
linkDestinationFunction · 0.85
blockRangeFunction · 0.85
inlineRangesFunction · 0.85
comparableDestinationFunction · 0.85
TypeMethod · 0.45

Tested by

no test coverage detected