identity.go 9.5 KB

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