identity.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. package identity
  2. import (
  3. "bufio"
  4. "os"
  5. "sort"
  6. "strings"
  7. "gopkg.in/src-d/go-git.v4"
  8. "gopkg.in/src-d/go-git.v4/plumbing/object"
  9. "gopkg.in/src-d/hercules.v4/internal/core"
  10. )
  11. // Detector determines the author of a commit. Same person can commit under different
  12. // signatures, and we apply some heuristics to merge those together.
  13. // It is a PipelineItem.
  14. type Detector struct {
  15. core.NoopMerger
  16. // PeopleDict maps email || name -> developer id
  17. PeopleDict map[string]int
  18. // ReversedPeopleDict maps developer id -> description
  19. ReversedPeopleDict []string
  20. }
  21. const (
  22. // AuthorMissing is the internal author index which denotes any unmatched identities
  23. // (Detector.Consume()).
  24. AuthorMissing = (1 << 18) - 1
  25. // AuthorMissingName is the string name which corresponds to AuthorMissing.
  26. AuthorMissingName = "<unmatched>"
  27. // FactIdentityDetectorPeopleDict is the name of the fact which is inserted in
  28. // Detector.Configure(). It corresponds to Detector.PeopleDict - the mapping
  29. // from the signatures to the author indices.
  30. FactIdentityDetectorPeopleDict = "IdentityDetector.PeopleDict"
  31. // FactIdentityDetectorReversedPeopleDict is the name of the fact which is inserted in
  32. // Detector.Configure(). It corresponds to Detector.ReversedPeopleDict -
  33. // the mapping from the author indices to the main signature.
  34. FactIdentityDetectorReversedPeopleDict = "IdentityDetector.ReversedPeopleDict"
  35. // ConfigIdentityDetectorPeopleDictPath is the name of the configuration option
  36. // (Detector.Configure()) which allows to set the external PeopleDict mapping from a file.
  37. ConfigIdentityDetectorPeopleDictPath = "IdentityDetector.PeopleDictPath"
  38. // FactIdentityDetectorPeopleCount is the name of the fact which is inserted in
  39. // Detector.Configure(). It is equal to the overall number of unique authors
  40. // (the length of ReversedPeopleDict).
  41. FactIdentityDetectorPeopleCount = "IdentityDetector.PeopleCount"
  42. // DependencyAuthor is the name of the dependency provided by Detector.
  43. DependencyAuthor = "author"
  44. )
  45. // Name of this PipelineItem. Uniquely identifies the type, used for mapping keys, etc.
  46. func (detector *Detector) Name() string {
  47. return "IdentityDetector"
  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 (detector *Detector) Provides() []string {
  53. arr := [...]string{DependencyAuthor}
  54. return arr[:]
  55. }
  56. // Requires returns the list of names of entities which are needed by this PipelineItem.
  57. // Each requested entity will be inserted into `deps` of Consume(). In turn, those
  58. // entities are Provides() upstream.
  59. func (detector *Detector) Requires() []string {
  60. return []string{}
  61. }
  62. // ListConfigurationOptions returns the list of changeable public properties of this PipelineItem.
  63. func (detector *Detector) ListConfigurationOptions() []core.ConfigurationOption {
  64. options := [...]core.ConfigurationOption{{
  65. Name: ConfigIdentityDetectorPeopleDictPath,
  66. Description: "Path to the developers' email associations.",
  67. Flag: "people-dict",
  68. Type: core.StringConfigurationOption,
  69. Default: ""},
  70. }
  71. return options[:]
  72. }
  73. // Configure sets the properties previously published by ListConfigurationOptions().
  74. func (detector *Detector) Configure(facts map[string]interface{}) {
  75. if val, exists := facts[FactIdentityDetectorPeopleDict].(map[string]int); exists {
  76. detector.PeopleDict = val
  77. }
  78. if val, exists := facts[FactIdentityDetectorReversedPeopleDict].([]string); exists {
  79. detector.ReversedPeopleDict = val
  80. }
  81. if detector.PeopleDict == nil || detector.ReversedPeopleDict == nil {
  82. peopleDictPath, _ := facts[ConfigIdentityDetectorPeopleDictPath].(string)
  83. if peopleDictPath != "" {
  84. detector.LoadPeopleDict(peopleDictPath)
  85. facts[FactIdentityDetectorPeopleCount] = len(detector.ReversedPeopleDict) - 1
  86. } else {
  87. if _, exists := facts[core.ConfigPipelineCommits]; !exists {
  88. panic("IdentityDetector needs a list of commits to initialize.")
  89. }
  90. detector.GeneratePeopleDict(facts[core.ConfigPipelineCommits].([]*object.Commit))
  91. facts[FactIdentityDetectorPeopleCount] = len(detector.ReversedPeopleDict)
  92. }
  93. } else {
  94. facts[FactIdentityDetectorPeopleCount] = len(detector.ReversedPeopleDict)
  95. }
  96. facts[FactIdentityDetectorPeopleDict] = detector.PeopleDict
  97. facts[FactIdentityDetectorReversedPeopleDict] = detector.ReversedPeopleDict
  98. }
  99. // Initialize resets the temporary caches and prepares this PipelineItem for a series of Consume()
  100. // calls. The repository which is going to be analysed is supplied as an argument.
  101. func (detector *Detector) Initialize(repository *git.Repository) {
  102. }
  103. // Consume runs this PipelineItem on the next commit data.
  104. // `deps` contain all the results from upstream PipelineItem-s as requested by Requires().
  105. // Additionally, DependencyCommit is always present there and represents the analysed *object.Commit.
  106. // This function returns the mapping with analysis results. The keys must be the same as
  107. // in Provides(). If there was an error, nil is returned.
  108. func (detector *Detector) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  109. commit := deps[core.DependencyCommit].(*object.Commit)
  110. signature := commit.Author
  111. authorID, exists := detector.PeopleDict[strings.ToLower(signature.Email)]
  112. if !exists {
  113. authorID, exists = detector.PeopleDict[strings.ToLower(signature.Name)]
  114. if !exists {
  115. authorID = AuthorMissing
  116. }
  117. }
  118. return map[string]interface{}{DependencyAuthor: authorID}, nil
  119. }
  120. // Fork clones this PipelineItem.
  121. func (detector *Detector) Fork(n int) []core.PipelineItem {
  122. return core.ForkSamePipelineItem(detector, n)
  123. }
  124. // LoadPeopleDict loads author signatures from a text file.
  125. // The format is one signature per line, and the signature consists of several
  126. // keys separated by "|". The first key is the main one and used to reference all the rest.
  127. func (detector *Detector) LoadPeopleDict(path string) error {
  128. file, err := os.Open(path)
  129. if err != nil {
  130. return err
  131. }
  132. defer file.Close()
  133. scanner := bufio.NewScanner(file)
  134. dict := make(map[string]int)
  135. reverseDict := []string{}
  136. size := 0
  137. for scanner.Scan() {
  138. ids := strings.Split(scanner.Text(), "|")
  139. for _, id := range ids {
  140. dict[strings.ToLower(id)] = size
  141. }
  142. reverseDict = append(reverseDict, ids[0])
  143. size++
  144. }
  145. reverseDict = append(reverseDict, AuthorMissingName)
  146. detector.PeopleDict = dict
  147. detector.ReversedPeopleDict = reverseDict
  148. return nil
  149. }
  150. // GeneratePeopleDict loads author signatures from the specified list of Git commits.
  151. func (detector *Detector) GeneratePeopleDict(commits []*object.Commit) {
  152. dict := map[string]int{}
  153. emails := map[int][]string{}
  154. names := map[int][]string{}
  155. size := 0
  156. mailmapFile, err := commits[len(commits)-1].File(".mailmap")
  157. if err == nil {
  158. mailMapContents, err := mailmapFile.Contents()
  159. if err == nil {
  160. mailmap := ParseMailmap(mailMapContents)
  161. for key, val := range mailmap {
  162. key = strings.ToLower(key)
  163. toEmail := strings.ToLower(val.Email)
  164. toName := strings.ToLower(val.Name)
  165. id, exists := dict[toEmail]
  166. if !exists {
  167. id, exists = dict[toName]
  168. }
  169. if exists {
  170. dict[key] = id
  171. } else {
  172. id = size
  173. size++
  174. if toEmail != "" {
  175. dict[toEmail] = id
  176. emails[id] = append(emails[id], toEmail)
  177. }
  178. if toName != "" {
  179. dict[toName] = id
  180. names[id] = append(names[id], toName)
  181. }
  182. dict[key] = id
  183. }
  184. if strings.Contains(key, "@") {
  185. exists := false
  186. for _, val := range emails[id] {
  187. if key == val {
  188. exists = true
  189. break
  190. }
  191. }
  192. if !exists {
  193. emails[id] = append(emails[id], key)
  194. }
  195. } else {
  196. exists := false
  197. for _, val := range names[id] {
  198. if key == val {
  199. exists = true
  200. break
  201. }
  202. }
  203. if !exists {
  204. names[id] = append(names[id], key)
  205. }
  206. }
  207. }
  208. }
  209. }
  210. for _, commit := range commits {
  211. email := strings.ToLower(commit.Author.Email)
  212. name := strings.ToLower(commit.Author.Name)
  213. id, exists := dict[email]
  214. if exists {
  215. _, exists := dict[name]
  216. if !exists {
  217. dict[name] = id
  218. names[id] = append(names[id], name)
  219. }
  220. continue
  221. }
  222. id, exists = dict[name]
  223. if exists {
  224. dict[email] = id
  225. emails[id] = append(emails[id], email)
  226. continue
  227. }
  228. dict[email] = size
  229. dict[name] = size
  230. emails[size] = append(emails[size], email)
  231. names[size] = append(names[size], name)
  232. size++
  233. }
  234. reverseDict := make([]string, size)
  235. for _, val := range dict {
  236. sort.Strings(names[val])
  237. sort.Strings(emails[val])
  238. reverseDict[val] = strings.Join(names[val], "|") + "|" + strings.Join(emails[val], "|")
  239. }
  240. detector.PeopleDict = dict
  241. detector.ReversedPeopleDict = reverseDict
  242. }
  243. // MergeReversedDicts joins two identity lists together, excluding duplicates, in-order.
  244. func (detector Detector) MergeReversedDicts(rd1, rd2 []string) (map[string][3]int, []string) {
  245. people := map[string][3]int{}
  246. for i, pid := range rd1 {
  247. ptrs := people[pid]
  248. ptrs[0] = len(people)
  249. ptrs[1] = i
  250. ptrs[2] = -1
  251. people[pid] = ptrs
  252. }
  253. for i, pid := range rd2 {
  254. ptrs, exists := people[pid]
  255. if !exists {
  256. ptrs[0] = len(people)
  257. ptrs[1] = -1
  258. }
  259. ptrs[2] = i
  260. people[pid] = ptrs
  261. }
  262. mrd := make([]string, len(people))
  263. for name, ptrs := range people {
  264. mrd[ptrs[0]] = name
  265. }
  266. return people, mrd
  267. }
  268. func init() {
  269. core.Registry.Register(&Detector{})
  270. }