identity.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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.v10/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()). It may *not* be (1 << 18) - 1, see BurndownAnalysis.packPersonWithDay().
  25. AuthorMissing = (1 << 18) - 2
  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. // MergedIndex is the result of merging `rd1[First]` and `rd2[Second]`: the index in the final reversed
  250. // dictionary. -1 for `First` or `Second` means that the corresponding string does not exist
  251. // in respectively `rd1` and `rd2`.
  252. // See also:
  253. // * MergeReversedDictsLiteral()
  254. // * MergeReversedDictsIdentities()
  255. type MergedIndex struct {
  256. Final int
  257. First int
  258. Second int
  259. }
  260. // MergeReversedDictsLiteral joins two string lists together, excluding duplicates, in-order.
  261. // The string comparisons are the usual ones.
  262. // The returned mapping's keys are the unique strings in `rd1 ∪ rd2`, and the values are:
  263. // 1. Index after merging.
  264. // 2. Corresponding index in the first array - `rd1`. -1 means that it does not exist.
  265. // 3. Corresponding index in the second array - `rd2`. -1 means that it does not exist.
  266. func MergeReversedDictsLiteral(rd1, rd2 []string) (map[string]MergedIndex, []string) {
  267. people := map[string]MergedIndex{}
  268. for i, pid := range rd1 {
  269. people[pid] = MergedIndex{len(people), i, -1}
  270. }
  271. for i, pid := range rd2 {
  272. if ptrs, exists := people[pid]; !exists {
  273. people[pid] = MergedIndex{len(people), -1, i}
  274. } else {
  275. people[pid] = MergedIndex{ptrs.Final, ptrs.First, i}
  276. }
  277. }
  278. mrd := make([]string, len(people))
  279. for name, ptrs := range people {
  280. mrd[ptrs.Final] = name
  281. }
  282. return people, mrd
  283. }
  284. type identityPair struct {
  285. Index1 int
  286. Index2 int
  287. }
  288. // MergeReversedDictsIdentities joins two identity lists together, excluding duplicates.
  289. // The strings are split by "|" and we find the connected components..
  290. // The returned mapping's keys are the unique strings in `rd1 ∪ rd2`, and the values are:
  291. // 1. Index after merging.
  292. // 2. Corresponding index in the first array - `rd1`. -1 means that it does not exist.
  293. // 3. Corresponding index in the second array - `rd2`. -1 means that it does not exist.
  294. func MergeReversedDictsIdentities(rd1, rd2 []string) (map[string]MergedIndex, []string) {
  295. vocabulary := map[string]identityPair{}
  296. vertices1 := make([][]string, len(rd1))
  297. for i, s := range rd1 {
  298. parts := strings.Split(s, "|")
  299. vertices1[i] = parts
  300. for _, p := range parts {
  301. vocabulary[p] = identityPair{i, -1}
  302. }
  303. }
  304. vertices2 := make([][]string, len(rd2))
  305. for i, s := range rd2 {
  306. parts := strings.Split(s, "|")
  307. vertices2[i] = parts
  308. for _, p := range parts {
  309. if ip, exists := vocabulary[p]; !exists {
  310. vocabulary[p] = identityPair{-1, i}
  311. } else {
  312. ip.Index2 = i
  313. vocabulary[p] = ip
  314. }
  315. }
  316. }
  317. // find the connected components by walking the graph
  318. var walks []map[string]bool
  319. visited := map[string]bool{}
  320. walkFromVertex := func(root []string) {
  321. walk := map[string]bool{}
  322. pending := map[string]bool{}
  323. for _, p := range root {
  324. pending[p] = true
  325. }
  326. for len(pending) > 0 {
  327. var element string
  328. for e := range pending {
  329. element = e
  330. delete(pending, e)
  331. break
  332. }
  333. if !walk[element] {
  334. walk[element] = true
  335. ip := vocabulary[element]
  336. if ip.Index1 >= 0 {
  337. for _, p := range vertices1[ip.Index1] {
  338. if !walk[p] {
  339. pending[p] = true
  340. }
  341. }
  342. }
  343. if ip.Index2 >= 0 {
  344. for _, p := range vertices2[ip.Index2] {
  345. if !walk[p] {
  346. pending[p] = true
  347. }
  348. }
  349. }
  350. }
  351. }
  352. for e := range walk {
  353. visited[e] = true
  354. }
  355. walks = append(walks, walk)
  356. }
  357. for i1 := range rd1 {
  358. var skip bool
  359. for _, p := range vertices1[i1] {
  360. if visited[p] {
  361. skip = true
  362. break
  363. }
  364. }
  365. if skip {
  366. continue
  367. }
  368. walkFromVertex(vertices1[i1])
  369. }
  370. for i2 := range rd2 {
  371. var skip bool
  372. for _, p := range vertices2[i2] {
  373. if visited[p] {
  374. skip = true
  375. break
  376. }
  377. }
  378. if skip {
  379. continue
  380. }
  381. walkFromVertex(vertices2[i2])
  382. }
  383. mergedStrings := make([]string, 0, len(walks))
  384. mergedIndex := map[string]MergedIndex{}
  385. // convert each walk from strings to indexes
  386. for walkIndex, walk := range walks {
  387. ids := make([]string, 0, len(walk))
  388. for key := range walk {
  389. ids = append(ids, key)
  390. }
  391. // place emails after names
  392. sort.Slice(ids, func(i, j int) bool {
  393. iid := ids[i]
  394. jid := ids[j]
  395. iHasAt := strings.ContainsRune(iid, '@')
  396. jHasAt := strings.ContainsRune(jid, '@')
  397. if iHasAt == jHasAt {
  398. return iid < jid
  399. }
  400. return jHasAt
  401. })
  402. mergedStrings = append(mergedStrings, strings.Join(ids, "|"))
  403. for _, key := range ids {
  404. ipair := vocabulary[key]
  405. if ipair.Index1 >= 0 {
  406. s1 := rd1[ipair.Index1]
  407. if mi, exists := mergedIndex[s1]; !exists {
  408. mergedIndex[s1] = MergedIndex{walkIndex, ipair.Index1, -1}
  409. } else {
  410. mergedIndex[s1] = MergedIndex{walkIndex, ipair.Index1, mi.Second}
  411. }
  412. }
  413. if ipair.Index2 >= 0 {
  414. s2 := rd2[ipair.Index2]
  415. if mi, exists := mergedIndex[s2]; !exists {
  416. mergedIndex[s2] = MergedIndex{walkIndex, -1, ipair.Index2}
  417. } else {
  418. mergedIndex[s2] = MergedIndex{walkIndex, mi.First, ipair.Index2}
  419. }
  420. }
  421. }
  422. }
  423. return mergedIndex, mergedStrings
  424. }
  425. func init() {
  426. core.Registry.Register(&Detector{})
  427. }