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.

charset.go 5.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. // Copyright 2014 The Gogs 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 charset
  5. import (
  6. "bytes"
  7. "fmt"
  8. "strings"
  9. "unicode/utf8"
  10. "code.gitea.io/gitea/modules/log"
  11. "code.gitea.io/gitea/modules/setting"
  12. "github.com/gogs/chardet"
  13. "golang.org/x/net/html/charset"
  14. "golang.org/x/text/transform"
  15. )
  16. // UTF8BOM is the utf-8 byte-order marker
  17. var UTF8BOM = []byte{'\xef', '\xbb', '\xbf'}
  18. // ToUTF8WithErr converts content to UTF8 encoding
  19. func ToUTF8WithErr(content []byte) (string, error) {
  20. charsetLabel, err := DetectEncoding(content)
  21. if err != nil {
  22. return "", err
  23. } else if charsetLabel == "UTF-8" {
  24. return string(RemoveBOMIfPresent(content)), nil
  25. }
  26. encoding, _ := charset.Lookup(charsetLabel)
  27. if encoding == nil {
  28. return string(content), fmt.Errorf("Unknown encoding: %s", charsetLabel)
  29. }
  30. // If there is an error, we concatenate the nicely decoded part and the
  31. // original left over. This way we won't lose much data.
  32. result, n, err := transform.Bytes(encoding.NewDecoder(), content)
  33. if err != nil {
  34. result = append(result, content[n:]...)
  35. }
  36. result = RemoveBOMIfPresent(result)
  37. return string(result), err
  38. }
  39. // ToUTF8WithFallback detects the encoding of content and coverts to UTF-8 if possible
  40. func ToUTF8WithFallback(content []byte) []byte {
  41. charsetLabel, err := DetectEncoding(content)
  42. if err != nil || charsetLabel == "UTF-8" {
  43. return RemoveBOMIfPresent(content)
  44. }
  45. encoding, _ := charset.Lookup(charsetLabel)
  46. if encoding == nil {
  47. return content
  48. }
  49. // If there is an error, we concatenate the nicely decoded part and the
  50. // original left over. This way we won't lose data.
  51. result, n, err := transform.Bytes(encoding.NewDecoder(), content)
  52. if err != nil {
  53. return append(result, content[n:]...)
  54. }
  55. return RemoveBOMIfPresent(result)
  56. }
  57. // ToUTF8 converts content to UTF8 encoding and ignore error
  58. func ToUTF8(content string) string {
  59. res, _ := ToUTF8WithErr([]byte(content))
  60. return res
  61. }
  62. // ToUTF8DropErrors makes sure the return string is valid utf-8; attempts conversion if possible
  63. func ToUTF8DropErrors(content []byte) []byte {
  64. charsetLabel, err := DetectEncoding(content)
  65. if err != nil || charsetLabel == "UTF-8" {
  66. return RemoveBOMIfPresent(content)
  67. }
  68. encoding, _ := charset.Lookup(charsetLabel)
  69. if encoding == nil {
  70. return content
  71. }
  72. // We ignore any non-decodable parts from the file.
  73. // Some parts might be lost
  74. var decoded []byte
  75. decoder := encoding.NewDecoder()
  76. idx := 0
  77. for {
  78. result, n, err := transform.Bytes(decoder, content[idx:])
  79. decoded = append(decoded, result...)
  80. if err == nil {
  81. break
  82. }
  83. decoded = append(decoded, ' ')
  84. idx = idx + n + 1
  85. if idx >= len(content) {
  86. break
  87. }
  88. }
  89. return RemoveBOMIfPresent(decoded)
  90. }
  91. // RemoveBOMIfPresent removes a UTF-8 BOM from a []byte
  92. func RemoveBOMIfPresent(content []byte) []byte {
  93. if len(content) > 2 && bytes.Equal(content[0:3], UTF8BOM) {
  94. return content[3:]
  95. }
  96. return content
  97. }
  98. // DetectEncoding detect the encoding of content
  99. func DetectEncoding(content []byte) (string, error) {
  100. if utf8.Valid(content) {
  101. log.Debug("Detected encoding: utf-8 (fast)")
  102. return "UTF-8", nil
  103. }
  104. textDetector := chardet.NewTextDetector()
  105. var detectContent []byte
  106. if len(content) < 1024 {
  107. // Check if original content is valid
  108. if _, err := textDetector.DetectBest(content); err != nil {
  109. return "", err
  110. }
  111. times := 1024 / len(content)
  112. detectContent = make([]byte, 0, times*len(content))
  113. for i := 0; i < times; i++ {
  114. detectContent = append(detectContent, content...)
  115. }
  116. } else {
  117. detectContent = content
  118. }
  119. // Now we can't use DetectBest or just results[0] because the result isn't stable - so we need a tie break
  120. results, err := textDetector.DetectAll(detectContent)
  121. if err != nil {
  122. if err == chardet.NotDetectedError && len(setting.Repository.AnsiCharset) > 0 {
  123. log.Debug("Using default AnsiCharset: %s", setting.Repository.AnsiCharset)
  124. return setting.Repository.AnsiCharset, nil
  125. }
  126. return "", err
  127. }
  128. topConfidence := results[0].Confidence
  129. topResult := results[0]
  130. priority, has := setting.Repository.DetectedCharsetScore[strings.ToLower(strings.TrimSpace(topResult.Charset))]
  131. for _, result := range results {
  132. // As results are sorted in confidence order - if we have a different confidence
  133. // we know it's less than the current confidence and can break out of the loop early
  134. if result.Confidence != topConfidence {
  135. break
  136. }
  137. // Otherwise check if this results is earlier in the DetectedCharsetOrder than our current top guesss
  138. resultPriority, resultHas := setting.Repository.DetectedCharsetScore[strings.ToLower(strings.TrimSpace(result.Charset))]
  139. if resultHas && (!has || resultPriority < priority) {
  140. topResult = result
  141. priority = resultPriority
  142. has = true
  143. }
  144. }
  145. // FIXME: to properly decouple this function the fallback ANSI charset should be passed as an argument
  146. if topResult.Charset != "UTF-8" && len(setting.Repository.AnsiCharset) > 0 {
  147. log.Debug("Using default AnsiCharset: %s", setting.Repository.AnsiCharset)
  148. return setting.Repository.AnsiCharset, err
  149. }
  150. log.Debug("Detected encoding: %s", topResult.Charset)
  151. return topResult.Charset, err
  152. }