github.com/dmaizel/tests@v0.0.0-20210728163746-cae6a2d9cee8/cmd/check-markdown/utils.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 "errors" 11 "fmt" 12 "os" 13 "strings" 14 "unicode" 15 16 bf "gopkg.in/russross/blackfriday.v2" 17 ) 18 19 // fileExists returns true if the specified file exists, else false. 20 func fileExists(path string) bool { 21 if _, err := os.Stat(path); os.IsNotExist(err) { 22 return false 23 } 24 25 return true 26 } 27 28 // splitLink splits a link like "foo.md#section-name" into a filename 29 // ("foo.md") and a section name ("section-name"). 30 func splitLink(linkName string) (fileName, sectionName string, err error) { 31 if linkName == "" { 32 return "", "", errors.New("need linkName") 33 } 34 35 if !strings.Contains(linkName, anchorPrefix) { 36 return linkName, "", nil 37 } 38 39 fields := strings.Split(linkName, anchorPrefix) 40 41 expectedFields := 2 42 foundFields := len(fields) 43 if foundFields != expectedFields { 44 45 return "", "", fmt.Errorf("invalid link %s: expected %d fields, found %d", linkName, expectedFields, foundFields) 46 } 47 48 fileName = fields[0] 49 sectionName = fields[1] 50 51 return fileName, sectionName, nil 52 } 53 54 // validHeadingIDChar is a strings.Map() function used to determine which characters 55 // can appear in a heading ID. 56 func validHeadingIDChar(r rune) rune { 57 if unicode.IsLetter(r) || 58 unicode.IsNumber(r) || 59 unicode.IsSpace(r) || 60 r == '-' || r == '_' { 61 return r 62 } 63 64 // Remove all other chars from destination string 65 return -1 66 } 67 68 // createHeadingID creates an HTML anchor name for the specified heading 69 func createHeadingID(headingName string) (id string, err error) { 70 if headingName == "" { 71 return "", fmt.Errorf("need heading name") 72 } 73 74 // Munge the original heading into an id by: 75 // 76 // - removing invalid characters. 77 // - lower-casing. 78 // - replace spaces 79 id = strings.Map(validHeadingIDChar, headingName) 80 81 id = strings.ToLower(id) 82 id = strings.Replace(id, " ", "-", -1) 83 84 return id, nil 85 } 86 87 func checkNode(node *bf.Node, expectedType bf.NodeType) error { 88 if node == nil { 89 return errors.New("node cannot be nil") 90 } 91 92 if node.Type != expectedType { 93 return fmt.Errorf("expected %v node, found %v", expectedType, node.Type) 94 } 95 96 return nil 97 }