churn_analysis.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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. arr := [...]string{
  64. hercules.DependencyFileDiff,
  65. hercules.DependencyTreeChanges,
  66. hercules.DependencyBlobCache,
  67. hercules.DependencyTick,
  68. hercules.DependencyAuthor}
  69. return arr[:]
  70. }
  71. // ListConfigurationOptions tells the engine which parameters can be changed through the command
  72. // line.
  73. func (churn *ChurnAnalysis) ListConfigurationOptions() []hercules.ConfigurationOption {
  74. opts := [...]hercules.ConfigurationOption{{
  75. Name: ConfigChurnTrackPeople,
  76. Description: "Record detailed statistics per each developer.",
  77. Flag: "churn-people",
  78. Type: hercules.BoolConfigurationOption,
  79. Default: false},
  80. }
  81. return opts[:]
  82. }
  83. // Flag returns the command line switch which activates the analysis.
  84. func (churn *ChurnAnalysis) Flag() string {
  85. return "churn"
  86. }
  87. // Description returns the text which explains what the analysis is doing.
  88. func (churn *ChurnAnalysis) Description() string {
  89. return "Collects the daily numbers of inserted and removed lines."
  90. }
  91. // Configure applies the parameters specified in the command line. Map keys correspond to "Name".
  92. func (churn *ChurnAnalysis) Configure(facts map[string]interface{}) error {
  93. if l, exists := facts[hercules.ConfigLogger].(hercules.Logger); exists {
  94. churn.l = l
  95. }
  96. if val, exists := facts[ConfigChurnTrackPeople].(bool); exists {
  97. churn.TrackPeople = val
  98. }
  99. if churn.TrackPeople {
  100. churn.reversedPeopleDict = facts[hercules.FactIdentityDetectorReversedPeopleDict].([]string)
  101. }
  102. return nil
  103. }
  104. // Initialize resets the internal temporary data structures and prepares the object for Consume().
  105. func (churn *ChurnAnalysis) Initialize(repository *git.Repository) error {
  106. churn.l = hercules.NewLogger()
  107. churn.global = []editInfo{}
  108. churn.people = map[int][]editInfo{}
  109. churn.OneShotMergeProcessor.Initialize()
  110. return nil
  111. }
  112. func (churn *ChurnAnalysis) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  113. if !churn.ShouldConsumeCommit(deps) {
  114. return nil, nil
  115. }
  116. fileDiffs := deps[hercules.DependencyFileDiff].(map[string]hercules.FileDiffData)
  117. treeDiffs := deps[hercules.DependencyTreeChanges].(object.Changes)
  118. cache := deps[hercules.DependencyBlobCache].(map[plumbing.Hash]*hercules.CachedBlob)
  119. tick := deps[hercules.DependencyTick].(int)
  120. author := deps[hercules.DependencyAuthor].(int)
  121. for _, change := range treeDiffs {
  122. action, err := change.Action()
  123. if err != nil {
  124. return nil, err
  125. }
  126. added := 0
  127. removed := 0
  128. switch action {
  129. case merkletrie.Insert:
  130. added, _ = cache[change.To.TreeEntry.Hash].CountLines()
  131. case merkletrie.Delete:
  132. removed, _ = cache[change.From.TreeEntry.Hash].CountLines()
  133. case merkletrie.Modify:
  134. diffs := fileDiffs[change.To.Name]
  135. for _, edit := range diffs.Diffs {
  136. length := utf8.RuneCountInString(edit.Text)
  137. switch edit.Type {
  138. case diffmatchpatch.DiffEqual:
  139. continue
  140. case diffmatchpatch.DiffInsert:
  141. added += length
  142. case diffmatchpatch.DiffDelete:
  143. removed += length
  144. }
  145. }
  146. }
  147. if err != nil {
  148. return nil, err
  149. }
  150. ei := editInfo{Tick: tick, Added: added, Removed: removed}
  151. churn.global = append(churn.global, ei)
  152. if churn.TrackPeople {
  153. seq, exists := churn.people[author]
  154. if !exists {
  155. seq = []editInfo{}
  156. }
  157. seq = append(seq, ei)
  158. churn.people[author] = seq
  159. }
  160. }
  161. return nil, nil
  162. }
  163. // Fork clones the same item several times on branches.
  164. func (churn *ChurnAnalysis) Fork(n int) []hercules.PipelineItem {
  165. return hercules.ForkSamePipelineItem(churn, n)
  166. }
  167. func (churn *ChurnAnalysis) Finalize() interface{} {
  168. result := ChurnAnalysisResult{
  169. Global: editInfosToEdits(churn.global),
  170. People: map[string]Edits{},
  171. }
  172. if churn.TrackPeople {
  173. for key, val := range churn.people {
  174. result.People[churn.reversedPeopleDict[key]] = editInfosToEdits(val)
  175. }
  176. }
  177. return result
  178. }
  179. func (churn *ChurnAnalysis) Serialize(result interface{}, binary bool, writer io.Writer) error {
  180. burndownResult := result.(ChurnAnalysisResult)
  181. if binary {
  182. return churn.serializeBinary(&burndownResult, writer)
  183. }
  184. churn.serializeText(&burndownResult, writer)
  185. return nil
  186. }
  187. func (churn *ChurnAnalysis) serializeText(result *ChurnAnalysisResult, writer io.Writer) {
  188. fmt.Fprintln(writer, " global:")
  189. printEdits(result.Global, writer, 4)
  190. for key, val := range result.People {
  191. fmt.Fprintf(writer, " %s:\n", hercules.SafeYamlString(key))
  192. printEdits(val, writer, 4)
  193. }
  194. }
  195. func (churn *ChurnAnalysis) serializeBinary(result *ChurnAnalysisResult, writer io.Writer) error {
  196. message := ChurnAnalysisResultMessage{
  197. Global: editsToEditsMessage(result.Global),
  198. People: map[string]*EditsMessage{},
  199. }
  200. for key, val := range result.People {
  201. message.People[key] = editsToEditsMessage(val)
  202. }
  203. serialized, err := proto.Marshal(&message)
  204. if err != nil {
  205. return err
  206. }
  207. writer.Write(serialized)
  208. return nil
  209. }
  210. func editInfosToEdits(eis []editInfo) Edits {
  211. aux := map[int]*editInfo{}
  212. for _, ei := range eis {
  213. ptr := aux[ei.Tick]
  214. if ptr == nil {
  215. ptr = &editInfo{Tick: ei.Tick}
  216. }
  217. ptr.Added += ei.Added
  218. ptr.Removed += ei.Removed
  219. aux[ei.Tick] = ptr
  220. }
  221. seq := []int{}
  222. for key := range aux {
  223. seq = append(seq, key)
  224. }
  225. sort.Ints(seq)
  226. edits := Edits{
  227. Ticks: make([]int, len(seq)),
  228. Additions: make([]int, len(seq)),
  229. Removals: make([]int, len(seq)),
  230. }
  231. for i, tick := range seq {
  232. edits.Ticks[i] = tick
  233. edits.Additions[i] = aux[tick].Added
  234. edits.Removals[i] = aux[tick].Removed
  235. }
  236. return edits
  237. }
  238. func printEdits(edits Edits, writer io.Writer, indent int) {
  239. strIndent := strings.Repeat(" ", indent)
  240. printArray := func(arr []int, name string) {
  241. fmt.Fprintf(writer, "%s%s: [", strIndent, name)
  242. for i, v := range arr {
  243. if i < len(arr)-1 {
  244. fmt.Fprintf(writer, "%d, ", v)
  245. } else {
  246. fmt.Fprintf(writer, "%d]\n", v)
  247. }
  248. }
  249. }
  250. printArray(edits.Ticks, "ticks")
  251. printArray(edits.Additions, "additions")
  252. printArray(edits.Removals, "removals")
  253. }
  254. func editsToEditsMessage(edits Edits) *EditsMessage {
  255. message := &EditsMessage{
  256. Ticks: make([]uint32, len(edits.Ticks)),
  257. Additions: make([]uint32, len(edits.Additions)),
  258. Removals: make([]uint32, len(edits.Removals)),
  259. }
  260. copyInts := func(arr []int, where []uint32) {
  261. for i, v := range arr {
  262. where[i] = uint32(v)
  263. }
  264. }
  265. copyInts(edits.Ticks, message.Ticks)
  266. copyInts(edits.Additions, message.Additions)
  267. copyInts(edits.Removals, message.Removals)
  268. return message
  269. }
  270. func init() {
  271. hercules.Registry.Register(&ChurnAnalysis{})
  272. }