File: changeset_writer.go

package info (click to toggle)
golang-gitea-noerw-unidiff-comments 0.0~git20220822.50f4daa%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 336 kB
  • sloc: makefile: 4
file content (57 lines) | stat: -rw-r--r-- 1,406 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
package writer

import (
	"io"
	"regexp"
	"strings"
	"text/template"

	"gitea.com/noerw/unidiff-comments/types"

	"github.com/seletskiy/tplutil"
)

var changesetTpl = template.New("changeset")

func init() {
	commentsTpl := template.New("comment")

	reBeginningOfLine := regexp.MustCompile(`(?m)^`)
	reNewLine := regexp.MustCompile(`^|\n`)
	reDanglingSpace := regexp.MustCompile(`(?m)\s+$`)

	funcs := template.FuncMap{
		"indent": func(input string) string {
			return reBeginningOfLine.ReplaceAllString(input, "    ")
		},
		"writeComments": func(input types.CommentsTree) string {
			res, _ := tplutil.ExecuteToString(commentsTpl, input)
			return res
		},
		"writeNote": func(input string) string {
			return types.Note(input)
		},
		"trimWhitespace": func(input string) string {
			return strings.TrimSpace(input)
		},
		"comment": func(input string) string {
			//log.Printf("%#v", input)
			return reDanglingSpace.ReplaceAllString(
				reNewLine.ReplaceAllString(input, `$0# `),
				``,
			)
		},
	}

	template.Must(
		commentsTpl.Funcs(funcs).Funcs(tplutil.Last).Parse(
			tplutil.Strip(commentsTplText)))
	template.Must(
		changesetTpl.Funcs(funcs).Funcs(tplutil.Last).Parse(
			tplutil.Strip(changesetTplText)))
}

// WriteChangeset outputs a changeset in unidiff format to writer
func WriteChangeset(changeset types.Changeset, to io.Writer) error {
	return changesetTpl.Execute(to, changeset)
}