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.

csv.go 5.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  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/filepath"
  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. return rd
  29. }
  30. // CreateReaderAndDetermineDelimiter tries to guess the field delimiter from the content and creates a csv.Reader.
  31. // Reads at most guessSampleSize bytes.
  32. func CreateReaderAndDetermineDelimiter(ctx *markup.RenderContext, rd io.Reader) (*stdcsv.Reader, error) {
  33. data := make([]byte, guessSampleSize)
  34. size, err := util.ReadAtMost(rd, data)
  35. if err != nil {
  36. return nil, err
  37. }
  38. return CreateReader(
  39. io.MultiReader(bytes.NewReader(data[:size]), rd),
  40. determineDelimiter(ctx, data[:size]),
  41. ), nil
  42. }
  43. // determineDelimiter takes a RenderContext and if it isn't nil and the Filename has an extension that specifies the delimiter,
  44. // it is used as the delimiter. Otherwise we call guessDelimiter with the data passed
  45. func determineDelimiter(ctx *markup.RenderContext, data []byte) rune {
  46. extension := ".csv"
  47. if ctx != nil {
  48. extension = strings.ToLower(filepath.Ext(ctx.RelativePath))
  49. }
  50. var delimiter rune
  51. switch extension {
  52. case ".tsv":
  53. delimiter = '\t'
  54. case ".psv":
  55. delimiter = '|'
  56. default:
  57. delimiter = guessDelimiter(data)
  58. }
  59. return delimiter
  60. }
  61. // quoteRegexp follows the RFC-4180 CSV standard for when double-quotes are used to enclose fields, then a double-quote appearing inside a
  62. // field must be escaped by preceding it with another double quote. https://www.ietf.org/rfc/rfc4180.txt
  63. // This finds all quoted strings that have escaped quotes.
  64. var quoteRegexp = regexp.MustCompile(`"[^"]*"`)
  65. // removeQuotedStrings uses the quoteRegexp to remove all quoted strings so that we can reliably have each row on one line
  66. // (quoted strings often have new lines within the string)
  67. func removeQuotedString(text string) string {
  68. return quoteRegexp.ReplaceAllLiteralString(text, "")
  69. }
  70. // 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.
  71. // If more than one delimiter passes, the delimiter that results in the most columns is returned.
  72. func guessDelimiter(data []byte) rune {
  73. delimiter := guessFromBeforeAfterQuotes(data)
  74. if delimiter != 0 {
  75. return delimiter
  76. }
  77. // Removes quoted values so we don't have columns with new lines in them
  78. text := removeQuotedString(string(data))
  79. // Make the text just be maxLines or less, ignoring truncated lines
  80. 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
  81. if len(lines) > maxLines {
  82. // If the length of lines is > maxLines we know we have the max number of lines, trim it to maxLines
  83. lines = lines[:maxLines]
  84. } else if len(lines) > 1 && len(data) >= guessSampleSize {
  85. // Even with data >= guessSampleSize, we don't have maxLines + 1 (no extra lines, must have really long lines)
  86. // thus the last line is probably have a truncated line. Drop the last line if len(lines) > 1
  87. lines = lines[:len(lines)-1]
  88. }
  89. // Put lines back together as a string
  90. text = strings.Join(lines, "\n")
  91. delimiters := []rune{',', '\t', ';', '|', '@'}
  92. validDelim := delimiters[0]
  93. validDelimColCount := 0
  94. for _, delim := range delimiters {
  95. csvReader := stdcsv.NewReader(strings.NewReader(text))
  96. csvReader.Comma = delim
  97. if rows, err := csvReader.ReadAll(); err == nil && len(rows) > 0 && len(rows[0]) > validDelimColCount {
  98. validDelim = delim
  99. validDelimColCount = len(rows[0])
  100. }
  101. }
  102. return validDelim
  103. }
  104. // FormatError converts csv errors into readable messages.
  105. func FormatError(err error, locale translation.Locale) (string, error) {
  106. if perr, ok := err.(*stdcsv.ParseError); ok {
  107. if perr.Err == stdcsv.ErrFieldCount {
  108. return locale.Tr("repo.error.csv.invalid_field_count", perr.Line), nil
  109. }
  110. return locale.Tr("repo.error.csv.unexpected", perr.Line, perr.Column), nil
  111. }
  112. return "", err
  113. }
  114. // Looks for possible delimiters right before or after (with spaces after the former) double quotes with closing quotes
  115. var beforeAfterQuotes = regexp.MustCompile(`([,@\t;|]{0,1}) *(?:"[^"]*")+([,@\t;|]{0,1})`)
  116. // guessFromBeforeAfterQuotes guesses the limiter by finding a double quote that has a valid delimiter before it and a closing quote,
  117. // or a double quote with a closing quote and a valid delimiter after it
  118. func guessFromBeforeAfterQuotes(data []byte) rune {
  119. rs := beforeAfterQuotes.FindStringSubmatch(string(data)) // returns first match, or nil if none
  120. if rs != nil {
  121. if rs[1] != "" {
  122. return rune(rs[1][0]) // delimiter found left of quoted string
  123. } else if rs[2] != "" {
  124. return rune(rs[2][0]) // delimiter found right of quoted string
  125. }
  126. }
  127. return 0 // no match found
  128. }