commits.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. package leaves
  2. import (
  3. "fmt"
  4. "io"
  5. "github.com/gogo/protobuf/proto"
  6. git "gopkg.in/src-d/go-git.v4"
  7. "gopkg.in/src-d/go-git.v4/plumbing"
  8. "gopkg.in/src-d/go-git.v4/plumbing/object"
  9. "gopkg.in/src-d/hercules.v10/internal/core"
  10. "gopkg.in/src-d/hercules.v10/internal/pb"
  11. items "gopkg.in/src-d/hercules.v10/internal/plumbing"
  12. "gopkg.in/src-d/hercules.v10/internal/plumbing/identity"
  13. "gopkg.in/src-d/hercules.v10/internal/yaml"
  14. )
  15. // CommitsAnalysis extracts statistics for each commit
  16. type CommitsAnalysis struct {
  17. core.NoopMerger
  18. // commits stores statistics for each commit
  19. commits []*CommitStat
  20. // reversedPeopleDict references IdentityDetector.ReversedPeopleDict
  21. reversedPeopleDict []string
  22. l core.Logger
  23. }
  24. // CommitsResult is returned by CommitsAnalysis.Finalize() and carries the statistics
  25. // per commit.
  26. type CommitsResult struct {
  27. Commits []*CommitStat
  28. // reversedPeopleDict references IdentityDetector.ReversedPeopleDict
  29. reversedPeopleDict []string
  30. }
  31. // FileStat is the statistics for a file in a commit
  32. type FileStat struct {
  33. Name string
  34. Language string
  35. items.LineStats
  36. }
  37. // CommitStat is the statistics for a commit
  38. type CommitStat struct {
  39. Hash string
  40. When int64
  41. Author int
  42. Files []FileStat
  43. }
  44. // Name of this PipelineItem. Uniquely identifies the type, used for mapping keys, etc.
  45. func (ca *CommitsAnalysis) Name() string {
  46. return "CommitsStat"
  47. }
  48. // Provides returns the list of names of entities which are produced by this PipelineItem.
  49. // Each produced entity will be inserted into `deps` of dependent Consume()-s according
  50. // to this list. Also used by core.Registry to build the global map of providers.
  51. func (ca *CommitsAnalysis) Provides() []string {
  52. return []string{}
  53. }
  54. // Requires returns the list of names of entities which are needed by this PipelineItem.
  55. // Each requested entity will be inserted into `deps` of Consume(). In turn, those
  56. // entities are Provides() upstream.
  57. func (ca *CommitsAnalysis) Requires() []string {
  58. arr := [...]string{
  59. identity.DependencyAuthor, items.DependencyLanguages, items.DependencyLineStats}
  60. return arr[:]
  61. }
  62. // ListConfigurationOptions returns the list of changeable public properties of this PipelineItem.
  63. func (ca *CommitsAnalysis) ListConfigurationOptions() []core.ConfigurationOption {
  64. return nil
  65. }
  66. // Configure sets the properties previously published by ListConfigurationOptions().
  67. func (ca *CommitsAnalysis) Configure(facts map[string]interface{}) error {
  68. if l, exists := facts[core.ConfigLogger].(core.Logger); exists {
  69. ca.l = l
  70. }
  71. if val, exists := facts[identity.FactIdentityDetectorReversedPeopleDict].([]string); exists {
  72. ca.reversedPeopleDict = val
  73. }
  74. return nil
  75. }
  76. // Flag for the command line switch which enables this analysis.
  77. func (ca *CommitsAnalysis) Flag() string {
  78. return "commits-stat"
  79. }
  80. // Description returns the text which explains what the analysis is doing.
  81. func (ca *CommitsAnalysis) Description() string {
  82. return "Extracts statistics for each commit. Identical to `git log --stat`"
  83. }
  84. // Initialize resets the temporary caches and prepares this PipelineItem for a series of Consume()
  85. // calls. The repository which is going to be analysed is supplied as an argument.
  86. func (ca *CommitsAnalysis) Initialize(repository *git.Repository) error {
  87. ca.l = core.NewLogger()
  88. return nil
  89. }
  90. // Consume runs this PipelineItem on the next commit data.
  91. // `deps` contain all the results from upstream PipelineItem-s as requested by Requires().
  92. // Additionally, DependencyCommit is always present there and represents the analysed *object.Commit.
  93. // This function returns the mapping with analysis results. The keys must be the same as
  94. // in Provides(). If there was an error, nil is returned.
  95. func (ca *CommitsAnalysis) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  96. if deps[core.DependencyIsMerge].(bool) {
  97. return nil, nil
  98. }
  99. commit := deps[core.DependencyCommit].(*object.Commit)
  100. author := deps[identity.DependencyAuthor].(int)
  101. lineStats := deps[items.DependencyLineStats].(map[object.ChangeEntry]items.LineStats)
  102. langs := deps[items.DependencyLanguages].(map[plumbing.Hash]string)
  103. cs := CommitStat{
  104. Hash: commit.Hash.String(),
  105. When: commit.Author.When.Unix(),
  106. Author: author,
  107. }
  108. for entry, stats := range lineStats {
  109. cs.Files = append(cs.Files, FileStat{
  110. Name: entry.Name,
  111. Language: langs[entry.TreeEntry.Hash],
  112. LineStats: stats,
  113. })
  114. }
  115. ca.commits = append(ca.commits, &cs)
  116. return nil, nil
  117. }
  118. // Finalize returns the result of the analysis. Further Consume() calls are not expected.
  119. func (ca *CommitsAnalysis) Finalize() interface{} {
  120. return CommitsResult{
  121. Commits: ca.commits,
  122. reversedPeopleDict: ca.reversedPeopleDict,
  123. }
  124. }
  125. // Fork clones this pipeline item.
  126. func (ca *CommitsAnalysis) Fork(n int) []core.PipelineItem {
  127. return core.ForkSamePipelineItem(ca, n)
  128. }
  129. // Serialize converts the analysis result as returned by Finalize() to text or bytes.
  130. // The text format is YAML and the bytes format is Protocol Buffers.
  131. func (ca *CommitsAnalysis) Serialize(result interface{}, binary bool, writer io.Writer) error {
  132. commitsResult := result.(CommitsResult)
  133. if binary {
  134. return ca.serializeBinary(&commitsResult, writer)
  135. }
  136. ca.serializeText(&commitsResult, writer)
  137. return nil
  138. }
  139. func (ca *CommitsAnalysis) serializeText(result *CommitsResult, writer io.Writer) {
  140. fmt.Fprintln(writer, " commits:")
  141. for _, c := range result.Commits {
  142. fmt.Fprintf(writer, " - hash: %s\n", c.Hash)
  143. fmt.Fprintf(writer, " when: %d\n", c.When)
  144. fmt.Fprintf(writer, " author: %d\n", c.Author)
  145. fmt.Fprintf(writer, " files:\n")
  146. for _, f := range c.Files {
  147. fmt.Fprintf(writer, " - name: %s\n", f.Name)
  148. fmt.Fprintf(writer, " language: %s\n", f.Language)
  149. fmt.Fprintf(writer, " stat: [%d, %d, %d]\n", f.Added, f.Changed, f.Removed)
  150. }
  151. }
  152. fmt.Fprintln(writer, " people:")
  153. for _, person := range result.reversedPeopleDict {
  154. fmt.Fprintf(writer, " - %s\n", yaml.SafeString(person))
  155. }
  156. }
  157. func (ca *CommitsAnalysis) serializeBinary(result *CommitsResult, writer io.Writer) error {
  158. message := pb.CommitsAnalysisResults{}
  159. message.AuthorIndex = result.reversedPeopleDict
  160. message.Commits = make([]*pb.Commit, len(result.Commits))
  161. for i, c := range result.Commits {
  162. files := make([]*pb.CommitFile, len(c.Files))
  163. for i, f := range c.Files {
  164. files[i] = &pb.CommitFile{
  165. Name: f.Name,
  166. Language: f.Language,
  167. Stats: &pb.LineStats{
  168. Added: int32(f.LineStats.Added),
  169. Changed: int32(f.LineStats.Changed),
  170. Removed: int32(f.LineStats.Removed),
  171. },
  172. }
  173. }
  174. message.Commits[i] = &pb.Commit{
  175. Hash: c.Hash,
  176. WhenUnixTime: c.When,
  177. Author: int32(c.Author),
  178. Files: files,
  179. }
  180. }
  181. serialized, err := proto.Marshal(&message)
  182. if err != nil {
  183. return err
  184. }
  185. _, err = writer.Write(serialized)
  186. return err
  187. }
  188. func init() {
  189. core.Registry.Register(&CommitsAnalysis{})
  190. }