summaryrefslogtreecommitdiffstats
path: root/modules/markup/csv/csv.go
blob: 68c89166b5b06472fd9d482d395620d2d3eee09c (plain)
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// Copyright 2018 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package markup

import (
	"bytes"
	"html"
	"io"
	"strconv"

	"code.gitea.io/gitea/modules/csv"
	"code.gitea.io/gitea/modules/markup"
	"code.gitea.io/gitea/modules/setting"
)

func init() {
	markup.RegisterParser(Parser{})
}

// Parser implements markup.Parser for csv files
type Parser struct {
}

// Name implements markup.Parser
func (Parser) Name() string {
	return "csv"
}

// NeedPostProcess implements markup.Parser
func (Parser) NeedPostProcess() bool { return false }

// Extensions implements markup.Parser
func (Parser) Extensions() []string {
	return []string{".csv", ".tsv"}
}

// Render implements markup.Parser
func (Parser) Render(rawBytes []byte, urlPrefix string, metas map[string]string, isWiki bool) []byte {
	var tmpBlock bytes.Buffer

	if setting.UI.CSV.MaxFileSize != 0 && setting.UI.CSV.MaxFileSize < int64(len(rawBytes)) {
		tmpBlock.WriteString("<pre>")
		tmpBlock.WriteString(html.EscapeString(string(rawBytes)))
		tmpBlock.WriteString("</pre>")
		return tmpBlock.Bytes()
	}

	rd := csv.CreateReaderAndGuessDelimiter(rawBytes)

	writeField := func(element, class, field string) {
		tmpBlock.WriteString("<")
		tmpBlock.WriteString(element)
		if len(class) > 0 {
			tmpBlock.WriteString(" class=\"")
			tmpBlock.WriteString(class)
			tmpBlock.WriteString("\"")
		}
		tmpBlock.WriteString(">")
		tmpBlock.WriteString(html.EscapeString(field))
		tmpBlock.WriteString("</")
		tmpBlock.WriteString(element)
		tmpBlock.WriteString(">")
	}

	tmpBlock.WriteString(`<table class="data-table">`)
	row := 1
	for {
		fields, err := rd.Read()
		if err == io.EOF {
			break
		}
		if err != nil {
			continue
		}
		tmpBlock.WriteString("<tr>")
		element := "td"
		if row == 1 {
			element = "th"
		}
		writeField(element, "line-num", strconv.Itoa(row))
		for _, field := range fields {
			writeField(element, "", field)
		}
		tmpBlock.WriteString("</tr>")

		row++
	}
	tmpBlock.WriteString("</table>")

	return tmpBlock.Bytes()
}