identity.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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. func (detector *Detector) Fork(n int) []core.PipelineItem {
  121. return core.ForkSamePipelineItem(detector, n)
  122. }
  123. // LoadPeopleDict loads author signatures from a text file.
  124. // The format is one signature per line, and the signature consists of several
  125. // keys separated by "|". The first key is the main one and used to reference all the rest.
  126. func (detector *Detector) LoadPeopleDict(path string) error {
  127. file, err := os.Open(path)
  128. if err != nil {
  129. return err
  130. }
  131. defer file.Close()
  132. scanner := bufio.NewScanner(file)
  133. dict := make(map[string]int)
  134. reverseDict := []string{}
  135. size := 0
  136. for scanner.Scan() {
  137. ids := strings.Split(scanner.Text(), "|")
  138. for _, id := range ids {
  139. dict[strings.ToLower(id)] = size
  140. }
  141. reverseDict = append(reverseDict, ids[0])
  142. size++
  143. }
  144. reverseDict = append(reverseDict, AuthorMissingName)
  145. detector.PeopleDict = dict
  146. detector.ReversedPeopleDict = reverseDict
  147. return nil
  148. }
  149. // GeneratePeopleDict loads author signatures from the specified list of Git commits.
  150. func (detector *Detector) GeneratePeopleDict(commits []*object.Commit) {
  151. dict := map[string]int{}
  152. emails := map[int][]string{}
  153. names := map[int][]string{}
  154. size := 0
  155. mailmapFile, err := commits[len(commits)-1].File(".mailmap")
  156. if err == nil {
  157. mailMapContents, err := mailmapFile.Contents()
  158. if err == nil {
  159. mailmap := ParseMailmap(mailMapContents)
  160. for key, val := range mailmap {
  161. key = strings.ToLower(key)
  162. toEmail := strings.ToLower(val.Email)
  163. toName := strings.ToLower(val.Name)
  164. id, exists := dict[toEmail]
  165. if !exists {
  166. id, exists = dict[toName]
  167. }
  168. if exists {
  169. dict[key] = id
  170. } else {
  171. id = size
  172. size++
  173. if toEmail != "" {
  174. dict[toEmail] = id
  175. emails[id] = append(emails[id], toEmail)
  176. }
  177. if toName != "" {
  178. dict[toName] = id
  179. names[id] = append(names[id], toName)
  180. }
  181. dict[key] = id
  182. }
  183. if strings.Contains(key, "@") {
  184. exists := false
  185. for _, val := range emails[id] {
  186. if key == val {
  187. exists = true
  188. break
  189. }
  190. }
  191. if !exists {
  192. emails[id] = append(emails[id], key)
  193. }
  194. } else {
  195. exists := false
  196. for _, val := range names[id] {
  197. if key == val {
  198. exists = true
  199. break
  200. }
  201. }
  202. if !exists {
  203. names[id] = append(names[id], key)
  204. }
  205. }
  206. }
  207. }
  208. }
  209. for _, commit := range commits {
  210. email := strings.ToLower(commit.Author.Email)
  211. name := strings.ToLower(commit.Author.Name)
  212. id, exists := dict[email]
  213. if exists {
  214. _, exists := dict[name]
  215. if !exists {
  216. dict[name] = id
  217. names[id] = append(names[id], name)
  218. }
  219. continue
  220. }
  221. id, exists = dict[name]
  222. if exists {
  223. dict[email] = id
  224. emails[id] = append(emails[id], email)
  225. continue
  226. }
  227. dict[email] = size
  228. dict[name] = size
  229. emails[size] = append(emails[size], email)
  230. names[size] = append(names[size], name)
  231. size++
  232. }
  233. reverseDict := make([]string, size)
  234. for _, val := range dict {
  235. sort.Strings(names[val])
  236. sort.Strings(emails[val])
  237. reverseDict[val] = strings.Join(names[val], "|") + "|" + strings.Join(emails[val], "|")
  238. }
  239. detector.PeopleDict = dict
  240. detector.ReversedPeopleDict = reverseDict
  241. }
  242. // MergeReversedDicts joins two identity lists together, excluding duplicates, in-order.
  243. func (detector Detector) MergeReversedDicts(rd1, rd2 []string) (map[string][3]int, []string) {
  244. people := map[string][3]int{}
  245. for i, pid := range rd1 {
  246. ptrs := people[pid]
  247. ptrs[0] = len(people)
  248. ptrs[1] = i
  249. ptrs[2] = -1
  250. people[pid] = ptrs
  251. }
  252. for i, pid := range rd2 {
  253. ptrs, exists := people[pid]
  254. if !exists {
  255. ptrs[0] = len(people)
  256. ptrs[1] = -1
  257. }
  258. ptrs[2] = i
  259. people[pid] = ptrs
  260. }
  261. mrd := make([]string, len(people))
  262. for name, ptrs := range people {
  263. mrd[ptrs[0]] = name
  264. }
  265. return people, mrd
  266. }
  267. func init() {
  268. core.Registry.Register(&Detector{})
  269. }