typos.go 11 KB

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