imports_printer.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. package leaves
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "log"
  7. "sort"
  8. "time"
  9. "github.com/gogo/protobuf/proto"
  10. imports2 "github.com/src-d/imports"
  11. "gopkg.in/src-d/go-git.v4"
  12. gitplumbing "gopkg.in/src-d/go-git.v4/plumbing"
  13. "gopkg.in/src-d/hercules.v10/internal/core"
  14. "gopkg.in/src-d/hercules.v10/internal/pb"
  15. "gopkg.in/src-d/hercules.v10/internal/plumbing"
  16. "gopkg.in/src-d/hercules.v10/internal/plumbing/identity"
  17. "gopkg.in/src-d/hercules.v10/internal/plumbing/imports"
  18. "gopkg.in/src-d/hercules.v10/internal/yaml"
  19. )
  20. // ImportsMap is the type of the mapping from dev indexes to languages to import names to ticks to
  21. // usage counts. Ticks start counting from 0 and correspond to the earliest commit timestamp
  22. // (included in the YAML/protobuf header).
  23. type ImportsMap = map[int]map[string]map[string]map[int]int64
  24. // ImportsPerDeveloper collects imports per developer.
  25. type ImportsPerDeveloper struct {
  26. core.NoopMerger
  27. core.OneShotMergeProcessor
  28. // TickSize defines the time mapping granularity (the last ImportsMap's key).
  29. TickSize time.Duration
  30. // imports mapping, see the referenced type for details.
  31. imports ImportsMap
  32. // reversedPeopleDict references IdentityDetector.ReversedPeopleDict
  33. reversedPeopleDict []string
  34. l core.Logger
  35. }
  36. // ImportsPerDeveloperResult is returned by Finalize() and represents the analysis result.
  37. type ImportsPerDeveloperResult struct {
  38. // Imports is the imports mapping, see the referenced type for details.
  39. Imports ImportsMap
  40. // reversedPeopleDict references IdentityDetector.ReversedPeopleDict
  41. reversedPeopleDict []string
  42. // tickSize references TicksSinceStart.TickSize
  43. tickSize time.Duration
  44. }
  45. // Name of this PipelineItem. Uniquely identifies the type, used for mapping keys, etc.
  46. func (ipd *ImportsPerDeveloper) Name() string {
  47. return "ImportsPerDeveloper"
  48. }
  49. // Provides returns the list of names of entities which are produced by this PipelineItem.
  50. // Each produced entity will be inserted into `deps` of dependent Consume()-s according
  51. // to this list. Also used by core.Registry to build the global map of providers.
  52. func (ipd *ImportsPerDeveloper) Provides() []string {
  53. return []string{}
  54. }
  55. // Requires returns the list of names of entities which are needed by this PipelineItem.
  56. // Each requested entity will be inserted into `deps` of Consume(). In turn, those
  57. // entities are Provides() upstream.
  58. func (ipd *ImportsPerDeveloper) Requires() []string {
  59. return []string{imports.DependencyImports, identity.DependencyAuthor, plumbing.DependencyTick}
  60. }
  61. // ListConfigurationOptions returns the list of changeable public properties of this PipelineItem.
  62. func (ipd *ImportsPerDeveloper) ListConfigurationOptions() []core.ConfigurationOption {
  63. return []core.ConfigurationOption{}
  64. }
  65. // Flag for the command line switch which enables this analysis.
  66. func (ipd *ImportsPerDeveloper) Flag() string {
  67. return "imports-per-dev"
  68. }
  69. // Description returns the text which explains what the analysis is doing.
  70. func (ipd *ImportsPerDeveloper) Description() string {
  71. return "Whenever a file is changed or added, we extract the imports from it and increment " +
  72. "their usage for the commit author."
  73. }
  74. // Configure sets the properties previously published by ListConfigurationOptions().
  75. func (ipd *ImportsPerDeveloper) Configure(facts map[string]interface{}) error {
  76. if l, exists := facts[core.ConfigLogger].(core.Logger); exists {
  77. ipd.l = l
  78. }
  79. ipd.reversedPeopleDict = facts[identity.FactIdentityDetectorReversedPeopleDict].([]string)
  80. if val, exists := facts[plumbing.FactTickSize].(time.Duration); exists {
  81. ipd.TickSize = val
  82. }
  83. return nil
  84. }
  85. // Initialize resets the temporary caches and prepares this PipelineItem for a series of Consume()
  86. // calls. The repository which is going to be analysed is supplied as an argument.
  87. func (ipd *ImportsPerDeveloper) Initialize(repository *git.Repository) error {
  88. ipd.l = core.NewLogger()
  89. ipd.imports = ImportsMap{}
  90. ipd.OneShotMergeProcessor.Initialize()
  91. if ipd.TickSize == 0 {
  92. ipd.TickSize = time.Hour * 24
  93. ipd.l.Warnf("tick size was not set, adjusted to %v\n", ipd.TickSize)
  94. }
  95. return nil
  96. }
  97. // Consume runs this PipelineItem on the next commit data.
  98. // `deps` contain all the results from upstream PipelineItem-s as requested by Requires().
  99. // Additionally, DependencyCommit is always present there and represents the analysed *object.Commit.
  100. // This function returns the mapping with analysis results. The keys must be the same as
  101. // in Provides(). If there was an error, nil is returned.
  102. func (ipd *ImportsPerDeveloper) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  103. if deps[core.DependencyIsMerge].(bool) {
  104. // we ignore merge commits
  105. // TODO(vmarkovtsev): handle them better
  106. return nil, nil
  107. }
  108. author := deps[identity.DependencyAuthor].(int)
  109. imps := deps[imports.DependencyImports].(map[gitplumbing.Hash]imports2.File)
  110. aimps := ipd.imports[author]
  111. tick := deps[plumbing.DependencyTick].(int)
  112. if aimps == nil {
  113. aimps = map[string]map[string]map[int]int64{}
  114. ipd.imports[author] = aimps
  115. }
  116. for _, file := range imps {
  117. limps := aimps[file.Lang]
  118. if limps == nil {
  119. limps = map[string]map[int]int64{}
  120. aimps[file.Lang] = limps
  121. }
  122. for _, imp := range file.Imports {
  123. timps, exists := limps[imp]
  124. if !exists {
  125. timps = map[int]int64{}
  126. limps[imp] = timps
  127. }
  128. timps[tick]++
  129. }
  130. }
  131. return nil, nil
  132. }
  133. // Finalize returns the result of the analysis. Further Consume() calls are not expected.
  134. func (ipd *ImportsPerDeveloper) Finalize() interface{} {
  135. return ImportsPerDeveloperResult{
  136. Imports: ipd.imports,
  137. reversedPeopleDict: ipd.reversedPeopleDict,
  138. tickSize: ipd.TickSize,
  139. }
  140. }
  141. // Fork clones this PipelineItem.
  142. func (ipd *ImportsPerDeveloper) Fork(n int) []core.PipelineItem {
  143. return core.ForkSamePipelineItem(ipd, n)
  144. }
  145. // Serialize converts the analysis result as returned by Finalize() to text or bytes.
  146. // The text format is YAML and the bytes format is Protocol Buffers.
  147. func (ipd *ImportsPerDeveloper) Serialize(result interface{}, binary bool, writer io.Writer) error {
  148. importsResult := result.(ImportsPerDeveloperResult)
  149. if binary {
  150. return ipd.serializeBinary(&importsResult, writer)
  151. }
  152. ipd.serializeText(&importsResult, writer)
  153. return nil
  154. }
  155. func (ipd *ImportsPerDeveloper) serializeText(result *ImportsPerDeveloperResult, writer io.Writer) {
  156. devs := make([]int, 0, len(result.Imports))
  157. for dev := range result.Imports {
  158. devs = append(devs, dev)
  159. }
  160. sort.Ints(devs)
  161. fmt.Fprintln(writer, " tick_size:", int(result.tickSize.Seconds()))
  162. fmt.Fprintln(writer, " imports:")
  163. for _, dev := range devs {
  164. imps := result.Imports[dev]
  165. obj, err := json.Marshal(imps)
  166. if err != nil {
  167. log.Panicf("Could not serialize %v: %v", imps, err)
  168. }
  169. fmt.Fprintf(writer, " %s: %s\n", yaml.SafeString(result.reversedPeopleDict[dev]), string(obj))
  170. }
  171. }
  172. func (ipd *ImportsPerDeveloper) serializeBinary(result *ImportsPerDeveloperResult, writer io.Writer) error {
  173. message := pb.ImportsPerDeveloperResults{
  174. Imports: make([]*pb.ImportsPerDeveloper, len(result.Imports)),
  175. AuthorIndex: result.reversedPeopleDict,
  176. TickSize: int64(result.tickSize),
  177. }
  178. for key, dev := range result.Imports {
  179. pbdev := &pb.ImportsPerDeveloper{Languages: map[string]*pb.ImportsPerLanguage{}}
  180. message.Imports[key] = pbdev
  181. for lang, ticks := range dev {
  182. pbticks := map[string]*pb.ImportsPerTick{}
  183. pbdev.Languages[lang] = &pb.ImportsPerLanguage{Ticks: pbticks}
  184. for imp, tick := range ticks {
  185. counts := map[int32]int64{}
  186. pbticks[imp] = &pb.ImportsPerTick{Counts: counts}
  187. for ti, val := range tick {
  188. counts[int32(ti)] = val
  189. }
  190. }
  191. }
  192. }
  193. serialized, err := proto.Marshal(&message)
  194. if err != nil {
  195. return err
  196. }
  197. _, err = writer.Write(serialized)
  198. return err
  199. }
  200. // Deserialize converts the specified protobuf bytes to ImportsPerDeveloperResult.
  201. func (ipd *ImportsPerDeveloper) Deserialize(pbmessage []byte) (interface{}, error) {
  202. msg := pb.ImportsPerDeveloperResults{}
  203. err := proto.Unmarshal(pbmessage, &msg)
  204. if err != nil {
  205. return nil, err
  206. }
  207. r := ImportsPerDeveloperResult{
  208. Imports: ImportsMap{},
  209. reversedPeopleDict: msg.AuthorIndex,
  210. tickSize: time.Duration(msg.TickSize),
  211. }
  212. for devi, dev := range msg.Imports {
  213. rdev := map[string]map[string]map[int]int64{}
  214. r.Imports[devi] = rdev
  215. for lang, names := range dev.Languages {
  216. rlang := map[string]map[int]int64{}
  217. rdev[lang] = rlang
  218. for name, ticks := range names.Ticks {
  219. rticks := map[int]int64{}
  220. rlang[name] = rticks
  221. for tick, val := range ticks.Counts {
  222. rticks[int(tick)] = val
  223. }
  224. }
  225. }
  226. }
  227. return r, nil
  228. }
  229. func init() {
  230. core.Registry.Register(&ImportsPerDeveloper{})
  231. }