churn_analysis.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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.v4"
  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. }
  29. type editInfo struct {
  30. Day int
  31. Added int
  32. Removed int
  33. }
  34. // ChurnAnalysisResult is returned by Finalize() and represents the analysis result.
  35. type ChurnAnalysisResult struct {
  36. Global Edits
  37. People map[string]Edits
  38. }
  39. type Edits struct {
  40. Days []int
  41. Additions []int
  42. Removals []int
  43. }
  44. const (
  45. ConfigChurnTrackPeople = "Churn.TrackPeople"
  46. )
  47. // Analysis' name in the graph is usually the same as the type's name, however, does not have to.
  48. func (churn *ChurnAnalysis) Name() string {
  49. return "ChurnAnalysis"
  50. }
  51. // LeafPipelineItem-s normally do not act as intermediate nodes and thus we return an empty slice.
  52. func (churn *ChurnAnalysis) Provides() []string {
  53. return []string{}
  54. }
  55. // Requires returns the list of dependencies which must be supplied in Consume().
  56. // file_diff - line diff for each commit change
  57. // changes - list of changed files for each commit
  58. // blob_cache - set of blobs affected by each commit
  59. // day - number of days since start for each commit
  60. // author - author of the commit
  61. func (churn *ChurnAnalysis) Requires() []string {
  62. arr := [...]string{
  63. hercules.DependencyFileDiff,
  64. hercules.DependencyTreeChanges,
  65. hercules.DependencyBlobCache,
  66. hercules.DependencyDay,
  67. hercules.DependencyAuthor}
  68. return arr[:]
  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{}) {
  92. if val, exists := facts[ConfigChurnTrackPeople].(bool); exists {
  93. churn.TrackPeople = val
  94. }
  95. if churn.TrackPeople {
  96. churn.reversedPeopleDict = facts[hercules.FactIdentityDetectorReversedPeopleDict].([]string)
  97. }
  98. }
  99. // Initialize resets the internal temporary data structures and prepares the object for Consume().
  100. func (churn *ChurnAnalysis) Initialize(repository *git.Repository) {
  101. churn.global = []editInfo{}
  102. churn.people = map[int][]editInfo{}
  103. churn.OneShotMergeProcessor.Initialize()
  104. }
  105. func (churn *ChurnAnalysis) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  106. if !churn.ShouldConsumeCommit(deps) {
  107. return nil, nil
  108. }
  109. fileDiffs := deps[hercules.DependencyFileDiff].(map[string]hercules.FileDiffData)
  110. treeDiffs := deps[hercules.DependencyTreeChanges].(object.Changes)
  111. cache := deps[hercules.DependencyBlobCache].(map[plumbing.Hash]*hercules.CachedBlob)
  112. day := deps[hercules.DependencyDay].(int)
  113. author := deps[hercules.DependencyAuthor].(int)
  114. for _, change := range treeDiffs {
  115. action, err := change.Action()
  116. if err != nil {
  117. return nil, err
  118. }
  119. added := 0
  120. removed := 0
  121. switch action {
  122. case merkletrie.Insert:
  123. added, _ = cache[change.To.TreeEntry.Hash].CountLines()
  124. case merkletrie.Delete:
  125. removed, _ = cache[change.From.TreeEntry.Hash].CountLines()
  126. case merkletrie.Modify:
  127. diffs := fileDiffs[change.To.Name]
  128. for _, edit := range diffs.Diffs {
  129. length := utf8.RuneCountInString(edit.Text)
  130. switch edit.Type {
  131. case diffmatchpatch.DiffEqual:
  132. continue
  133. case diffmatchpatch.DiffInsert:
  134. added += length
  135. case diffmatchpatch.DiffDelete:
  136. removed += length
  137. }
  138. }
  139. }
  140. if err != nil {
  141. return nil, err
  142. }
  143. ei := editInfo{Day: day, Added: added, Removed: removed}
  144. churn.global = append(churn.global, ei)
  145. if churn.TrackPeople {
  146. seq, exists := churn.people[author]
  147. if !exists {
  148. seq = []editInfo{}
  149. }
  150. seq = append(seq, ei)
  151. churn.people[author] = seq
  152. }
  153. }
  154. return nil, nil
  155. }
  156. // Fork clones the same item several times on branches.
  157. func (churn *ChurnAnalysis) Fork(n int) []hercules.PipelineItem {
  158. return hercules.ForkSamePipelineItem(churn, n)
  159. }
  160. func (churn *ChurnAnalysis) Finalize() interface{} {
  161. result := ChurnAnalysisResult{
  162. Global: editInfosToEdits(churn.global),
  163. People: map[string]Edits{},
  164. }
  165. if churn.TrackPeople {
  166. for key, val := range churn.people {
  167. result.People[churn.reversedPeopleDict[key]] = editInfosToEdits(val)
  168. }
  169. }
  170. return result
  171. }
  172. func (churn *ChurnAnalysis) Serialize(result interface{}, binary bool, writer io.Writer) error {
  173. burndownResult := result.(ChurnAnalysisResult)
  174. if binary {
  175. return churn.serializeBinary(&burndownResult, writer)
  176. }
  177. churn.serializeText(&burndownResult, writer)
  178. return nil
  179. }
  180. func (churn *ChurnAnalysis) serializeText(result *ChurnAnalysisResult, writer io.Writer) {
  181. fmt.Fprintln(writer, " global:")
  182. printEdits(result.Global, writer, 4)
  183. for key, val := range result.People {
  184. fmt.Fprintf(writer, " %s:\n", hercules.SafeYamlString(key))
  185. printEdits(val, writer, 4)
  186. }
  187. }
  188. func (churn *ChurnAnalysis) serializeBinary(result *ChurnAnalysisResult, writer io.Writer) error {
  189. message := ChurnAnalysisResultMessage{
  190. Global: editsToEditsMessage(result.Global),
  191. People: map[string]*EditsMessage{},
  192. }
  193. for key, val := range result.People {
  194. message.People[key] = editsToEditsMessage(val)
  195. }
  196. serialized, err := proto.Marshal(&message)
  197. if err != nil {
  198. return err
  199. }
  200. writer.Write(serialized)
  201. return nil
  202. }
  203. func editInfosToEdits(eis []editInfo) Edits {
  204. aux := map[int]*editInfo{}
  205. for _, ei := range eis {
  206. ptr := aux[ei.Day]
  207. if ptr == nil {
  208. ptr = &editInfo{Day: ei.Day}
  209. }
  210. ptr.Added += ei.Added
  211. ptr.Removed += ei.Removed
  212. aux[ei.Day] = ptr
  213. }
  214. seq := []int{}
  215. for key := range aux {
  216. seq = append(seq, key)
  217. }
  218. sort.Ints(seq)
  219. edits := Edits{
  220. Days: make([]int, len(seq)),
  221. Additions: make([]int, len(seq)),
  222. Removals: make([]int, len(seq)),
  223. }
  224. for i, day := range seq {
  225. edits.Days[i] = day
  226. edits.Additions[i] = aux[day].Added
  227. edits.Removals[i] = aux[day].Removed
  228. }
  229. return edits
  230. }
  231. func printEdits(edits Edits, writer io.Writer, indent int) {
  232. strIndent := strings.Repeat(" ", indent)
  233. printArray := func(arr []int, name string) {
  234. fmt.Fprintf(writer, "%s%s: [", strIndent, name)
  235. for i, v := range arr {
  236. if i < len(arr)-1 {
  237. fmt.Fprintf(writer, "%d, ", v)
  238. } else {
  239. fmt.Fprintf(writer, "%d]\n", v)
  240. }
  241. }
  242. }
  243. printArray(edits.Days, "days")
  244. printArray(edits.Additions, "additions")
  245. printArray(edits.Removals, "removals")
  246. }
  247. func editsToEditsMessage(edits Edits) *EditsMessage {
  248. message := &EditsMessage{
  249. Days: make([]uint32, len(edits.Days)),
  250. Additions: make([]uint32, len(edits.Additions)),
  251. Removals: make([]uint32, len(edits.Removals)),
  252. }
  253. copyInts := func(arr []int, where []uint32) {
  254. for i, v := range arr {
  255. where[i] = uint32(v)
  256. }
  257. }
  258. copyInts(edits.Days, message.Days)
  259. copyInts(edits.Additions, message.Additions)
  260. copyInts(edits.Removals, message.Removals)
  261. return message
  262. }
  263. func init() {
  264. hercules.Registry.Register(&ChurnAnalysis{})
  265. }