similar.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955
  1. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  2. # For details: https://github.com/pylint-dev/pylint/blob/main/LICENSE
  3. # Copyright (c) https://github.com/pylint-dev/pylint/blob/main/CONTRIBUTORS.txt
  4. """A similarities / code duplication command line tool and pylint checker.
  5. The algorithm is based on comparing the hash value of n successive lines of a file.
  6. First the files are read and any line that doesn't fulfill requirement are removed
  7. (comments, docstrings...)
  8. Those stripped lines are stored in the LineSet class which gives access to them.
  9. Then each index of the stripped lines collection is associated with the hash of n
  10. successive entries of the stripped lines starting at the current index (n is the
  11. minimum common lines option).
  12. The common hashes between both linesets are then looked for. If there are matches, then
  13. the match indices in both linesets are stored and associated with the corresponding
  14. couples (start line number/end line number) in both files.
  15. This association is then post-processed to handle the case of successive matches. For
  16. example if the minimum common lines setting is set to four, then the hashes are
  17. computed with four lines. If one of match indices couple (12, 34) is the
  18. successor of another one (11, 33) then it means that there are in fact five lines which
  19. are common.
  20. Once post-processed the values of association table are the result looked for, i.e.
  21. start and end lines numbers of common lines in both files.
  22. """
  23. from __future__ import annotations
  24. import argparse
  25. import copy
  26. import functools
  27. import itertools
  28. import operator
  29. import re
  30. import sys
  31. import warnings
  32. from collections import defaultdict
  33. from collections.abc import Callable, Generator, Iterable, Sequence
  34. from getopt import getopt
  35. from io import BufferedIOBase, BufferedReader, BytesIO
  36. from itertools import chain, groupby
  37. from typing import (
  38. TYPE_CHECKING,
  39. Any,
  40. Dict,
  41. List,
  42. NamedTuple,
  43. NewType,
  44. NoReturn,
  45. TextIO,
  46. Tuple,
  47. Union,
  48. )
  49. import astroid
  50. from astroid import nodes
  51. from pylint.checkers import BaseChecker, BaseRawFileChecker, table_lines_from_stats
  52. from pylint.reporters.ureports.nodes import Section, Table
  53. from pylint.typing import MessageDefinitionTuple, Options
  54. from pylint.utils import LinterStats, decoding_stream
  55. if TYPE_CHECKING:
  56. from pylint.lint import PyLinter
  57. DEFAULT_MIN_SIMILARITY_LINE = 4
  58. REGEX_FOR_LINES_WITH_CONTENT = re.compile(r".*\w+")
  59. # Index defines a location in a LineSet stripped lines collection
  60. Index = NewType("Index", int)
  61. # LineNumber defines a location in a LinesSet real lines collection (the whole file lines)
  62. LineNumber = NewType("LineNumber", int)
  63. # LineSpecifs holds characteristics of a line in a file
  64. class LineSpecifs(NamedTuple):
  65. line_number: LineNumber
  66. text: str
  67. # Links LinesChunk object to the starting indices (in lineset's stripped lines)
  68. # of the different chunk of lines that are used to compute the hash
  69. HashToIndex_T = Dict["LinesChunk", List[Index]]
  70. # Links index in the lineset's stripped lines to the real lines in the file
  71. IndexToLines_T = Dict[Index, "SuccessiveLinesLimits"]
  72. # The types the streams read by pylint can take. Originating from astroid.nodes.Module.stream() and open()
  73. STREAM_TYPES = Union[TextIO, BufferedReader, BytesIO]
  74. class CplSuccessiveLinesLimits:
  75. """Holds a SuccessiveLinesLimits object for each checked file and counts the number
  76. of common lines between both stripped lines collections extracted from both files.
  77. """
  78. __slots__ = ("first_file", "second_file", "effective_cmn_lines_nb")
  79. def __init__(
  80. self,
  81. first_file: SuccessiveLinesLimits,
  82. second_file: SuccessiveLinesLimits,
  83. effective_cmn_lines_nb: int,
  84. ) -> None:
  85. self.first_file = first_file
  86. self.second_file = second_file
  87. self.effective_cmn_lines_nb = effective_cmn_lines_nb
  88. # Links the indices to the starting line in both lineset's stripped lines to
  89. # the start and end lines in both files
  90. CplIndexToCplLines_T = Dict["LineSetStartCouple", CplSuccessiveLinesLimits]
  91. class LinesChunk:
  92. """The LinesChunk object computes and stores the hash of some consecutive stripped
  93. lines of a lineset.
  94. """
  95. __slots__ = ("_fileid", "_index", "_hash")
  96. def __init__(self, fileid: str, num_line: int, *lines: Iterable[str]) -> None:
  97. self._fileid: str = fileid
  98. """The name of the file from which the LinesChunk object is generated."""
  99. self._index: Index = Index(num_line)
  100. """The index in the stripped lines that is the starting of consecutive
  101. lines.
  102. """
  103. self._hash: int = sum(hash(lin) for lin in lines)
  104. """The hash of some consecutive lines."""
  105. def __eq__(self, o: Any) -> bool:
  106. if not isinstance(o, LinesChunk):
  107. return NotImplemented
  108. return self._hash == o._hash
  109. def __hash__(self) -> int:
  110. return self._hash
  111. def __repr__(self) -> str:
  112. return (
  113. f"<LinesChunk object for file {self._fileid} ({self._index}, {self._hash})>"
  114. )
  115. def __str__(self) -> str:
  116. return (
  117. f"LinesChunk object for file {self._fileid}, starting at line {self._index} \n"
  118. f"Hash is {self._hash}"
  119. )
  120. class SuccessiveLinesLimits:
  121. """A class to handle the numbering of begin and end of successive lines.
  122. :note: Only the end line number can be updated.
  123. """
  124. __slots__ = ("_start", "_end")
  125. def __init__(self, start: LineNumber, end: LineNumber) -> None:
  126. self._start: LineNumber = start
  127. self._end: LineNumber = end
  128. @property
  129. def start(self) -> LineNumber:
  130. return self._start
  131. @property
  132. def end(self) -> LineNumber:
  133. return self._end
  134. @end.setter
  135. def end(self, value: LineNumber) -> None:
  136. self._end = value
  137. def __repr__(self) -> str:
  138. return f"<SuccessiveLinesLimits <{self._start};{self._end}>>"
  139. class LineSetStartCouple(NamedTuple):
  140. """Indices in both linesets that mark the beginning of successive lines."""
  141. fst_lineset_index: Index
  142. snd_lineset_index: Index
  143. def __repr__(self) -> str:
  144. return (
  145. f"<LineSetStartCouple <{self.fst_lineset_index};{self.snd_lineset_index}>>"
  146. )
  147. def __eq__(self, other: Any) -> bool:
  148. if not isinstance(other, LineSetStartCouple):
  149. return NotImplemented
  150. return (
  151. self.fst_lineset_index == other.fst_lineset_index
  152. and self.snd_lineset_index == other.snd_lineset_index
  153. )
  154. def __hash__(self) -> int:
  155. return hash(self.fst_lineset_index) + hash(self.snd_lineset_index)
  156. def increment(self, value: Index) -> LineSetStartCouple:
  157. return LineSetStartCouple(
  158. Index(self.fst_lineset_index + value),
  159. Index(self.snd_lineset_index + value),
  160. )
  161. LinesChunkLimits_T = Tuple["LineSet", LineNumber, LineNumber]
  162. def hash_lineset(
  163. lineset: LineSet, min_common_lines: int = DEFAULT_MIN_SIMILARITY_LINE
  164. ) -> tuple[HashToIndex_T, IndexToLines_T]:
  165. """Return two dicts.
  166. The first associates the hash of successive stripped lines of a lineset
  167. to the indices of the starting lines.
  168. The second dict, associates the index of the starting line in the lineset's stripped lines to the
  169. couple [start, end] lines number in the corresponding file.
  170. :param lineset: lineset object (i.e the lines in a file)
  171. :param min_common_lines: number of successive lines that are used to compute the hash
  172. :return: a dict linking hashes to corresponding start index and a dict that links this
  173. index to the start and end lines in the file
  174. """
  175. hash2index = defaultdict(list)
  176. index2lines = {}
  177. # Comments, docstring and other specific patterns maybe excluded -> call to stripped_lines
  178. # to get only what is desired
  179. lines = tuple(x.text for x in lineset.stripped_lines)
  180. # Need different iterators on same lines but each one is shifted 1 from the precedent
  181. shifted_lines = [iter(lines[i:]) for i in range(min_common_lines)]
  182. for i, *succ_lines in enumerate(zip(*shifted_lines)):
  183. start_linenumber = LineNumber(lineset.stripped_lines[i].line_number)
  184. try:
  185. end_linenumber = lineset.stripped_lines[i + min_common_lines].line_number
  186. except IndexError:
  187. end_linenumber = LineNumber(lineset.stripped_lines[-1].line_number + 1)
  188. index = Index(i)
  189. index2lines[index] = SuccessiveLinesLimits(
  190. start=start_linenumber, end=end_linenumber
  191. )
  192. l_c = LinesChunk(lineset.name, index, *succ_lines)
  193. hash2index[l_c].append(index)
  194. return hash2index, index2lines
  195. def remove_successive(all_couples: CplIndexToCplLines_T) -> None:
  196. """Removes all successive entries in the dictionary in argument.
  197. :param all_couples: collection that has to be cleaned up from successive entries.
  198. The keys are couples of indices that mark the beginning of common entries
  199. in both linesets. The values have two parts. The first one is the couple
  200. of starting and ending line numbers of common successive lines in the first file.
  201. The second part is the same for the second file.
  202. For example consider the following dict:
  203. >>> all_couples
  204. {(11, 34): ([5, 9], [27, 31]),
  205. (23, 79): ([15, 19], [45, 49]),
  206. (12, 35): ([6, 10], [28, 32])}
  207. There are two successive keys (11, 34) and (12, 35).
  208. It means there are two consecutive similar chunks of lines in both files.
  209. Thus remove last entry and update the last line numbers in the first entry
  210. >>> remove_successive(all_couples)
  211. >>> all_couples
  212. {(11, 34): ([5, 10], [27, 32]),
  213. (23, 79): ([15, 19], [45, 49])}
  214. """
  215. couple: LineSetStartCouple
  216. for couple in tuple(all_couples.keys()):
  217. to_remove = []
  218. test = couple.increment(Index(1))
  219. while test in all_couples:
  220. all_couples[couple].first_file.end = all_couples[test].first_file.end
  221. all_couples[couple].second_file.end = all_couples[test].second_file.end
  222. all_couples[couple].effective_cmn_lines_nb += 1
  223. to_remove.append(test)
  224. test = test.increment(Index(1))
  225. for target in to_remove:
  226. try:
  227. all_couples.pop(target)
  228. except KeyError:
  229. pass
  230. def filter_noncode_lines(
  231. ls_1: LineSet,
  232. stindex_1: Index,
  233. ls_2: LineSet,
  234. stindex_2: Index,
  235. common_lines_nb: int,
  236. ) -> int:
  237. """Return the effective number of common lines between lineset1
  238. and lineset2 filtered from non code lines.
  239. That is to say the number of common successive stripped
  240. lines except those that do not contain code (for example
  241. a line with only an ending parenthesis)
  242. :param ls_1: first lineset
  243. :param stindex_1: first lineset starting index
  244. :param ls_2: second lineset
  245. :param stindex_2: second lineset starting index
  246. :param common_lines_nb: number of common successive stripped lines before being filtered from non code lines
  247. :return: the number of common successive stripped lines that contain code
  248. """
  249. stripped_l1 = [
  250. lspecif.text
  251. for lspecif in ls_1.stripped_lines[stindex_1 : stindex_1 + common_lines_nb]
  252. if REGEX_FOR_LINES_WITH_CONTENT.match(lspecif.text)
  253. ]
  254. stripped_l2 = [
  255. lspecif.text
  256. for lspecif in ls_2.stripped_lines[stindex_2 : stindex_2 + common_lines_nb]
  257. if REGEX_FOR_LINES_WITH_CONTENT.match(lspecif.text)
  258. ]
  259. return sum(sline_1 == sline_2 for sline_1, sline_2 in zip(stripped_l1, stripped_l2))
  260. class Commonality(NamedTuple):
  261. cmn_lines_nb: int
  262. fst_lset: LineSet
  263. fst_file_start: LineNumber
  264. fst_file_end: LineNumber
  265. snd_lset: LineSet
  266. snd_file_start: LineNumber
  267. snd_file_end: LineNumber
  268. class Similar:
  269. """Finds copy-pasted lines of code in a project."""
  270. def __init__(
  271. self,
  272. min_lines: int = DEFAULT_MIN_SIMILARITY_LINE,
  273. ignore_comments: bool = False,
  274. ignore_docstrings: bool = False,
  275. ignore_imports: bool = False,
  276. ignore_signatures: bool = False,
  277. ) -> None:
  278. # If we run in pylint mode we link the namespace objects
  279. if isinstance(self, BaseChecker):
  280. self.namespace = self.linter.config
  281. else:
  282. self.namespace = argparse.Namespace()
  283. self.namespace.min_similarity_lines = min_lines
  284. self.namespace.ignore_comments = ignore_comments
  285. self.namespace.ignore_docstrings = ignore_docstrings
  286. self.namespace.ignore_imports = ignore_imports
  287. self.namespace.ignore_signatures = ignore_signatures
  288. self.linesets: list[LineSet] = []
  289. def append_stream(
  290. self, streamid: str, stream: STREAM_TYPES, encoding: str | None = None
  291. ) -> None:
  292. """Append a file to search for similarities."""
  293. if isinstance(stream, BufferedIOBase):
  294. if encoding is None:
  295. raise ValueError
  296. readlines = decoding_stream(stream, encoding).readlines
  297. else:
  298. # hint parameter is incorrectly typed as non-optional
  299. readlines = stream.readlines # type: ignore[assignment]
  300. try:
  301. lines = readlines()
  302. except UnicodeDecodeError:
  303. lines = []
  304. self.linesets.append(
  305. LineSet(
  306. streamid,
  307. lines,
  308. self.namespace.ignore_comments,
  309. self.namespace.ignore_docstrings,
  310. self.namespace.ignore_imports,
  311. self.namespace.ignore_signatures,
  312. line_enabled_callback=self.linter._is_one_message_enabled
  313. if hasattr(self, "linter")
  314. else None,
  315. )
  316. )
  317. def run(self) -> None:
  318. """Start looking for similarities and display results on stdout."""
  319. if self.namespace.min_similarity_lines == 0:
  320. return
  321. self._display_sims(self._compute_sims())
  322. def _compute_sims(self) -> list[tuple[int, set[LinesChunkLimits_T]]]:
  323. """Compute similarities in appended files."""
  324. no_duplicates: dict[int, list[set[LinesChunkLimits_T]]] = defaultdict(list)
  325. for commonality in self._iter_sims():
  326. num = commonality.cmn_lines_nb
  327. lineset1 = commonality.fst_lset
  328. start_line_1 = commonality.fst_file_start
  329. end_line_1 = commonality.fst_file_end
  330. lineset2 = commonality.snd_lset
  331. start_line_2 = commonality.snd_file_start
  332. end_line_2 = commonality.snd_file_end
  333. duplicate = no_duplicates[num]
  334. couples: set[LinesChunkLimits_T]
  335. for couples in duplicate:
  336. if (lineset1, start_line_1, end_line_1) in couples or (
  337. lineset2,
  338. start_line_2,
  339. end_line_2,
  340. ) in couples:
  341. break
  342. else:
  343. duplicate.append(
  344. {
  345. (lineset1, start_line_1, end_line_1),
  346. (lineset2, start_line_2, end_line_2),
  347. }
  348. )
  349. sims: list[tuple[int, set[LinesChunkLimits_T]]] = []
  350. ensembles: list[set[LinesChunkLimits_T]]
  351. for num, ensembles in no_duplicates.items():
  352. cpls: set[LinesChunkLimits_T]
  353. for cpls in ensembles:
  354. sims.append((num, cpls))
  355. sims.sort()
  356. sims.reverse()
  357. return sims
  358. def _display_sims(
  359. self, similarities: list[tuple[int, set[LinesChunkLimits_T]]]
  360. ) -> None:
  361. """Display computed similarities on stdout."""
  362. report = self._get_similarity_report(similarities)
  363. print(report)
  364. def _get_similarity_report(
  365. self, similarities: list[tuple[int, set[LinesChunkLimits_T]]]
  366. ) -> str:
  367. """Create a report from similarities."""
  368. report: str = ""
  369. duplicated_line_number: int = 0
  370. for number, couples in similarities:
  371. report += f"\n{number} similar lines in {len(couples)} files\n"
  372. couples_l = sorted(couples)
  373. line_set = start_line = end_line = None
  374. for line_set, start_line, end_line in couples_l:
  375. report += f"=={line_set.name}:[{start_line}:{end_line}]\n"
  376. if line_set:
  377. for line in line_set._real_lines[start_line:end_line]:
  378. report += f" {line.rstrip()}\n" if line.rstrip() else "\n"
  379. duplicated_line_number += number * (len(couples_l) - 1)
  380. total_line_number: int = sum(len(lineset) for lineset in self.linesets)
  381. report += (
  382. f"TOTAL lines={total_line_number} "
  383. f"duplicates={duplicated_line_number} "
  384. f"percent={duplicated_line_number * 100.0 / total_line_number:.2f}\n"
  385. )
  386. return report
  387. # pylint: disable = too-many-locals
  388. def _find_common(
  389. self, lineset1: LineSet, lineset2: LineSet
  390. ) -> Generator[Commonality, None, None]:
  391. """Find similarities in the two given linesets.
  392. This the core of the algorithm. The idea is to compute the hashes of a
  393. minimal number of successive lines of each lineset and then compare the
  394. hashes. Every match of such comparison is stored in a dict that links the
  395. couple of starting indices in both linesets to the couple of corresponding
  396. starting and ending lines in both files.
  397. Last regroups all successive couples in a bigger one. It allows to take into
  398. account common chunk of lines that have more than the minimal number of
  399. successive lines required.
  400. """
  401. hash_to_index_1: HashToIndex_T
  402. hash_to_index_2: HashToIndex_T
  403. index_to_lines_1: IndexToLines_T
  404. index_to_lines_2: IndexToLines_T
  405. hash_to_index_1, index_to_lines_1 = hash_lineset(
  406. lineset1, self.namespace.min_similarity_lines
  407. )
  408. hash_to_index_2, index_to_lines_2 = hash_lineset(
  409. lineset2, self.namespace.min_similarity_lines
  410. )
  411. hash_1: frozenset[LinesChunk] = frozenset(hash_to_index_1.keys())
  412. hash_2: frozenset[LinesChunk] = frozenset(hash_to_index_2.keys())
  413. common_hashes: Iterable[LinesChunk] = sorted(
  414. hash_1 & hash_2, key=lambda m: hash_to_index_1[m][0]
  415. )
  416. # all_couples is a dict that links the couple of indices in both linesets that mark the beginning of
  417. # successive common lines, to the corresponding starting and ending number lines in both files
  418. all_couples: CplIndexToCplLines_T = {}
  419. for c_hash in sorted(common_hashes, key=operator.attrgetter("_index")):
  420. for indices_in_linesets in itertools.product(
  421. hash_to_index_1[c_hash], hash_to_index_2[c_hash]
  422. ):
  423. index_1 = indices_in_linesets[0]
  424. index_2 = indices_in_linesets[1]
  425. all_couples[
  426. LineSetStartCouple(index_1, index_2)
  427. ] = CplSuccessiveLinesLimits(
  428. copy.copy(index_to_lines_1[index_1]),
  429. copy.copy(index_to_lines_2[index_2]),
  430. effective_cmn_lines_nb=self.namespace.min_similarity_lines,
  431. )
  432. remove_successive(all_couples)
  433. for cml_stripped_l, cmn_l in all_couples.items():
  434. start_index_1 = cml_stripped_l.fst_lineset_index
  435. start_index_2 = cml_stripped_l.snd_lineset_index
  436. nb_common_lines = cmn_l.effective_cmn_lines_nb
  437. com = Commonality(
  438. cmn_lines_nb=nb_common_lines,
  439. fst_lset=lineset1,
  440. fst_file_start=cmn_l.first_file.start,
  441. fst_file_end=cmn_l.first_file.end,
  442. snd_lset=lineset2,
  443. snd_file_start=cmn_l.second_file.start,
  444. snd_file_end=cmn_l.second_file.end,
  445. )
  446. eff_cmn_nb = filter_noncode_lines(
  447. lineset1, start_index_1, lineset2, start_index_2, nb_common_lines
  448. )
  449. if eff_cmn_nb > self.namespace.min_similarity_lines:
  450. yield com
  451. def _iter_sims(self) -> Generator[Commonality, None, None]:
  452. """Iterate on similarities among all files, by making a Cartesian
  453. product.
  454. """
  455. for idx, lineset in enumerate(self.linesets[:-1]):
  456. for lineset2 in self.linesets[idx + 1 :]:
  457. yield from self._find_common(lineset, lineset2)
  458. def get_map_data(self) -> list[LineSet]:
  459. """Returns the data we can use for a map/reduce process.
  460. In this case we are returning this instance's Linesets, that is all file
  461. information that will later be used for vectorisation.
  462. """
  463. return self.linesets
  464. def combine_mapreduce_data(self, linesets_collection: list[list[LineSet]]) -> None:
  465. """Reduces and recombines data into a format that we can report on.
  466. The partner function of get_map_data()
  467. """
  468. self.linesets = [line for lineset in linesets_collection for line in lineset]
  469. def stripped_lines(
  470. lines: Iterable[str],
  471. ignore_comments: bool,
  472. ignore_docstrings: bool,
  473. ignore_imports: bool,
  474. ignore_signatures: bool,
  475. line_enabled_callback: Callable[[str, int], bool] | None = None,
  476. ) -> list[LineSpecifs]:
  477. """Return tuples of line/line number/line type with leading/trailing white-space and
  478. any ignored code features removed.
  479. :param lines: a collection of lines
  480. :param ignore_comments: if true, any comment in the lines collection is removed from the result
  481. :param ignore_docstrings: if true, any line that is a docstring is removed from the result
  482. :param ignore_imports: if true, any line that is an import is removed from the result
  483. :param ignore_signatures: if true, any line that is part of a function signature is removed from the result
  484. :param line_enabled_callback: If called with "R0801" and a line number, a return value of False will disregard
  485. the line
  486. :return: the collection of line/line number/line type tuples
  487. """
  488. if ignore_imports or ignore_signatures:
  489. tree = astroid.parse("".join(lines))
  490. if ignore_imports:
  491. node_is_import_by_lineno = (
  492. (node.lineno, isinstance(node, (nodes.Import, nodes.ImportFrom)))
  493. for node in tree.body
  494. )
  495. line_begins_import = {
  496. lineno: all(is_import for _, is_import in node_is_import_group)
  497. for lineno, node_is_import_group in groupby(
  498. node_is_import_by_lineno, key=lambda x: x[0] # type: ignore[no-any-return]
  499. )
  500. }
  501. current_line_is_import = False
  502. if ignore_signatures:
  503. def _get_functions(
  504. functions: list[nodes.NodeNG], tree: nodes.NodeNG
  505. ) -> list[nodes.NodeNG]:
  506. """Recursively get all functions including nested in the classes from the
  507. tree.
  508. """
  509. for node in tree.body:
  510. if isinstance(node, (nodes.FunctionDef, nodes.AsyncFunctionDef)):
  511. functions.append(node)
  512. if isinstance(
  513. node,
  514. (nodes.ClassDef, nodes.FunctionDef, nodes.AsyncFunctionDef),
  515. ):
  516. _get_functions(functions, node)
  517. return functions
  518. functions = _get_functions([], tree)
  519. signature_lines = set(
  520. chain(
  521. *(
  522. range(
  523. func.lineno,
  524. func.body[0].lineno if func.body else func.tolineno + 1,
  525. )
  526. for func in functions
  527. )
  528. )
  529. )
  530. strippedlines = []
  531. docstring = None
  532. for lineno, line in enumerate(lines, start=1):
  533. if line_enabled_callback is not None and not line_enabled_callback(
  534. "R0801", lineno
  535. ):
  536. continue
  537. line = line.strip()
  538. if ignore_docstrings:
  539. if not docstring:
  540. if line.startswith('"""') or line.startswith("'''"):
  541. docstring = line[:3]
  542. line = line[3:]
  543. elif line.startswith('r"""') or line.startswith("r'''"):
  544. docstring = line[1:4]
  545. line = line[4:]
  546. if docstring:
  547. if line.endswith(docstring):
  548. docstring = None
  549. line = ""
  550. if ignore_imports:
  551. current_line_is_import = line_begins_import.get(
  552. lineno, current_line_is_import
  553. )
  554. if current_line_is_import:
  555. line = ""
  556. if ignore_comments:
  557. line = line.split("#", 1)[0].strip()
  558. if ignore_signatures and lineno in signature_lines:
  559. line = ""
  560. if line:
  561. strippedlines.append(
  562. LineSpecifs(text=line, line_number=LineNumber(lineno - 1))
  563. )
  564. return strippedlines
  565. @functools.total_ordering
  566. class LineSet:
  567. """Holds and indexes all the lines of a single source file.
  568. Allows for correspondence between real lines of the source file and stripped ones, which
  569. are the real ones from which undesired patterns have been removed.
  570. """
  571. def __init__(
  572. self,
  573. name: str,
  574. lines: list[str],
  575. ignore_comments: bool = False,
  576. ignore_docstrings: bool = False,
  577. ignore_imports: bool = False,
  578. ignore_signatures: bool = False,
  579. line_enabled_callback: Callable[[str, int], bool] | None = None,
  580. ) -> None:
  581. self.name = name
  582. self._real_lines = lines
  583. self._stripped_lines = stripped_lines(
  584. lines,
  585. ignore_comments,
  586. ignore_docstrings,
  587. ignore_imports,
  588. ignore_signatures,
  589. line_enabled_callback=line_enabled_callback,
  590. )
  591. def __str__(self) -> str:
  592. return f"<Lineset for {self.name}>"
  593. def __len__(self) -> int:
  594. return len(self._real_lines)
  595. def __getitem__(self, index: int) -> LineSpecifs:
  596. return self._stripped_lines[index]
  597. def __lt__(self, other: LineSet) -> bool:
  598. return self.name < other.name
  599. def __hash__(self) -> int:
  600. return id(self)
  601. def __eq__(self, other: Any) -> bool:
  602. if not isinstance(other, LineSet):
  603. return False
  604. return self.__dict__ == other.__dict__
  605. @property
  606. def stripped_lines(self) -> list[LineSpecifs]:
  607. return self._stripped_lines
  608. @property
  609. def real_lines(self) -> list[str]:
  610. return self._real_lines
  611. MSGS: dict[str, MessageDefinitionTuple] = {
  612. "R0801": (
  613. "Similar lines in %s files\n%s",
  614. "duplicate-code",
  615. "Indicates that a set of similar lines has been detected "
  616. "among multiple file. This usually means that the code should "
  617. "be refactored to avoid this duplication.",
  618. )
  619. }
  620. def report_similarities(
  621. sect: Section,
  622. stats: LinterStats,
  623. old_stats: LinterStats | None,
  624. ) -> None:
  625. """Make a layout with some stats about duplication."""
  626. lines = ["", "now", "previous", "difference"]
  627. lines += table_lines_from_stats(stats, old_stats, "duplicated_lines")
  628. sect.append(Table(children=lines, cols=4, rheaders=1, cheaders=1))
  629. # wrapper to get a pylint checker from the similar class
  630. class SimilarChecker(BaseRawFileChecker, Similar):
  631. """Checks for similarities and duplicated code.
  632. This computation may be memory / CPU intensive, so you
  633. should disable it if you experience some problems.
  634. """
  635. # configuration section name
  636. name = "similarities"
  637. # messages
  638. msgs = MSGS
  639. # configuration options
  640. # for available dict keys/values see the optik parser 'add_option' method
  641. options: Options = (
  642. (
  643. "min-similarity-lines",
  644. {
  645. "default": DEFAULT_MIN_SIMILARITY_LINE,
  646. "type": "int",
  647. "metavar": "<int>",
  648. "help": "Minimum lines number of a similarity.",
  649. },
  650. ),
  651. (
  652. "ignore-comments",
  653. {
  654. "default": True,
  655. "type": "yn",
  656. "metavar": "<y or n>",
  657. "help": "Comments are removed from the similarity computation",
  658. },
  659. ),
  660. (
  661. "ignore-docstrings",
  662. {
  663. "default": True,
  664. "type": "yn",
  665. "metavar": "<y or n>",
  666. "help": "Docstrings are removed from the similarity computation",
  667. },
  668. ),
  669. (
  670. "ignore-imports",
  671. {
  672. "default": True,
  673. "type": "yn",
  674. "metavar": "<y or n>",
  675. "help": "Imports are removed from the similarity computation",
  676. },
  677. ),
  678. (
  679. "ignore-signatures",
  680. {
  681. "default": True,
  682. "type": "yn",
  683. "metavar": "<y or n>",
  684. "help": "Signatures are removed from the similarity computation",
  685. },
  686. ),
  687. )
  688. # reports
  689. reports = (("RP0801", "Duplication", report_similarities),)
  690. def __init__(self, linter: PyLinter) -> None:
  691. BaseRawFileChecker.__init__(self, linter)
  692. Similar.__init__(
  693. self,
  694. min_lines=self.linter.config.min_similarity_lines,
  695. ignore_comments=self.linter.config.ignore_comments,
  696. ignore_docstrings=self.linter.config.ignore_docstrings,
  697. ignore_imports=self.linter.config.ignore_imports,
  698. ignore_signatures=self.linter.config.ignore_signatures,
  699. )
  700. def open(self) -> None:
  701. """Init the checkers: reset linesets and statistics information."""
  702. self.linesets = []
  703. self.linter.stats.reset_duplicated_lines()
  704. def process_module(self, node: nodes.Module) -> None:
  705. """Process a module.
  706. the module's content is accessible via the stream object
  707. stream must implement the readlines method
  708. """
  709. if self.linter.current_name is None:
  710. warnings.warn(
  711. (
  712. "In pylint 3.0 the current_name attribute of the linter object should be a string. "
  713. "If unknown it should be initialized as an empty string."
  714. ),
  715. DeprecationWarning,
  716. )
  717. with node.stream() as stream:
  718. self.append_stream(self.linter.current_name, stream, node.file_encoding) # type: ignore[arg-type]
  719. def close(self) -> None:
  720. """Compute and display similarities on closing (i.e. end of parsing)."""
  721. total = sum(len(lineset) for lineset in self.linesets)
  722. duplicated = 0
  723. stats = self.linter.stats
  724. for num, couples in self._compute_sims():
  725. msg = []
  726. lineset = start_line = end_line = None
  727. for lineset, start_line, end_line in couples:
  728. msg.append(f"=={lineset.name}:[{start_line}:{end_line}]")
  729. msg.sort()
  730. if lineset:
  731. for line in lineset.real_lines[start_line:end_line]:
  732. msg.append(line.rstrip())
  733. self.add_message("R0801", args=(len(couples), "\n".join(msg)))
  734. duplicated += num * (len(couples) - 1)
  735. stats.nb_duplicated_lines += int(duplicated)
  736. stats.percent_duplicated_lines += float(total and duplicated * 100.0 / total)
  737. def get_map_data(self) -> list[LineSet]:
  738. """Passthru override."""
  739. return Similar.get_map_data(self)
  740. def reduce_map_data(self, linter: PyLinter, data: list[list[LineSet]]) -> None:
  741. """Reduces and recombines data into a format that we can report on.
  742. The partner function of get_map_data()
  743. """
  744. Similar.combine_mapreduce_data(self, linesets_collection=data)
  745. def register(linter: PyLinter) -> None:
  746. linter.register_checker(SimilarChecker(linter))
  747. def usage(status: int = 0) -> NoReturn:
  748. """Display command line usage information."""
  749. print("finds copy pasted blocks in a set of files")
  750. print()
  751. print(
  752. "Usage: symilar [-d|--duplicates min_duplicated_lines] \
  753. [-i|--ignore-comments] [--ignore-docstrings] [--ignore-imports] [--ignore-signatures] file1..."
  754. )
  755. sys.exit(status)
  756. def Run(argv: Sequence[str] | None = None) -> NoReturn:
  757. """Standalone command line access point."""
  758. if argv is None:
  759. argv = sys.argv[1:]
  760. s_opts = "hdi"
  761. l_opts = [
  762. "help",
  763. "duplicates=",
  764. "ignore-comments",
  765. "ignore-imports",
  766. "ignore-docstrings",
  767. "ignore-signatures",
  768. ]
  769. min_lines = DEFAULT_MIN_SIMILARITY_LINE
  770. ignore_comments = False
  771. ignore_docstrings = False
  772. ignore_imports = False
  773. ignore_signatures = False
  774. opts, args = getopt(list(argv), s_opts, l_opts)
  775. for opt, val in opts:
  776. if opt in {"-d", "--duplicates"}:
  777. min_lines = int(val)
  778. elif opt in {"-h", "--help"}:
  779. usage()
  780. elif opt in {"-i", "--ignore-comments"}:
  781. ignore_comments = True
  782. elif opt in {"--ignore-docstrings"}:
  783. ignore_docstrings = True
  784. elif opt in {"--ignore-imports"}:
  785. ignore_imports = True
  786. elif opt in {"--ignore-signatures"}:
  787. ignore_signatures = True
  788. if not args:
  789. usage(1)
  790. sim = Similar(
  791. min_lines, ignore_comments, ignore_docstrings, ignore_imports, ignore_signatures
  792. )
  793. for filename in args:
  794. with open(filename, encoding="utf-8") as stream:
  795. sim.append_stream(filename, stream)
  796. sim.run()
  797. sys.exit(0)
  798. if __name__ == "__main__":
  799. Run()