github.com/kata-containers/tests@v0.0.0-20240307153542-772105b56064/cmd/check-markdown/hack.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  	"strings"
    11  
    12  	bf "gopkg.in/russross/blackfriday.v2"
    13  )
    14  
    15  // forceCreateHeadings extracts "missed" headings from the specified node,
    16  // returning a slice of the newly headings created (which need to be added by the
    17  // caller).
    18  //
    19  // Alas, Black Friday isn't 100% reliable...
    20  func (d *Doc) forceCreateHeadings(node *bf.Node) ([]Heading, error) {
    21  	if err := checkNode(node, bf.Text); err != nil {
    22  		return []Heading{}, err
    23  	}
    24  
    25  	chunk := string(node.Literal)
    26  
    27  	if chunk == "" {
    28  		// No text in this node
    29  		return []Heading{}, nil
    30  	}
    31  
    32  	lines := strings.Split(chunk, "\n")
    33  	if len(lines) <= 1 {
    34  		// No headings lurking in this text node
    35  		return []Heading{}, nil
    36  	}
    37  
    38  	var headings []Heading
    39  
    40  	for _, line := range lines {
    41  		if !strings.HasPrefix(line, anchorPrefix) {
    42  			continue
    43  		}
    44  
    45  		fields := strings.Split(line, anchorPrefix)
    46  		name := strings.Join(fields, "")
    47  		name = strings.TrimSpace(name)
    48  
    49  		count := strings.Count(line, anchorPrefix)
    50  
    51  		heading := Heading{
    52  			Name:  name,
    53  			Level: count,
    54  		}
    55  
    56  		id, err := createHeadingID(heading.Name)
    57  		if err != nil {
    58  			return []Heading{}, err
    59  		}
    60  
    61  		heading.LinkName = id
    62  
    63  		headings = append(headings, heading)
    64  
    65  		extraHeadings++
    66  	}
    67  
    68  	return headings, nil
    69  }