File: write_comment.go

package info (click to toggle)
golang-github-pocketbase-tygoja 0.0~git20250812.97ffe05-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,164 kB
  • sloc: javascript: 5; makefile: 4
file content (66 lines) | stat: -rw-r--r-- 1,422 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package tygoja

import (
	"go/ast"
	"strings"
)

func (g *PackageGenerator) writeCommentGroup(s *strings.Builder, f *ast.CommentGroup, depth int) {
	if f == nil {
		return
	}

	docLines := strings.Split(f.Text(), "\n")

	g.writeIndent(s, depth)
	s.WriteString("/**\n")

	lastLineIdx := len(docLines) - 1

	var isCodeBlock bool

	emptySB := new(strings.Builder)

	for i, c := range docLines {
		isEndLine := i == lastLineIdx
		isEmpty := len(strings.TrimSpace(c)) == 0
		isIndented := strings.HasPrefix(c, "\t") || strings.HasPrefix(c, "  ")

		// end code block
		if isCodeBlock && (isEndLine || (!isIndented && !isEmpty)) {
			g.writeIndent(s, depth)
			s.WriteString(" * ```\n")
			isCodeBlock = false
		}

		// accumulate empty comment lines
		// (this is done to properly enclose code blocks with new lines)
		if isEmpty {
			g.writeIndent(emptySB, depth)
			emptySB.WriteString(" * \n")
		} else {
			// write all empty lines
			s.WriteString(emptySB.String())
			emptySB.Reset()
		}

		// start code block
		if isIndented && !isCodeBlock && !isEndLine {
			g.writeIndent(s, depth)
			s.WriteString(" * ```\n")
			isCodeBlock = true
		}

		// write comment line
		if !isEmpty {
			g.writeIndent(s, depth)
			s.WriteString(" * ")
			c = strings.ReplaceAll(c, "*/", "*\\/") // An edge case: a // comment can contain */
			s.WriteString(c)
			s.WriteByte('\n')
		}
	}

	g.writeIndent(s, depth)
	s.WriteString(" */\n")
}