churn_analysis.go 7.5 KB

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