churn_analysis.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "sort"
  6. "strings"
  7. "unicode/utf8"
  8. "github.com/gogo/protobuf/proto"
  9. "github.com/sergi/go-diff/diffmatchpatch"
  10. "gopkg.in/src-d/go-git.v4"
  11. "gopkg.in/src-d/go-git.v4/plumbing"
  12. "gopkg.in/src-d/go-git.v4/plumbing/object"
  13. "gopkg.in/src-d/go-git.v4/utils/merkletrie"
  14. "gopkg.in/src-d/hercules.v10"
  15. )
  16. // ChurnAnalysis contains the intermediate state which is mutated by Consume(). It should implement
  17. // hercules.LeafPipelineItem.
  18. type ChurnAnalysis struct {
  19. // No special merge logic is required
  20. hercules.NoopMerger
  21. // Process each merge only once
  22. hercules.OneShotMergeProcessor
  23. TrackPeople bool
  24. global []editInfo
  25. people map[int][]editInfo
  26. // references IdentityDetector.ReversedPeopleDict
  27. reversedPeopleDict []string
  28. l hercules.Logger
  29. }
  30. type editInfo struct {
  31. Tick int
  32. Added int
  33. Removed int
  34. }
  35. // ChurnAnalysisResult is returned by Finalize() and represents the analysis result.
  36. type ChurnAnalysisResult struct {
  37. Global Edits
  38. People map[string]Edits
  39. }
  40. type Edits struct {
  41. Ticks []int
  42. Additions []int
  43. Removals []int
  44. }
  45. const (
  46. ConfigChurnTrackPeople = "Churn.TrackPeople"
  47. )
  48. // Analysis' name in the graph is usually the same as the type's name, however, does not have to.
  49. func (churn *ChurnAnalysis) Name() string {
  50. return "ChurnAnalysis"
  51. }
  52. // LeafPipelineItem-s normally do not act as intermediate nodes and thus we return an empty slice.
  53. func (churn *ChurnAnalysis) Provides() []string {
  54. return []string{}
  55. }
  56. // Requires returns the list of dependencies which must be supplied in Consume().
  57. // file_diff - line diff for each commit change
  58. // changes - list of changed files for each commit
  59. // blob_cache - set of blobs affected by each commit
  60. // tick - number of ticks since start for each commit
  61. // author - author of the commit
  62. func (churn *ChurnAnalysis) Requires() []string {
  63. return []string{
  64. hercules.DependencyFileDiff,
  65. hercules.DependencyTreeChanges,
  66. hercules.DependencyBlobCache,
  67. hercules.DependencyTick,
  68. hercules.DependencyAuthor}
  69. }
  70. // ListConfigurationOptions tells the engine which parameters can be changed through the command
  71. // line.
  72. func (churn *ChurnAnalysis) ListConfigurationOptions() []hercules.ConfigurationOption {
  73. opts := [...]hercules.ConfigurationOption{{
  74. Name: ConfigChurnTrackPeople,
  75. Description: "Record detailed statistics per each developer.",
  76. Flag: "churn-people",
  77. Type: hercules.BoolConfigurationOption,
  78. Default: false},
  79. }
  80. return opts[:]
  81. }
  82. // Flag returns the command line switch which activates the analysis.
  83. func (churn *ChurnAnalysis) Flag() string {
  84. return "churn"
  85. }
  86. // Description returns the text which explains what the analysis is doing.
  87. func (churn *ChurnAnalysis) Description() string {
  88. return "Collects the daily numbers of inserted and removed lines."
  89. }
  90. // Configure applies the parameters specified in the command line. Map keys correspond to "Name".
  91. func (churn *ChurnAnalysis) Configure(facts map[string]interface{}) error {
  92. if l, exists := facts[hercules.ConfigLogger].(hercules.Logger); exists {
  93. churn.l = l
  94. }
  95. if val, exists := facts[ConfigChurnTrackPeople].(bool); exists {
  96. churn.TrackPeople = val
  97. }
  98. if churn.TrackPeople {
  99. churn.reversedPeopleDict = facts[hercules.FactIdentityDetectorReversedPeopleDict].([]string)
  100. }
  101. return nil
  102. }
  103. // Initialize resets the internal temporary data structures and prepares the object for Consume().
  104. func (churn *ChurnAnalysis) Initialize(repository *git.Repository) error {
  105. churn.l = hercules.NewLogger()
  106. churn.global = []editInfo{}
  107. churn.people = map[int][]editInfo{}
  108. churn.OneShotMergeProcessor.Initialize()
  109. return nil
  110. }
  111. func (churn *ChurnAnalysis) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  112. if !churn.ShouldConsumeCommit(deps) {
  113. return nil, nil
  114. }
  115. fileDiffs := deps[hercules.DependencyFileDiff].(map[string]hercules.FileDiffData)
  116. treeDiffs := deps[hercules.DependencyTreeChanges].(object.Changes)
  117. cache := deps[hercules.DependencyBlobCache].(map[plumbing.Hash]*hercules.CachedBlob)
  118. tick := deps[hercules.DependencyTick].(int)
  119. author := deps[hercules.DependencyAuthor].(int)
  120. for _, change := range treeDiffs {
  121. action, err := change.Action()
  122. if err != nil {
  123. return nil, err
  124. }
  125. added := 0
  126. removed := 0
  127. switch action {
  128. case merkletrie.Insert:
  129. added, _ = cache[change.To.TreeEntry.Hash].CountLines()
  130. case merkletrie.Delete:
  131. removed, _ = cache[change.From.TreeEntry.Hash].CountLines()
  132. case merkletrie.Modify:
  133. diffs := fileDiffs[change.To.Name]
  134. for _, edit := range diffs.Diffs {
  135. length := utf8.RuneCountInString(edit.Text)
  136. switch edit.Type {
  137. case diffmatchpatch.DiffEqual:
  138. continue
  139. case diffmatchpatch.DiffInsert:
  140. added += length
  141. case diffmatchpatch.DiffDelete:
  142. removed += length
  143. }
  144. }
  145. }
  146. if err != nil {
  147. return nil, err
  148. }
  149. ei := editInfo{Tick: tick, Added: added, Removed: removed}
  150. churn.global = append(churn.global, ei)
  151. if churn.TrackPeople {
  152. seq, exists := churn.people[author]
  153. if !exists {
  154. seq = []editInfo{}
  155. }
  156. seq = append(seq, ei)
  157. churn.people[author] = seq
  158. }
  159. }
  160. return nil, nil
  161. }
  162. // Fork clones the same item several times on branches.
  163. func (churn *ChurnAnalysis) Fork(n int) []hercules.PipelineItem {
  164. return hercules.ForkSamePipelineItem(churn, n)
  165. }
  166. func (churn *ChurnAnalysis) Finalize() interface{} {
  167. result := ChurnAnalysisResult{
  168. Global: editInfosToEdits(churn.global),
  169. People: map[string]Edits{},
  170. }
  171. if churn.TrackPeople {
  172. for key, val := range churn.people {
  173. result.People[churn.reversedPeopleDict[key]] = editInfosToEdits(val)
  174. }
  175. }
  176. return result
  177. }
  178. func (churn *ChurnAnalysis) Serialize(result interface{}, binary bool, writer io.Writer) error {
  179. burndownResult := result.(ChurnAnalysisResult)
  180. if binary {
  181. return churn.serializeBinary(&burndownResult, writer)
  182. }
  183. churn.serializeText(&burndownResult, writer)
  184. return nil
  185. }
  186. func (churn *ChurnAnalysis) serializeText(result *ChurnAnalysisResult, writer io.Writer) {
  187. fmt.Fprintln(writer, " global:")
  188. printEdits(result.Global, writer, 4)
  189. for key, val := range result.People {
  190. fmt.Fprintf(writer, " %s:\n", hercules.SafeYamlString(key))
  191. printEdits(val, writer, 4)
  192. }
  193. }
  194. func (churn *ChurnAnalysis) serializeBinary(result *ChurnAnalysisResult, writer io.Writer) error {
  195. message := ChurnAnalysisResultMessage{
  196. Global: editsToEditsMessage(result.Global),
  197. People: map[string]*EditsMessage{},
  198. }
  199. for key, val := range result.People {
  200. message.People[key] = editsToEditsMessage(val)
  201. }
  202. serialized, err := proto.Marshal(&message)
  203. if err != nil {
  204. return err
  205. }
  206. writer.Write(serialized)
  207. return nil
  208. }
  209. func editInfosToEdits(eis []editInfo) Edits {
  210. aux := map[int]*editInfo{}
  211. for _, ei := range eis {
  212. ptr := aux[ei.Tick]
  213. if ptr == nil {
  214. ptr = &editInfo{Tick: ei.Tick}
  215. }
  216. ptr.Added += ei.Added
  217. ptr.Removed += ei.Removed
  218. aux[ei.Tick] = ptr
  219. }
  220. seq := []int{}
  221. for key := range aux {
  222. seq = append(seq, key)
  223. }
  224. sort.Ints(seq)
  225. edits := Edits{
  226. Ticks: make([]int, len(seq)),
  227. Additions: make([]int, len(seq)),
  228. Removals: make([]int, len(seq)),
  229. }
  230. for i, tick := range seq {
  231. edits.Ticks[i] = tick
  232. edits.Additions[i] = aux[tick].Added
  233. edits.Removals[i] = aux[tick].Removed
  234. }
  235. return edits
  236. }
  237. func printEdits(edits Edits, writer io.Writer, indent int) {
  238. strIndent := strings.Repeat(" ", indent)
  239. printArray := func(arr []int, name string) {
  240. fmt.Fprintf(writer, "%s%s: [", strIndent, name)
  241. for i, v := range arr {
  242. if i < len(arr)-1 {
  243. fmt.Fprintf(writer, "%d, ", v)
  244. } else {
  245. fmt.Fprintf(writer, "%d]\n", v)
  246. }
  247. }
  248. }
  249. printArray(edits.Ticks, "ticks")
  250. printArray(edits.Additions, "additions")
  251. printArray(edits.Removals, "removals")
  252. }
  253. func editsToEditsMessage(edits Edits) *EditsMessage {
  254. message := &EditsMessage{
  255. Ticks: make([]uint32, len(edits.Ticks)),
  256. Additions: make([]uint32, len(edits.Additions)),
  257. Removals: make([]uint32, len(edits.Removals)),
  258. }
  259. copyInts := func(arr []int, where []uint32) {
  260. for i, v := range arr {
  261. where[i] = uint32(v)
  262. }
  263. }
  264. copyInts(edits.Ticks, message.Ticks)
  265. copyInts(edits.Additions, message.Additions)
  266. copyInts(edits.Removals, message.Removals)
  267. return message
  268. }
  269. func init() {
  270. hercules.Registry.Register(&ChurnAnalysis{})
  271. }