churn_analysis.go 7.4 KB

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