churn_analysis.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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]*object.Blob)
  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, err = hercules.CountLines(cache[change.To.TreeEntry.Hash])
  124. if err != nil && err.Error() == "binary" {
  125. err = nil
  126. }
  127. case merkletrie.Delete:
  128. removed, err = hercules.CountLines(cache[change.From.TreeEntry.Hash])
  129. if err != nil && err.Error() == "binary" {
  130. err = nil
  131. }
  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{Day: day, 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.Day]
  213. if ptr == nil {
  214. ptr = &editInfo{Day: ei.Day}
  215. }
  216. ptr.Added += ei.Added
  217. ptr.Removed += ei.Removed
  218. aux[ei.Day] = ptr
  219. }
  220. seq := []int{}
  221. for key := range aux {
  222. seq = append(seq, key)
  223. }
  224. sort.Ints(seq)
  225. edits := Edits{
  226. Days: make([]int, len(seq)),
  227. Additions: make([]int, len(seq)),
  228. Removals: make([]int, len(seq)),
  229. }
  230. for i, day := range seq {
  231. edits.Days[i] = day
  232. edits.Additions[i] = aux[day].Added
  233. edits.Removals[i] = aux[day].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.Days, "days")
  250. printArray(edits.Additions, "additions")
  251. printArray(edits.Removals, "removals")
  252. }
  253. func editsToEditsMessage(edits Edits) *EditsMessage {
  254. message := &EditsMessage{
  255. Days: make([]uint32, len(edits.Days)),
  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.Days, message.Days)
  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. }