repos / pico

pico services - prose.sh, pastes.sh, imgs.sh, feeds.sh, pgs.sh
git clone https://github.com/picosh/pico.git

commit
5f4b1c3
parent
91aad91
author
ChloƩ Vulquin
date
2024-03-08 19:58:26 +0000 UTC
mdparser: extract hashtag detection into a func

Also fix a bug where `tags: []` would still do the detection.
1 files changed,  +39, -34
M shared/mdparser.go
+39, -34
 1@@ -289,44 +289,14 @@ func ParseText(text string) (*ParsedText, error) {
 2 	}
 3 	parsed.MetaData.Aliases = aliases
 4 
 5-	tags, err := toTags(metaData["tags"])
 6+	rtags := metaData["tags"]
 7+	tags, err := toTags(rtags)
 8 	if err != nil {
 9 		return &parsed, err
10 	}
11 	// fill from hashtag ASTs as fallback
12-	if len(tags) == 0 {
13-		// collect all matching tags
14-		err = ast.Walk(doc, func(n ast.Node, entering bool) (ast.WalkStatus, error) {
15-			switch n.Kind() {
16-			// ignore hashtags inside of these sections
17-			case ast.KindBlockquote, ast.KindCodeBlock, ast.KindCodeSpan:
18-				return ast.WalkSkipChildren, nil
19-			// register hashtags
20-			case hashtag.Kind:
21-				t := n.(*hashtag.Node)
22-				if entering { // only add each tag once
23-					tags = append(tags, string(t.Tag))
24-				}
25-			}
26-			// out-of-switch default
27-			return ast.WalkContinue, nil
28-		})
29-		if err != nil {
30-			panic(err)
31-		}
32-
33-		// sort and deduplicate results
34-		sort.Strings(tags)
35-		e := 1
36-		for i := 1; i < len(tags); i++ {
37-			// this works because we're keeping tags[0]
38-			if tags[i] == tags[i-1] {
39-				continue
40-			}
41-			tags[e] = tags[i]
42-			e++
43-		}
44-		tags = tags[:e]
45+	if rtags == nil {
46+		tags = AstTags(doc)
47 	}
48 	parsed.MetaData.Tags = tags
49 
50@@ -341,6 +311,41 @@ func ParseText(text string) (*ParsedText, error) {
51 	return &parsed, nil
52 }
53 
54+func AstTags(doc ast.Node) []string {
55+	var tags []string
56+	err := ast.Walk(doc, func(n ast.Node, entering bool) (ast.WalkStatus, error) {
57+		switch n.Kind() {
58+		// ignore hashtags inside of these sections
59+		case ast.KindBlockquote, ast.KindCodeBlock, ast.KindCodeSpan:
60+			return ast.WalkSkipChildren, nil
61+		// register hashtags
62+		case hashtag.Kind:
63+			t := n.(*hashtag.Node)
64+			if entering { // only add each tag once
65+				tags = append(tags, string(t.Tag))
66+			}
67+		}
68+		// out-of-switch default
69+		return ast.WalkContinue, nil
70+	})
71+	if err != nil {
72+		panic(err)
73+	}
74+
75+	// sort and deduplicate results
76+	sort.Strings(tags)
77+	e := 1
78+	for i := 1; i < len(tags); i++ {
79+		// this works because we're keeping tags[0]
80+		if tags[i] == tags[i-1] {
81+			continue
82+		}
83+		tags[e] = tags[i]
84+		e++
85+	}
86+	return tags[:e]
87+}
88+
89 // AstTitle extracts the title (if any) from a parsed markdown document.
90 //
91 // If "clean" is true, it will also remove the heading node from the AST.