gitea源码

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package csv
  4. import (
  5. "bytes"
  6. stdcsv "encoding/csv"
  7. "io"
  8. "path"
  9. "regexp"
  10. "strings"
  11. "code.gitea.io/gitea/modules/markup"
  12. "code.gitea.io/gitea/modules/translation"
  13. "code.gitea.io/gitea/modules/util"
  14. )
  15. const (
  16. maxLines = 10
  17. guessSampleSize = 1e4 // 10k
  18. )
  19. // CreateReader creates a csv.Reader with the given delimiter.
  20. func CreateReader(input io.Reader, delimiter rune) *stdcsv.Reader {
  21. rd := stdcsv.NewReader(input)
  22. rd.Comma = delimiter
  23. if delimiter != '\t' && delimiter != ' ' {
  24. // TrimLeadingSpace can't be true when delimiter is a tab or a space as the value for a column might be empty,
  25. // thus would change `\t\t` to just `\t` or ` ` (two spaces) to just ` ` (single space)
  26. rd.TrimLeadingSpace = true
  27. }
  28. // Don't force validation of every row to have the same number of entries as the first row.
  29. rd.FieldsPerRecord = -1
  30. return rd
  31. }
  32. // CreateReaderAndDetermineDelimiter tries to guess the field delimiter from the content and creates a csv.Reader.
  33. // Reads at most guessSampleSize bytes.
  34. func CreateReaderAndDetermineDelimiter(ctx *markup.RenderContext, rd io.Reader) (*stdcsv.Reader, error) {
  35. data := make([]byte, guessSampleSize)
  36. size, err := util.ReadAtMost(rd, data)
  37. if err != nil {
  38. return nil, err
  39. }
  40. return CreateReader(
  41. io.MultiReader(bytes.NewReader(data[:size]), rd),
  42. determineDelimiter(ctx, data[:size]),
  43. ), nil
  44. }
  45. // determineDelimiter takes a RenderContext and if it isn't nil and the Filename has an extension that specifies the delimiter,
  46. // it is used as the delimiter. Otherwise we call guessDelimiter with the data passed
  47. func determineDelimiter(ctx *markup.RenderContext, data []byte) rune {
  48. extension := ".csv"
  49. if ctx != nil {
  50. extension = strings.ToLower(path.Ext(ctx.RenderOptions.RelativePath))
  51. }
  52. var delimiter rune
  53. switch extension {
  54. case ".tsv":
  55. delimiter = '\t'
  56. case ".psv":
  57. delimiter = '|'
  58. default:
  59. delimiter = guessDelimiter(data)
  60. }
  61. return delimiter
  62. }
  63. // quoteRegexp follows the RFC-4180 CSV standard for when double-quotes are used to enclose fields, then a double-quote appearing inside a
  64. // field must be escaped by preceding it with another double quote. https://www.ietf.org/rfc/rfc4180.txt
  65. // This finds all quoted strings that have escaped quotes.
  66. var quoteRegexp = regexp.MustCompile(`"[^"]*"`)
  67. // removeQuotedStrings uses the quoteRegexp to remove all quoted strings so that we can reliably have each row on one line
  68. // (quoted strings often have new lines within the string)
  69. func removeQuotedString(text string) string {
  70. return quoteRegexp.ReplaceAllLiteralString(text, "")
  71. }
  72. // guessDelimiter takes up to maxLines of the CSV text, iterates through the possible delimiters, and sees if the CSV Reader reads it without throwing any errors.
  73. // If more than one delimiter passes, the delimiter that results in the most columns is returned.
  74. func guessDelimiter(data []byte) rune {
  75. delimiter := guessFromBeforeAfterQuotes(data)
  76. if delimiter != 0 {
  77. return delimiter
  78. }
  79. // Removes quoted values so we don't have columns with new lines in them
  80. text := removeQuotedString(string(data))
  81. // Make the text just be maxLines or less, ignoring truncated lines
  82. lines := strings.SplitN(text, "\n", maxLines+1) // Will contain at least one line, and if there are more than MaxLines, the last item holds the rest of the lines
  83. if len(lines) > maxLines {
  84. // If the length of lines is > maxLines we know we have the max number of lines, trim it to maxLines
  85. lines = lines[:maxLines]
  86. } else if len(lines) > 1 && len(data) >= guessSampleSize {
  87. // Even with data >= guessSampleSize, we don't have maxLines + 1 (no extra lines, must have really long lines)
  88. // thus the last line is probably have a truncated line. Drop the last line if len(lines) > 1
  89. lines = lines[:len(lines)-1]
  90. }
  91. // Put lines back together as a string
  92. text = strings.Join(lines, "\n")
  93. delimiters := []rune{',', '\t', ';', '|', '@'}
  94. validDelim := delimiters[0]
  95. validDelimColCount := 0
  96. for _, delim := range delimiters {
  97. csvReader := stdcsv.NewReader(strings.NewReader(text))
  98. csvReader.Comma = delim
  99. if rows, err := csvReader.ReadAll(); err == nil && len(rows) > 0 && len(rows[0]) > validDelimColCount {
  100. validDelim = delim
  101. validDelimColCount = len(rows[0])
  102. }
  103. }
  104. return validDelim
  105. }
  106. // FormatError converts csv errors into readable messages.
  107. func FormatError(err error, locale translation.Locale) (string, error) {
  108. if perr, ok := err.(*stdcsv.ParseError); ok {
  109. if perr.Err == stdcsv.ErrFieldCount {
  110. return locale.TrString("repo.error.csv.invalid_field_count", perr.Line), nil
  111. }
  112. return locale.TrString("repo.error.csv.unexpected", perr.Line, perr.Column), nil
  113. }
  114. return "", err
  115. }
  116. // Looks for possible delimiters right before or after (with spaces after the former) double quotes with closing quotes
  117. var beforeAfterQuotes = regexp.MustCompile(`([,@\t;|]{0,1}) *(?:"[^"]*")+([,@\t;|]{0,1})`)
  118. // guessFromBeforeAfterQuotes guesses the limiter by finding a double quote that has a valid delimiter before it and a closing quote,
  119. // or a double quote with a closing quote and a valid delimiter after it
  120. func guessFromBeforeAfterQuotes(data []byte) rune {
  121. rs := beforeAfterQuotes.FindStringSubmatch(string(data)) // returns first match, or nil if none
  122. if rs != nil {
  123. if rs[1] != "" {
  124. return rune(rs[1][0]) // delimiter found left of quoted string
  125. } else if rs[2] != "" {
  126. return rune(rs[2][0]) // delimiter found right of quoted string
  127. }
  128. }
  129. return 0 // no match found
  130. }