typos.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. package research
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "log"
  7. "unicode/utf8"
  8. "github.com/gogo/protobuf/proto"
  9. "github.com/sergi/go-diff/diffmatchpatch"
  10. "gopkg.in/bblfsh/sdk.v2/uast"
  11. "gopkg.in/bblfsh/sdk.v2/uast/nodes"
  12. "gopkg.in/src-d/go-git.v4"
  13. "gopkg.in/src-d/go-git.v4/plumbing"
  14. "gopkg.in/src-d/go-git.v4/plumbing/object"
  15. "gopkg.in/src-d/hercules.v10/internal/core"
  16. "gopkg.in/src-d/hercules.v10/internal/levenshtein"
  17. "gopkg.in/src-d/hercules.v10/internal/pb"
  18. items "gopkg.in/src-d/hercules.v10/internal/plumbing"
  19. uast_items "gopkg.in/src-d/hercules.v10/internal/plumbing/uast"
  20. "gopkg.in/src-d/hercules.v10/internal/yaml"
  21. )
  22. // TyposDatasetBuilder collects pairs of typo-fix in source code identifiers.
  23. type TyposDatasetBuilder struct {
  24. core.NoopMerger
  25. // MaximumAllowedDistance is the maximum Levenshtein distance between two identifiers
  26. // to consider them a typo-fix pair.
  27. MaximumAllowedDistance int
  28. // typos stores the found typo-fix pairs.
  29. typos []Typo
  30. // lcontext is the Context for measuring Levenshtein distance between lines.
  31. lcontext *levenshtein.Context
  32. // xpather filters identifiers.
  33. xpather uast_items.ChangesXPather
  34. // remote carries the repository remote URL (for debugging)
  35. remote string
  36. }
  37. // TyposResult is returned by TyposDatasetBuilder.Finalize() and carries the found typo-fix
  38. // pairs of identifiers.
  39. type TyposResult struct {
  40. Typos []Typo
  41. }
  42. // Typo carries the information about a typo-fix pair.
  43. type Typo struct {
  44. Wrong string
  45. Correct string
  46. Commit plumbing.Hash
  47. File string
  48. Line int
  49. }
  50. const (
  51. // DefaultMaximumAllowedTypoDistance is the default value of the maximum Levenshtein distance
  52. // between two identifiers to consider them a typo-fix pair.
  53. DefaultMaximumAllowedTypoDistance = 4
  54. // ConfigTyposDatasetMaximumAllowedDistance is the name of the configuration option
  55. // (`TyposDatasetBuilder.Configure()`) which sets the maximum Levenshtein distance between
  56. // two identifiers to consider them a typo-fix pair.
  57. ConfigTyposDatasetMaximumAllowedDistance = "TyposDatasetBuilder.MaximumAllowedDistance"
  58. )
  59. // Name of this PipelineItem. Uniquely identifies the type, used for mapping keys, etc.
  60. func (tdb *TyposDatasetBuilder) Name() string {
  61. return "TyposDataset"
  62. }
  63. // Provides returns the list of names of entities which are produced by this PipelineItem.
  64. // Each produced entity will be inserted into `deps` of dependent Consume()-s according
  65. // to this list. Also used by core.Registry to build the global map of providers.
  66. func (tdb *TyposDatasetBuilder) Provides() []string {
  67. return []string{}
  68. }
  69. // Requires returns the list of names of entities which are needed by this PipelineItem.
  70. // Each requested entity will be inserted into `deps` of Consume(). In turn, those
  71. // entities are Provides() upstream.
  72. func (tdb *TyposDatasetBuilder) Requires() []string {
  73. arr := [...]string{
  74. uast_items.DependencyUastChanges, items.DependencyFileDiff, items.DependencyBlobCache}
  75. return arr[:]
  76. }
  77. // ListConfigurationOptions returns the list of changeable public properties of this PipelineItem.
  78. func (tdb *TyposDatasetBuilder) ListConfigurationOptions() []core.ConfigurationOption {
  79. options := [...]core.ConfigurationOption{{
  80. Name: ConfigTyposDatasetMaximumAllowedDistance,
  81. Description: "Maximum Levenshtein distance between two identifiers to consider them " +
  82. "a typo-fix pair.",
  83. Flag: "typos-max-distance",
  84. Type: core.IntConfigurationOption,
  85. Default: DefaultMaximumAllowedTypoDistance},
  86. }
  87. return options[:]
  88. }
  89. // Configure sets the properties previously published by ListConfigurationOptions().
  90. func (tdb *TyposDatasetBuilder) Configure(facts map[string]interface{}) error {
  91. if val, exists := facts[ConfigTyposDatasetMaximumAllowedDistance].(int); exists {
  92. tdb.MaximumAllowedDistance = val
  93. }
  94. return nil
  95. }
  96. // Flag for the command line switch which enables this analysis.
  97. func (tdb *TyposDatasetBuilder) Flag() string {
  98. return "typos-dataset"
  99. }
  100. // Description returns the text which explains what the analysis is doing.
  101. func (tdb *TyposDatasetBuilder) Description() string {
  102. return "Extracts typo-fix identifier pairs from source code in commit diffs."
  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 (tdb *TyposDatasetBuilder) Initialize(repository *git.Repository) error {
  107. if tdb.MaximumAllowedDistance <= 0 {
  108. tdb.MaximumAllowedDistance = DefaultMaximumAllowedTypoDistance
  109. }
  110. tdb.lcontext = &levenshtein.Context{}
  111. tdb.xpather.XPath = "//uast:Identifier"
  112. tdb.remote = core.GetSensibleRemote(repository)
  113. return nil
  114. }
  115. type candidate struct {
  116. Before int
  117. After int
  118. }
  119. // Consume runs this PipelineItem on the next commit data.
  120. // `deps` contain all the results from upstream PipelineItem-s as requested by Requires().
  121. // Additionally, DependencyCommit is always present there and represents the analysed *object.Commit.
  122. // This function returns the mapping with analysis results. The keys must be the same as
  123. // in Provides(). If there was an error, nil is returned.
  124. func (tdb *TyposDatasetBuilder) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  125. if deps[core.DependencyIsMerge].(bool) {
  126. return nil, nil
  127. }
  128. commit := deps[core.DependencyCommit].(*object.Commit).Hash
  129. cache := deps[items.DependencyBlobCache].(map[plumbing.Hash]*items.CachedBlob)
  130. diffs := deps[items.DependencyFileDiff].(map[string]items.FileDiffData)
  131. changes := deps[uast_items.DependencyUastChanges].([]uast_items.Change)
  132. for _, change := range changes {
  133. if change.Before == nil || change.After == nil {
  134. continue
  135. }
  136. linesBefore := bytes.Split(cache[change.Change.From.TreeEntry.Hash].Data, []byte{'\n'})
  137. linesAfter := bytes.Split(cache[change.Change.To.TreeEntry.Hash].Data, []byte{'\n'})
  138. diff := diffs[change.Change.To.Name]
  139. var lineNumBefore, lineNumAfter int
  140. var candidates []candidate
  141. focusedLinesBefore := map[int]bool{}
  142. focusedLinesAfter := map[int]bool{}
  143. removedSize := 0
  144. for _, edit := range diff.Diffs {
  145. size := utf8.RuneCountInString(edit.Text)
  146. switch edit.Type {
  147. case diffmatchpatch.DiffDelete:
  148. lineNumBefore += size
  149. removedSize = size
  150. case diffmatchpatch.DiffInsert:
  151. if size == removedSize {
  152. for i := 0; i < size; i++ {
  153. lb := lineNumBefore - size + i
  154. la := lineNumAfter + i
  155. dist := tdb.lcontext.Distance(string(linesBefore[lb]), string(linesAfter[la]))
  156. if dist <= tdb.MaximumAllowedDistance {
  157. candidates = append(candidates, candidate{lb, la})
  158. focusedLinesBefore[lb] = true
  159. focusedLinesAfter[la] = true
  160. }
  161. }
  162. }
  163. lineNumAfter += size
  164. removedSize = 0
  165. case diffmatchpatch.DiffEqual:
  166. lineNumBefore += size
  167. lineNumAfter += size
  168. removedSize = 0
  169. }
  170. }
  171. if len(candidates) == 0 {
  172. continue
  173. }
  174. // at this point we have pairs of very similar lines
  175. // we need to build the line mappings of the identifiers before/after the change
  176. // we should keep only those which are present on those focused lines
  177. nodesAdded, nodesRemoved := tdb.xpather.Extract([]uast_items.Change{change})
  178. addedIdentifiers := map[int][]nodes.Node{}
  179. removedIdentifiers := map[int][]nodes.Node{}
  180. for _, n := range nodesAdded {
  181. pos := uast.PositionsOf(n.(nodes.Object))
  182. if pos.Start() == nil {
  183. log.Printf("repo %s commit %s file %s adds identifier %s with no position",
  184. tdb.remote, commit.String(), change.Change.To.Name,
  185. n.(nodes.Object)["Name"].(nodes.String))
  186. continue
  187. }
  188. line := int(pos.Start().Line) - 1
  189. if focusedLinesAfter[line] {
  190. addedIdentifiers[line] = append(addedIdentifiers[line], n)
  191. }
  192. }
  193. for _, n := range nodesRemoved {
  194. pos := uast.PositionsOf(n.(nodes.Object))
  195. if pos.Start() == nil {
  196. log.Printf("repo %s commit %s file %s removes identifier %s with no position",
  197. tdb.remote, commit.String(), change.Change.To.Name,
  198. n.(nodes.Object)["Name"].(nodes.String))
  199. continue
  200. }
  201. line := int(pos.Start().Line) - 1
  202. if focusedLinesBefore[line] {
  203. removedIdentifiers[line] = append(removedIdentifiers[line], n)
  204. }
  205. }
  206. for _, c := range candidates {
  207. nodesBefore := removedIdentifiers[c.Before]
  208. nodesAfter := addedIdentifiers[c.After]
  209. if len(nodesBefore) == 1 && len(nodesAfter) == 1 {
  210. idBefore := string(nodesBefore[0].(nodes.Object)["Name"].(nodes.String))
  211. idAfter := string(nodesAfter[0].(nodes.Object)["Name"].(nodes.String))
  212. tdb.typos = append(tdb.typos, Typo{
  213. Wrong: idBefore,
  214. Correct: idAfter,
  215. Commit: commit,
  216. File: change.Change.To.Name,
  217. Line: c.After,
  218. })
  219. }
  220. }
  221. }
  222. return nil, nil
  223. }
  224. // Finalize returns the result of the analysis. Further Consume() calls are not expected.
  225. func (tdb *TyposDatasetBuilder) Finalize() interface{} {
  226. // deduplicate
  227. typos := make([]Typo, 0, len(tdb.typos))
  228. pairs := map[string]bool{}
  229. for _, t := range tdb.typos {
  230. id := t.Wrong + "|" + t.Correct
  231. if _, exists := pairs[id]; !exists {
  232. pairs[id] = true
  233. typos = append(typos, t)
  234. }
  235. }
  236. return TyposResult{Typos: typos}
  237. }
  238. // Fork clones this pipeline item.
  239. func (tdb *TyposDatasetBuilder) Fork(n int) []core.PipelineItem {
  240. return core.ForkSamePipelineItem(tdb, n)
  241. }
  242. // Serialize converts the analysis result as returned by Finalize() to text or bytes.
  243. // The text format is YAML and the bytes format is Protocol Buffers.
  244. func (tdb *TyposDatasetBuilder) Serialize(result interface{}, binary bool, writer io.Writer) error {
  245. commitsResult := result.(TyposResult)
  246. if binary {
  247. return tdb.serializeBinary(&commitsResult, writer)
  248. }
  249. tdb.serializeText(&commitsResult, writer)
  250. return nil
  251. }
  252. func (tdb *TyposDatasetBuilder) serializeText(result *TyposResult, writer io.Writer) {
  253. for _, t := range result.Typos {
  254. fmt.Fprintf(writer, " - wrong: %s\n", yaml.SafeString(t.Wrong))
  255. fmt.Fprintf(writer, " correct: %s\n", yaml.SafeString(t.Correct))
  256. fmt.Fprintf(writer, " commit: %s\n", t.Commit.String())
  257. fmt.Fprintf(writer, " file: %s\n", yaml.SafeString(t.File))
  258. fmt.Fprintf(writer, " line: %d\n", t.Line)
  259. }
  260. }
  261. func (tdb *TyposDatasetBuilder) serializeBinary(result *TyposResult, writer io.Writer) error {
  262. message := pb.TyposDataset{}
  263. message.Typos = make([]*pb.Typo, len(result.Typos))
  264. for i, t := range result.Typos {
  265. message.Typos[i] = &pb.Typo{
  266. Wrong: t.Wrong,
  267. Correct: t.Correct,
  268. Commit: t.Commit.String(),
  269. File: t.File,
  270. Line: int32(t.Line),
  271. }
  272. }
  273. serialized, err := proto.Marshal(&message)
  274. if err != nil {
  275. return err
  276. }
  277. _, err = writer.Write(serialized)
  278. return err
  279. }
  280. func init() {
  281. core.Registry.Register(&TyposDatasetBuilder{})
  282. }