本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

114 line
2.6KB

  1. // Copyright 2018 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package markup
  5. import (
  6. "bytes"
  7. "encoding/csv"
  8. "html"
  9. "io"
  10. "regexp"
  11. "strings"
  12. "code.gitea.io/gitea/modules/markup"
  13. "code.gitea.io/gitea/modules/util"
  14. )
  15. var quoteRegexp = regexp.MustCompile(`["'][\s\S]+?["']`)
  16. func init() {
  17. markup.RegisterParser(Parser{})
  18. }
  19. // Parser implements markup.Parser for orgmode
  20. type Parser struct {
  21. }
  22. // Name implements markup.Parser
  23. func (Parser) Name() string {
  24. return "csv"
  25. }
  26. // Extensions implements markup.Parser
  27. func (Parser) Extensions() []string {
  28. return []string{".csv", ".tsv"}
  29. }
  30. // Render implements markup.Parser
  31. func (p Parser) Render(rawBytes []byte, urlPrefix string, metas map[string]string, isWiki bool) []byte {
  32. rd := csv.NewReader(bytes.NewReader(rawBytes))
  33. rd.Comma = p.bestDelimiter(rawBytes)
  34. var tmpBlock bytes.Buffer
  35. tmpBlock.WriteString(`<table class="table">`)
  36. for {
  37. fields, err := rd.Read()
  38. if err == io.EOF {
  39. break
  40. }
  41. if err != nil {
  42. continue
  43. }
  44. tmpBlock.WriteString("<tr>")
  45. for _, field := range fields {
  46. tmpBlock.WriteString("<td>")
  47. tmpBlock.WriteString(html.EscapeString(field))
  48. tmpBlock.WriteString("</td>")
  49. }
  50. tmpBlock.WriteString("</tr>")
  51. }
  52. tmpBlock.WriteString("</table>")
  53. return tmpBlock.Bytes()
  54. }
  55. // bestDelimiter scores the input CSV data against delimiters, and returns the best match.
  56. // Reads at most 10k bytes & 10 lines.
  57. func (p Parser) bestDelimiter(data []byte) rune {
  58. maxLines := 10
  59. maxBytes := util.Min(len(data), 1e4)
  60. text := string(data[:maxBytes])
  61. text = quoteRegexp.ReplaceAllLiteralString(text, "")
  62. lines := strings.SplitN(text, "\n", maxLines+1)
  63. lines = lines[:util.Min(maxLines, len(lines))]
  64. delimiters := []rune{',', ';', '\t', '|'}
  65. bestDelim := delimiters[0]
  66. bestScore := 0.0
  67. for _, delim := range delimiters {
  68. score := p.scoreDelimiter(lines, delim)
  69. if score > bestScore {
  70. bestScore = score
  71. bestDelim = delim
  72. }
  73. }
  74. return bestDelim
  75. }
  76. // scoreDelimiter uses a count & regularity metric to evaluate a delimiter against lines of CSV
  77. func (Parser) scoreDelimiter(lines []string, delim rune) (score float64) {
  78. countTotal := 0
  79. countLineMax := 0
  80. linesNotEqual := 0
  81. for _, line := range lines {
  82. if len(line) == 0 {
  83. continue
  84. }
  85. countLine := strings.Count(line, string(delim))
  86. countTotal += countLine
  87. if countLine != countLineMax {
  88. if countLineMax != 0 {
  89. linesNotEqual++
  90. }
  91. countLineMax = util.Max(countLine, countLineMax)
  92. }
  93. }
  94. return float64(countTotal) * (1 - float64(linesNotEqual)/float64(len(lines)))
  95. }
上海开阖软件有限公司 沪ICP备12045867号-1