identity.go 9.0 KB

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