github.com/kata-containers/tests@v0.0.0-20240307153542-772105b56064/cmd/check-markdown/extract.go (about)

     1  //
     2  // Copyright (c) 2019 Intel Corporation
     3  //
     4  // SPDX-License-Identifier: Apache-2.0
     5  //
     6  
     7  package main
     8  
     9  import (
    10  	"fmt"
    11  
    12  	bf "gopkg.in/russross/blackfriday.v2"
    13  )
    14  
    15  // linkDescription extracts the description from the specified link node.
    16  func linkDescription(l *bf.Node) (string, error) {
    17  	if err := checkNode(l, bf.Link); err != nil {
    18  		return "", err
    19  	}
    20  
    21  	// A link description can be comprised of various elements so scan
    22  	// through them to build up the final value.
    23  
    24  	text := ""
    25  	node := l.FirstChild
    26  
    27  	for node != nil {
    28  		switch node.Type {
    29  		case bf.Code:
    30  			text += string(node.Literal)
    31  		case bf.Text:
    32  			text += string(node.Literal)
    33  		default:
    34  			logger.WithField("node", node).Debug("ignoring node")
    35  		}
    36  
    37  		if node == l.LastChild {
    38  			break
    39  		}
    40  
    41  		node = node.Next
    42  	}
    43  
    44  	return text, nil
    45  }
    46  
    47  // headingName extracts the heading name from the specified Heading node in
    48  // plain text, and markdown. The latter is used for creating TOC's which need
    49  // to include the original markdown value.
    50  func headingName(h *bf.Node) (name, mdName string, err error) {
    51  	if err = checkNode(h, bf.Heading); err != nil {
    52  		return "", "", err
    53  	}
    54  
    55  	// A heading can be comprised of various elements so scan
    56  	// through them to build up the final value.
    57  
    58  	node := h.FirstChild
    59  
    60  	for node != nil {
    61  		switch node.Type {
    62  		case bf.Code:
    63  			value := string(node.Literal)
    64  
    65  			name += value
    66  			mdName += fmt.Sprintf("`%s`", value)
    67  		case bf.Text:
    68  			value := string(node.Literal)
    69  
    70  			name += value
    71  			mdName += value
    72  		case bf.Link:
    73  			// yep, people do crazy things like adding links into titles!
    74  			descr, err := linkDescription(node)
    75  			if err != nil {
    76  				return "", "", err
    77  			}
    78  
    79  			name += descr
    80  			mdName += descr
    81  		default:
    82  			logger.WithField("node", node).Debug("ignoring node")
    83  		}
    84  
    85  		if node == h.LastChild {
    86  			break
    87  		}
    88  
    89  		node = node.Next
    90  	}
    91  
    92  	return name, mdName, nil
    93  }