symilar.py 33 KB

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