gitea源码

language_stats_nogogit.go 5.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. // Copyright 2020 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. //go:build !gogit
  4. package languagestats
  5. import (
  6. "bytes"
  7. "io"
  8. "code.gitea.io/gitea/modules/analyze"
  9. "code.gitea.io/gitea/modules/git"
  10. "code.gitea.io/gitea/modules/git/attribute"
  11. "code.gitea.io/gitea/modules/log"
  12. "code.gitea.io/gitea/modules/optional"
  13. "github.com/go-enry/go-enry/v2"
  14. )
  15. // GetLanguageStats calculates language stats for git repository at specified commit
  16. func GetLanguageStats(repo *git.Repository, commitID string) (map[string]int64, error) {
  17. // We will feed the commit IDs in order into cat-file --batch, followed by blobs as necessary.
  18. // so let's create a batch stdin and stdout
  19. batchStdinWriter, batchReader, cancel, err := repo.CatFileBatch(repo.Ctx)
  20. if err != nil {
  21. return nil, err
  22. }
  23. defer cancel()
  24. writeID := func(id string) error {
  25. _, err := batchStdinWriter.Write([]byte(id + "\n"))
  26. return err
  27. }
  28. if err := writeID(commitID); err != nil {
  29. return nil, err
  30. }
  31. shaBytes, typ, size, err := git.ReadBatchLine(batchReader)
  32. if typ != "commit" {
  33. log.Debug("Unable to get commit for: %s. Err: %v", commitID, err)
  34. return nil, git.ErrNotExist{ID: commitID}
  35. }
  36. sha, err := git.NewIDFromString(string(shaBytes))
  37. if err != nil {
  38. log.Debug("Unable to get commit for: %s. Err: %v", commitID, err)
  39. return nil, git.ErrNotExist{ID: commitID}
  40. }
  41. commit, err := git.CommitFromReader(repo, sha, io.LimitReader(batchReader, size))
  42. if err != nil {
  43. log.Debug("Unable to get commit for: %s. Err: %v", commitID, err)
  44. return nil, err
  45. }
  46. if _, err = batchReader.Discard(1); err != nil {
  47. return nil, err
  48. }
  49. tree := commit.Tree
  50. entries, err := tree.ListEntriesRecursiveWithSize()
  51. if err != nil {
  52. return nil, err
  53. }
  54. checker, err := attribute.NewBatchChecker(repo, commitID, attribute.LinguistAttributes)
  55. if err != nil {
  56. return nil, err
  57. }
  58. defer checker.Close()
  59. contentBuf := bytes.Buffer{}
  60. var content []byte
  61. // sizes contains the current calculated size of all files by language
  62. sizes := make(map[string]int64)
  63. // by default we will only count the sizes of programming languages or markup languages
  64. // unless they are explicitly set using linguist-language
  65. includedLanguage := map[string]bool{}
  66. // or if there's only one language in the repository
  67. firstExcludedLanguage := ""
  68. firstExcludedLanguageSize := int64(0)
  69. for _, f := range entries {
  70. select {
  71. case <-repo.Ctx.Done():
  72. return sizes, repo.Ctx.Err()
  73. default:
  74. }
  75. contentBuf.Reset()
  76. content = contentBuf.Bytes()
  77. if f.Size() == 0 {
  78. continue
  79. }
  80. isVendored := optional.None[bool]()
  81. isDocumentation := optional.None[bool]()
  82. isDetectable := optional.None[bool]()
  83. attrs, err := checker.CheckPath(f.Name())
  84. attrLinguistGenerated := optional.None[bool]()
  85. if err == nil {
  86. if isVendored = attrs.GetVendored(); isVendored.ValueOrDefault(false) {
  87. continue
  88. }
  89. if attrLinguistGenerated = attrs.GetGenerated(); attrLinguistGenerated.ValueOrDefault(false) {
  90. continue
  91. }
  92. if isDocumentation = attrs.GetDocumentation(); isDocumentation.ValueOrDefault(false) {
  93. continue
  94. }
  95. if isDetectable = attrs.GetDetectable(); !isDetectable.ValueOrDefault(true) {
  96. continue
  97. }
  98. if hasLanguage := attrs.GetLanguage(); hasLanguage.Value() != "" {
  99. language := hasLanguage.Value()
  100. // group languages, such as Pug -> HTML; SCSS -> CSS
  101. group := enry.GetLanguageGroup(language)
  102. if len(group) != 0 {
  103. language = group
  104. }
  105. // this language will always be added to the size
  106. sizes[language] += f.Size()
  107. continue
  108. }
  109. }
  110. if (!isVendored.Has() && analyze.IsVendor(f.Name())) ||
  111. enry.IsDotFile(f.Name()) ||
  112. (!isDocumentation.Has() && enry.IsDocumentation(f.Name())) ||
  113. enry.IsConfiguration(f.Name()) {
  114. continue
  115. }
  116. // If content can not be read or file is too big just do detection by filename
  117. if f.Size() <= bigFileSize {
  118. if err := writeID(f.ID.String()); err != nil {
  119. return nil, err
  120. }
  121. _, _, size, err := git.ReadBatchLine(batchReader)
  122. if err != nil {
  123. log.Debug("Error reading blob: %s Err: %v", f.ID.String(), err)
  124. return nil, err
  125. }
  126. sizeToRead := size
  127. discard := int64(1)
  128. if size > fileSizeLimit {
  129. sizeToRead = fileSizeLimit
  130. discard = size - fileSizeLimit + 1
  131. }
  132. _, err = contentBuf.ReadFrom(io.LimitReader(batchReader, sizeToRead))
  133. if err != nil {
  134. return nil, err
  135. }
  136. content = contentBuf.Bytes()
  137. if err := git.DiscardFull(batchReader, discard); err != nil {
  138. return nil, err
  139. }
  140. }
  141. // if "generated" attribute is set, use it, otherwise use enry.IsGenerated to guess
  142. var isGenerated bool
  143. if attrLinguistGenerated.Has() {
  144. isGenerated = attrLinguistGenerated.Value()
  145. } else {
  146. isGenerated = enry.IsGenerated(f.Name(), content)
  147. }
  148. if isGenerated {
  149. continue
  150. }
  151. // FIXME: Why can't we split this and the IsGenerated tests to avoid reading the blob unless absolutely necessary?
  152. // - eg. do the all the detection tests using filename first before reading content.
  153. language := analyze.GetCodeLanguage(f.Name(), content)
  154. if language == "" {
  155. continue
  156. }
  157. // group languages, such as Pug -> HTML; SCSS -> CSS
  158. group := enry.GetLanguageGroup(language)
  159. if group != "" {
  160. language = group
  161. }
  162. included, checked := includedLanguage[language]
  163. if !checked {
  164. langType := enry.GetLanguageType(language)
  165. included = langType == enry.Programming || langType == enry.Markup
  166. includedLanguage[language] = included
  167. }
  168. if included || isDetectable.ValueOrDefault(false) {
  169. sizes[language] += f.Size()
  170. } else if len(sizes) == 0 && (firstExcludedLanguage == "" || firstExcludedLanguage == language) {
  171. firstExcludedLanguage = language
  172. firstExcludedLanguageSize += f.Size()
  173. }
  174. }
  175. // If there are no included languages add the first excluded language
  176. if len(sizes) == 0 && firstExcludedLanguage != "" {
  177. sizes[firstExcludedLanguage] = firstExcludedLanguageSize
  178. }
  179. return mergeLanguageStats(sizes), nil
  180. }