mirror of
https://github.com/unclebob/dryer.git
synced 2026-11-26 18:58:51 +00:00
Merge pull request #29 from unclebob/cursor/swift-language-support-e0b5
Add Swift as a supported language
This commit is contained in:
@@ -1,8 +1,8 @@
|
||||
# dryer
|
||||
|
||||
dryer finds candidate duplicate code in Clojure, Java, Go, TypeScript, Rust, and Python. One run detects the language of each source file, normalizes that language's forms, and reports pairs whose structure is close enough to review.
|
||||
dryer finds candidate duplicate code in Clojure, Java, Go, TypeScript, Rust, Python, and Swift. One run detects the language of each source file, normalizes that language's forms, and reports pairs whose structure is close enough to review.
|
||||
|
||||
Clojure follows [dry4clj](https://github.com/unclebob/dry4clj). The other languages use the same idea on the functions and methods [crapper](https://github.com/unclebob/crapper) and [mutator](https://github.com/unclebob/mutator) already treat as one unit. A form is only compared with forms written in the same language.
|
||||
Clojure follows [dry4clj](https://github.com/unclebob/dry4clj). Java, Go, TypeScript, Rust, and Python use the same idea on the functions and methods [crapper](https://github.com/unclebob/crapper) and [mutator](https://github.com/unclebob/mutator) already treat as one unit. Swift uses that same unit. A form is only compared with forms written in the same language.
|
||||
|
||||
The score is Jaccard similarity of structural fingerprints:
|
||||
|
||||
@@ -39,6 +39,13 @@ def beta(items):
|
||||
return map(kept, dec)
|
||||
```
|
||||
|
||||
```swift
|
||||
func alpha(xs: [Int]) -> [Int] {
|
||||
let ys = filter(xs, odd)
|
||||
return map(ys, inc)
|
||||
}
|
||||
```
|
||||
|
||||
What stays is the call or method name, the operator, and the shape of the tree. What drops out is the local name, the field name, the literal, and the keyword. A Clojure keyword call `(:kind m)` and `(:id row)` is the same shape. So is `order.total` and `row.amount`.
|
||||
|
||||
## Run
|
||||
@@ -101,6 +108,9 @@ DUPLICATE score=0.89
|
||||
| TypeScript | functions, methods, and top-level arrow functions | callbacks nested inside another function |
|
||||
| Rust | functions and methods with a body | functions inside `mod tests`, and closures |
|
||||
| Python | functions and methods | functions nested inside another function |
|
||||
| Swift | functions and methods with a body, computed properties, and file-level closures | initializers, subscripts, protocol requirements, and closures or functions nested inside another form |
|
||||
|
||||
A Swift computed property includes a SwiftUI `body`. A method on a struct, class, actor, enum, or extension is a candidate, and so is a deinit and a protocol method that has a default body. A protocol requirement does not. A closure written inside a function stays in that function. A closure bound with `let` or `var` at file scope is its own candidate, as a top-level arrow function is in TypeScript. Argument labels stay, including the label of a trailing closure, because in Swift they are part of the call. `>=`, `!=`, `...`, and `..<` stay. Locals, field names, and literals, including `nil`, do not. An interpolated string keeps the interpolation.
|
||||
|
||||
Clojure reader conditionals keep the `:clj` branch, as dry4clj does. Syntax-quote is kept as a `syntax-quote` form rather than expanded.
|
||||
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
[project]
|
||||
name = "dryer"
|
||||
version = "0.1.0"
|
||||
description = "Structural duplicate finder for Clojure, Java, Go, TypeScript, Rust, and Python."
|
||||
description = "Structural duplicate finder for Clojure, Java, Go, TypeScript, Rust, Python, and Swift."
|
||||
readme = "README.md"
|
||||
license = { file = "LICENSE" }
|
||||
classifiers = ["License :: OSI Approved :: Zero-Clause BSD (0BSD)"]
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
"""Find structural duplicates in Clojure, Java, Go, TypeScript, Rust, and Python."""
|
||||
"""Find structural duplicates in Clojure, Java, Go, TypeScript, Rust, Python, and Swift."""
|
||||
|
||||
__version__ = "0.1.0"
|
||||
|
||||
+48
-9
@@ -18,6 +18,7 @@ _SKIP = {
|
||||
"block_comment",
|
||||
"documentation_comment",
|
||||
"doc_comment",
|
||||
"multiline_comment",
|
||||
}
|
||||
|
||||
_IDENTIFIERS = {
|
||||
@@ -28,6 +29,7 @@ _IDENTIFIERS = {
|
||||
"shorthand_property_identifier",
|
||||
"shorthand_property_identifier_pattern",
|
||||
"package_identifier",
|
||||
"simple_identifier",
|
||||
}
|
||||
|
||||
_LITERALS = {
|
||||
@@ -62,6 +64,10 @@ _LITERALS = {
|
||||
"template_string",
|
||||
"regex",
|
||||
"regex_literal",
|
||||
"line_string_literal",
|
||||
"multi_line_string_literal",
|
||||
"nil_literal",
|
||||
"real_literal",
|
||||
}
|
||||
|
||||
_OPERATORS = {
|
||||
@@ -111,6 +117,8 @@ _OPERATORS = {
|
||||
":=",
|
||||
"=>",
|
||||
"?",
|
||||
"...",
|
||||
"..<",
|
||||
}
|
||||
|
||||
_CALLS = {
|
||||
@@ -127,14 +135,21 @@ _ATTRIBUTES = {
|
||||
"selector_expression",
|
||||
"field_access",
|
||||
"field_expression",
|
||||
"navigation_expression",
|
||||
}
|
||||
|
||||
# The spelling is the structure: Swift spells >= as custom_operator, and an
|
||||
# argument label is part of the call name. A trailing closure's label is an
|
||||
# identifier placed directly on the call_suffix, not a value_argument_label.
|
||||
_TEXT_SYMBOLS = {"custom_operator", "value_argument_label"}
|
||||
_INTERPOLATED = {"interpolation", "interpolated_expression"}
|
||||
|
||||
_SCOPED = {
|
||||
"scoped_identifier",
|
||||
"scoped_type_identifier",
|
||||
}
|
||||
|
||||
_ARG_LISTS = {"argument_list", "arguments"}
|
||||
_ARG_LISTS = {"argument_list", "arguments", "call_suffix"}
|
||||
_TYPE_ARGS = {"type_arguments", "type_parameters"}
|
||||
|
||||
_DATA: bytes = b""
|
||||
@@ -158,9 +173,7 @@ _PENDING = object()
|
||||
def _is_literal(node) -> bool:
|
||||
if node.type not in _LITERALS:
|
||||
return False
|
||||
if node.type == "string" and any(child.type == "interpolation" for child in node.children):
|
||||
return False
|
||||
return True
|
||||
return not any(child.type in _INTERPOLATED for child in node.children)
|
||||
|
||||
|
||||
def _named_before_args(node):
|
||||
@@ -194,6 +207,13 @@ def _named_leaf(node, head: bool):
|
||||
return _PENDING
|
||||
|
||||
|
||||
def _trailing_label(node) -> bool:
|
||||
"""A trailing-closure label sits on the call, so its spelling stays."""
|
||||
|
||||
parent = node.parent
|
||||
return parent is not None and parent.type == "call_suffix" and node.type in _IDENTIFIERS
|
||||
|
||||
|
||||
def _try_leaf(node, mode: str, head: bool):
|
||||
if mode == "callee":
|
||||
return _callee_leaf(node)
|
||||
@@ -203,6 +223,8 @@ def _try_leaf(node, mode: str, head: bool):
|
||||
return None
|
||||
if node.type in _OPERATORS:
|
||||
return [K("symbol"), node.type]
|
||||
if node.type in _TEXT_SYMBOLS or _trailing_label(node):
|
||||
return [K("symbol"), _text(node)]
|
||||
if not node.is_named:
|
||||
return None
|
||||
return _named_leaf(node, head)
|
||||
@@ -222,11 +244,29 @@ def _call_jobs(node):
|
||||
return jobs
|
||||
|
||||
|
||||
def _attr_jobs(node, head: bool):
|
||||
def _member_name(node):
|
||||
"""Swift wraps the member in navigation_suffix. The name inside is the member."""
|
||||
|
||||
if node.type != "navigation_suffix":
|
||||
return node
|
||||
for child in node.named_children:
|
||||
if child.type in _IDENTIFIERS:
|
||||
return child
|
||||
return node
|
||||
|
||||
|
||||
def _attr_ends(node):
|
||||
named = list(node.named_children)
|
||||
if not named:
|
||||
return []
|
||||
return [], None
|
||||
*objects, name = named
|
||||
return objects, _member_name(name)
|
||||
|
||||
|
||||
def _attr_jobs(node, head: bool):
|
||||
objects, name = _attr_ends(node)
|
||||
if name is None:
|
||||
return []
|
||||
jobs = [(obj, "norm", False) for obj in objects]
|
||||
if name.type in _IDENTIFIERS:
|
||||
return jobs
|
||||
@@ -306,10 +346,9 @@ def _assemble_call(node, cache):
|
||||
|
||||
|
||||
def _assemble_attr(node, head: bool, cache):
|
||||
named = list(node.named_children)
|
||||
if not named:
|
||||
objects, name = _attr_ends(node)
|
||||
if name is None:
|
||||
return [K(node.type)]
|
||||
*objects, name = named
|
||||
parts = [K(node.type)]
|
||||
for obj in objects:
|
||||
norm = cache[(id(obj), "norm", False)]
|
||||
|
||||
+12
-14
@@ -21,16 +21,16 @@ def _skipped_directory_text() -> str:
|
||||
HELP = f"""\
|
||||
Usage: dryer [options] [path-or-filter ...]
|
||||
|
||||
Find candidate duplicate code in Clojure, Java, Go, TypeScript, Rust, and
|
||||
Python. Each form is normalized — call and method names, operators, and
|
||||
tree shape stay; local names, field names, and literals do not — and compared
|
||||
with the other forms of the same language. The score is Jaccard similarity of
|
||||
those structural fingerprints, the same score as dry4clj.
|
||||
Find candidate duplicate code in Clojure, Java, Go, TypeScript, Rust,
|
||||
Python, and Swift. Each form is normalized — call and method names, operators,
|
||||
and tree shape stay; local names, field names, and literals do not — and
|
||||
compared with the other forms of the same language. The score is Jaccard
|
||||
similarity of those structural fingerprints, the same score as dry4clj.
|
||||
|
||||
Prints a report and writes .metrics/dry.edn.
|
||||
|
||||
Languages: Clojure (.clj .cljc .cljs .cljd .bb), Java (.java), Go (.go),
|
||||
TypeScript (.ts .tsx .mts .cts), Rust (.rs), Python (.py).
|
||||
TypeScript (.ts .tsx .mts .cts), Rust (.rs), Python (.py), Swift (.swift).
|
||||
|
||||
Options:
|
||||
-h, --help Print this help and exit.
|
||||
@@ -56,10 +56,12 @@ Arguments:
|
||||
|
||||
With no paths, source files under the project root are compared. Directories
|
||||
named {_skipped_directory_text()} are skipped, as are *_test.go, *.test.cts,
|
||||
*.spec.cts, *.spec.ts, test_*.py, and *_test.py files.
|
||||
*.spec.cts, *.spec.ts, test_*.py, *_test.py, and *Tests.swift files.
|
||||
|
||||
Clojure compares every top-level form except ns. The other languages compare
|
||||
functions and methods. A form is only compared with forms in the same language.
|
||||
functions and methods. Swift also compares computed properties, including a
|
||||
SwiftUI view body, a closure bound at file scope, and deinit. A form is only compared
|
||||
with forms in the same language.
|
||||
|
||||
Exit codes:
|
||||
0 the report was written
|
||||
@@ -176,12 +178,8 @@ class GitStatusError(Exception):
|
||||
|
||||
|
||||
def _git(root: Path, *args: str) -> bytes:
|
||||
result = subprocess.run(
|
||||
["git", "-C", os.fspath(root), *args],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
check=False,
|
||||
)
|
||||
command = ["git", "-C", os.fspath(root), *args]
|
||||
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False)
|
||||
if result.returncode != 0:
|
||||
message = os.fsdecode(result.stderr).strip() or "git status failed"
|
||||
raise GitStatusError(result.returncode, message)
|
||||
|
||||
+25
-21
@@ -1,7 +1,7 @@
|
||||
"""Find source files and decide which language each one is written in.
|
||||
|
||||
The extensions and the skipped directories match crapper and mutator, with
|
||||
`.cljd` added because dry4clj reads it.
|
||||
`.cljd` added because dry4clj reads it and `.swift` added for Swift.
|
||||
"""
|
||||
|
||||
import os
|
||||
@@ -21,6 +21,7 @@ EXTENSIONS = {
|
||||
".cts": "typescript",
|
||||
".rs": "rust",
|
||||
".py": "python",
|
||||
".swift": "swift",
|
||||
}
|
||||
|
||||
SKIP_DIRS = {
|
||||
@@ -43,7 +44,27 @@ SKIP_DIRS = {
|
||||
".clj-kondo",
|
||||
}
|
||||
|
||||
TEST_DIRS = {"test", "tests", "spec", "specs", "__tests__"}
|
||||
TEST_DIRS = {"test", "tests", "spec", "specs", "__tests__", "Tests"}
|
||||
|
||||
# One suffix list. Swift packages name XCTest files *Tests.swift.
|
||||
_TEST_SUFFIXES = (
|
||||
"_test.go",
|
||||
"_test.clj",
|
||||
"_test.cljc",
|
||||
"_test.cljs",
|
||||
"_test.cljd",
|
||||
"_test.bb",
|
||||
".test.ts",
|
||||
".spec.ts",
|
||||
".test.tsx",
|
||||
".spec.tsx",
|
||||
".test.mts",
|
||||
".spec.mts",
|
||||
".test.cts",
|
||||
".spec.cts",
|
||||
"_test.py",
|
||||
"Tests.swift",
|
||||
)
|
||||
|
||||
|
||||
def language_of(path: str | Path) -> str | None:
|
||||
@@ -57,26 +78,9 @@ def language_of(path: str | Path) -> str | None:
|
||||
def is_test_file(path: str | Path) -> bool:
|
||||
file_path = Path(path)
|
||||
name = file_path.name
|
||||
if name.endswith("_test.go"):
|
||||
if name == "conftest.py" or name.endswith(_TEST_SUFFIXES):
|
||||
return True
|
||||
if name.endswith(("_test.clj", "_test.cljc", "_test.cljs", "_test.cljd", "_test.bb")):
|
||||
return True
|
||||
if name.endswith(
|
||||
(
|
||||
".test.ts",
|
||||
".spec.ts",
|
||||
".test.tsx",
|
||||
".spec.tsx",
|
||||
".test.mts",
|
||||
".spec.mts",
|
||||
".test.cts",
|
||||
".spec.cts",
|
||||
)
|
||||
):
|
||||
return True
|
||||
if name == "conftest.py":
|
||||
return True
|
||||
if name.endswith("_test.py") or (name.startswith("test_") and name.endswith(".py")):
|
||||
if name.startswith("test_") and name.endswith(".py"):
|
||||
return True
|
||||
return any(part in TEST_DIRS for part in file_path.parts)
|
||||
|
||||
|
||||
+36
-1
@@ -3,7 +3,8 @@
|
||||
Clojure compares every top-level list except `ns`, matching dry4clj. The other
|
||||
languages compare the functions and methods crapper scores: bodies, not
|
||||
signatures alone, and not callbacks nested inside another function. Rust
|
||||
functions inside `mod tests` are test code and are skipped.
|
||||
functions inside `mod tests` are test code and are skipped. Swift also
|
||||
compares computed properties, a closure bound at file scope, and deinit.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -130,6 +131,39 @@ def _typescript_nodes(data: bytes, root) -> list:
|
||||
return found
|
||||
|
||||
|
||||
# A closure, a local function, and a function written inside a view body or a
|
||||
# deinit stay inside the form that contains them. A protocol requirement has
|
||||
# no body. deinit itself is a method with a body.
|
||||
_SWIFT_NEST = {
|
||||
"function_declaration",
|
||||
"protocol_function_declaration",
|
||||
"lambda_literal",
|
||||
"computed_property",
|
||||
"init_declaration",
|
||||
"subscript_declaration",
|
||||
"deinit_declaration",
|
||||
}
|
||||
_SWIFT_FUNCTION = {"function_declaration", "deinit_declaration"}
|
||||
|
||||
|
||||
def _swift_property(node) -> bool:
|
||||
return node.type == "property_declaration" and _has(node, "computed_property", "lambda_literal")
|
||||
|
||||
|
||||
def _swift_nodes(data: bytes, root) -> list:
|
||||
found = []
|
||||
for node in descendants(root):
|
||||
if _inside(node, _SWIFT_NEST):
|
||||
continue
|
||||
if node.type in _SWIFT_FUNCTION:
|
||||
found.append(node)
|
||||
elif node.type == "protocol_function_declaration" and _has(node, "statements"):
|
||||
found.append(node)
|
||||
elif _swift_property(node):
|
||||
found.append(node)
|
||||
return found
|
||||
|
||||
|
||||
def _rust_nodes(data: bytes, root) -> list:
|
||||
found = []
|
||||
for node in descendants(root):
|
||||
@@ -149,6 +183,7 @@ _PICKERS = {
|
||||
"python": ("python", _python_nodes),
|
||||
"typescript": (_grammar, _typescript_nodes),
|
||||
"rust": ("rust", _rust_nodes),
|
||||
"swift": ("swift", _swift_nodes),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -40,6 +40,8 @@ def test_help_does_not_scan(capsys):
|
||||
assert "Usage: dryer" in out
|
||||
assert "__pycache__" in out
|
||||
assert ".test.cts" in out
|
||||
assert "Swift (.swift)" in out
|
||||
assert "*Tests.swift" in out
|
||||
assert "--threshold" in out
|
||||
|
||||
|
||||
@@ -330,6 +332,14 @@ def test_changed_source_skips_unknown_and_test_files(tmp_path):
|
||||
assert _tracked_source(tmp_path / "target" / "app.py") is False
|
||||
|
||||
|
||||
def test_a_file_outside_the_project_root_is_not_source(tmp_path):
|
||||
outside = tmp_path / "outside.py"
|
||||
outside.write_text("x = 1\n", encoding="utf-8")
|
||||
root = tmp_path / "project"
|
||||
root.mkdir()
|
||||
assert _tracked_source(outside, root) is False
|
||||
|
||||
|
||||
def test_test_files_and_skipped_directories_are_left_out(tmp_path):
|
||||
write_source(tmp_path, "src/app.py", "x = 1\n")
|
||||
write_source(tmp_path, "src/foo_test.py", "x = 1\n")
|
||||
|
||||
+34
-3
@@ -126,6 +126,18 @@ def test_each_language_matches_renamed_locals(tmp_path):
|
||||
"right.tsx": TSX_RIGHT,
|
||||
"left.rs": RUST_LEFT,
|
||||
"right.rs": RUST_RIGHT,
|
||||
"left.swift": """\
|
||||
func alpha(xs: [Int]) -> [Int] {
|
||||
let ys = filter(xs, odd)
|
||||
return map(ys, inc)
|
||||
}
|
||||
""",
|
||||
"right.swift": """\
|
||||
func beta(items: [Int]) -> [Int] {
|
||||
let kept = filter(items, even)
|
||||
return map(kept, dec)
|
||||
}
|
||||
""",
|
||||
}
|
||||
for name, source in samples.items():
|
||||
write_source(tmp_path, name, source)
|
||||
@@ -133,7 +145,7 @@ def test_each_language_matches_renamed_locals(tmp_path):
|
||||
by_language = {}
|
||||
for item in found:
|
||||
by_language.setdefault(item.language, []).append(item)
|
||||
assert set(by_language) == {"java", "go", "python", "typescript", "rust"}
|
||||
assert set(by_language) == {"java", "go", "python", "typescript", "rust", "swift"}
|
||||
assert [(item.left.file, item.right.file) for item in by_language["typescript"]] == [
|
||||
("left.ts", "right.ts"),
|
||||
("left.tsx", "right.tsx"),
|
||||
@@ -237,7 +249,14 @@ class Right {
|
||||
|
||||
|
||||
def _suffix(language: str) -> str:
|
||||
return {"python": "py", "go": "go", "rust": "rs", "java": "java", "typescript": "ts"}[language]
|
||||
return {
|
||||
"python": "py",
|
||||
"go": "go",
|
||||
"rust": "rs",
|
||||
"java": "java",
|
||||
"typescript": "ts",
|
||||
"swift": "swift",
|
||||
}[language]
|
||||
|
||||
|
||||
def test_callee_names_stay_and_member_names_do_not(tmp_path):
|
||||
@@ -307,6 +326,18 @@ export function alpha(xs: number[]): number {
|
||||
export function beta(items: number[]): number {
|
||||
return foo<number>(items.baz);
|
||||
}
|
||||
""",
|
||||
"left.swift": """\
|
||||
func alpha(xs: Order) -> Int {
|
||||
let ys = xs.filter(odd)
|
||||
return xs.total
|
||||
}
|
||||
""",
|
||||
"right.swift": """\
|
||||
func beta(items: Order) -> Int {
|
||||
let kept = items.filter(even)
|
||||
return items.count
|
||||
}
|
||||
""",
|
||||
}
|
||||
for name, source in samples.items():
|
||||
@@ -315,7 +346,7 @@ export function beta(items: number[]): number {
|
||||
by_language = {}
|
||||
for item in found:
|
||||
by_language.setdefault(item.language, []).append(item)
|
||||
assert set(by_language) == {"python", "go", "rust", "java", "typescript"}
|
||||
assert set(by_language) == {"python", "go", "rust", "java", "typescript", "swift"}
|
||||
for language, group in by_language.items():
|
||||
assert [(item.left.file, item.right.file, item.score) for item in group] == [
|
||||
(f"left.{_suffix(language)}", f"right.{_suffix(language)}", 1.0)
|
||||
|
||||
@@ -0,0 +1,623 @@
|
||||
from pathlib import Path
|
||||
|
||||
from dryer.cli import run
|
||||
from dryer.discover import iter_source_files, language_of
|
||||
from dryer.extract import entries_in_source
|
||||
from dryer.scan import find_duplicates, scan_files
|
||||
|
||||
|
||||
def write_source(root: Path, name: str, text: str) -> None:
|
||||
path = root / name
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(text, encoding="utf-8")
|
||||
|
||||
|
||||
def pairs(root: Path):
|
||||
files = sorted(path for path in root.rglob("*") if path.is_file())
|
||||
entries, warnings = scan_files(files, root, min_lines=1, min_nodes=1)
|
||||
assert warnings == []
|
||||
return find_duplicates(entries, threshold=0.99)
|
||||
|
||||
|
||||
SWIFT_LEFT = """\
|
||||
func alpha(xs: [Int]) -> [Int] {
|
||||
let ys = filter(xs, odd)
|
||||
return map(ys, inc)
|
||||
}
|
||||
"""
|
||||
|
||||
SWIFT_RIGHT = """\
|
||||
func beta(items: [Int]) -> [Int] {
|
||||
let kept = filter(items, even)
|
||||
return map(kept, dec)
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def test_renamed_locals_in_swift_functions_match(tmp_path):
|
||||
write_source(tmp_path, "left.swift", SWIFT_LEFT)
|
||||
write_source(tmp_path, "right.swift", SWIFT_RIGHT)
|
||||
found = pairs(tmp_path)
|
||||
assert [(item.language, item.left.file, item.right.file, item.score) for item in found] == [
|
||||
("swift", "left.swift", "right.swift", 1.0)
|
||||
]
|
||||
|
||||
|
||||
def test_a_different_swift_callee_is_not_the_same_structure(tmp_path):
|
||||
write_source(tmp_path, "left.swift", SWIFT_LEFT)
|
||||
write_source(
|
||||
tmp_path,
|
||||
"right.swift",
|
||||
"""\
|
||||
func beta(items: [Int]) -> [Int] {
|
||||
let kept = select(items, even)
|
||||
return collect(kept, dec)
|
||||
}
|
||||
""",
|
||||
)
|
||||
files = sorted(tmp_path.glob("*.swift"))
|
||||
entries, warnings = scan_files(files, tmp_path, min_lines=1, min_nodes=1)
|
||||
assert warnings == []
|
||||
found = find_duplicates(entries, threshold=0.0)
|
||||
assert len(found) == 1
|
||||
assert found[0].score < 1.0
|
||||
|
||||
|
||||
def _scored(tmp_path, left: str, right: str) -> float:
|
||||
write_source(tmp_path, "left.swift", left)
|
||||
write_source(tmp_path, "right.swift", right)
|
||||
files = sorted(tmp_path.glob("*.swift"))
|
||||
entries, warnings = scan_files(files, tmp_path, min_lines=1, min_nodes=1)
|
||||
assert warnings == []
|
||||
found = find_duplicates(entries, threshold=0.0)
|
||||
assert len(found) == 1
|
||||
return found[0].score
|
||||
|
||||
|
||||
def test_a_swift_method_name_stays_and_the_field_name_does_not(tmp_path):
|
||||
assert _scored(
|
||||
tmp_path,
|
||||
"func alpha(xs: Order) -> Int {\n return xs.total\n}\n",
|
||||
"func beta(items: Order) -> Int {\n return items.count\n}\n",
|
||||
) == 1.0
|
||||
assert _scored(
|
||||
tmp_path,
|
||||
"func alpha(xs: Order) -> [Int] {\n return xs.filter(odd)\n}\n",
|
||||
"func beta(items: Order) -> [Int] {\n return items.select(even)\n}\n",
|
||||
) < 1.0
|
||||
assert _scored(
|
||||
tmp_path,
|
||||
"func alpha(pair: (Int, Int)) -> Int {\n return pair.0\n}\n",
|
||||
"func beta(pair: (Int, Int)) -> Int {\n return pair.1\n}\n",
|
||||
) == 1.0
|
||||
|
||||
|
||||
def test_a_different_swift_operator_lowers_the_score(tmp_path):
|
||||
assert _scored(
|
||||
tmp_path,
|
||||
"func alpha(xs: Int) -> Bool {\n return xs >= 1\n}\n",
|
||||
"func beta(items: Int) -> Bool {\n return items >= 2\n}\n",
|
||||
) == 1.0
|
||||
assert _scored(
|
||||
tmp_path,
|
||||
"func alpha(xs: Int) -> Bool {\n return xs >= 1\n}\n",
|
||||
"func beta(items: Int) -> Bool {\n return items != 1\n}\n",
|
||||
) < 1.0
|
||||
|
||||
|
||||
def test_a_different_swift_range_lowers_the_score(tmp_path):
|
||||
assert _scored(
|
||||
tmp_path,
|
||||
"func alpha(xs: Int) -> Bool {\n return xs..<1\n}\n",
|
||||
"func beta(items: Int) -> Bool {\n return items..<2\n}\n",
|
||||
) == 1.0
|
||||
assert _scored(
|
||||
tmp_path,
|
||||
"func alpha(xs: Int) -> Bool {\n return xs..<1\n}\n",
|
||||
"func beta(items: Int) -> Bool {\n return items...1\n}\n",
|
||||
) < 1.0
|
||||
|
||||
|
||||
def test_a_swift_argument_label_is_part_of_the_call(tmp_path):
|
||||
assert _scored(
|
||||
tmp_path,
|
||||
"func alpha(xs: [Int]) -> [Int] {\n return move(from: xs, to: xs)\n}\n",
|
||||
"func beta(items: [Int]) -> [Int] {\n return move(from: items, to: items)\n}\n",
|
||||
) == 1.0
|
||||
assert _scored(
|
||||
tmp_path,
|
||||
"func alpha(xs: [Int]) -> [Int] {\n return move(from: xs, to: xs)\n}\n",
|
||||
"func beta(items: [Int]) -> [Int] {\n return move(start: items, end: items)\n}\n",
|
||||
) < 1.0
|
||||
|
||||
|
||||
def test_a_trailing_closure_label_is_part_of_the_call(tmp_path):
|
||||
labeled = """\
|
||||
func alpha() -> Int {
|
||||
return Button {
|
||||
save()
|
||||
} label: {
|
||||
Text(title)
|
||||
}
|
||||
}
|
||||
"""
|
||||
renamed = """\
|
||||
func beta() -> Int {
|
||||
return Button {
|
||||
save()
|
||||
} label: {
|
||||
Text(heading)
|
||||
}
|
||||
}
|
||||
"""
|
||||
relabeled = """\
|
||||
func beta() -> Int {
|
||||
return Button {
|
||||
save()
|
||||
} action: {
|
||||
Text(title)
|
||||
}
|
||||
}
|
||||
"""
|
||||
assert _scored(tmp_path, labeled, renamed) == 1.0
|
||||
assert _scored(tmp_path, labeled, relabeled) < 1.0
|
||||
assert _scored(
|
||||
tmp_path,
|
||||
"func alpha(xs: [Int]) -> [Int] {\n return xs.filter { item in\n odd(item)\n }\n}\n",
|
||||
"func beta(items: [Int]) -> [Int] {\n return items.filter { value in\n odd(value)\n }\n}\n",
|
||||
) == 1.0
|
||||
|
||||
|
||||
def test_swift_literals_normalize_and_interpolation_does_not(tmp_path):
|
||||
assert _scored(
|
||||
tmp_path,
|
||||
'func alpha() -> String {\n return "Save"\n}\n',
|
||||
"func beta() -> Int {\n return 1\n}\n",
|
||||
) == 1.0
|
||||
assert _scored(
|
||||
tmp_path,
|
||||
"func alpha() -> Int {\n return nil\n}\n",
|
||||
"func beta() -> Double {\n return 1.5\n}\n",
|
||||
) == 1.0
|
||||
assert _scored(
|
||||
tmp_path,
|
||||
'func alpha() -> String {\n return """\n hello\n """\n}\n',
|
||||
"func beta() -> Int {\n return 0\n}\n",
|
||||
) == 1.0
|
||||
assert _scored(
|
||||
tmp_path,
|
||||
'func alpha(name: String) -> String {\n return "Hello \\(name)"\n}\n',
|
||||
'func beta() -> String {\n return "Hello"\n}\n',
|
||||
) < 1.0
|
||||
|
||||
|
||||
def test_a_swift_comment_is_not_part_of_the_structure(tmp_path):
|
||||
commented = """\
|
||||
func alpha(xs: [Int]) -> [Int] {
|
||||
// keep the odds
|
||||
/* and this */
|
||||
let ys = filter(xs, odd)
|
||||
return map(ys, inc)
|
||||
}
|
||||
"""
|
||||
assert _scored(tmp_path, commented, SWIFT_RIGHT) == 1.0
|
||||
|
||||
|
||||
APP = """\
|
||||
import SwiftUI
|
||||
|
||||
struct InvoiceView: View {
|
||||
var title: String
|
||||
|
||||
var body: some View {
|
||||
func hidden() -> Int {
|
||||
return count()
|
||||
}
|
||||
VStack {
|
||||
Text(title)
|
||||
Button(action: { save() }) {
|
||||
Text("Save")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func refresh(xs: [Int]) -> [Int] {
|
||||
let ys = filter(xs, odd)
|
||||
return map(ys, inc)
|
||||
}
|
||||
}
|
||||
|
||||
class Panel {
|
||||
init(xs: [Int]) {
|
||||
self.items = filter(xs, odd)
|
||||
self.kept = map(xs, inc)
|
||||
}
|
||||
|
||||
func beta(items: [Int]) -> [Int] {
|
||||
let kept = filter(items, even)
|
||||
return map(kept, dec)
|
||||
}
|
||||
}
|
||||
|
||||
extension Board {
|
||||
func gamma(xs: [Int]) -> [Int] {
|
||||
let ys = filter(xs, odd)
|
||||
return map(ys, inc)
|
||||
}
|
||||
}
|
||||
|
||||
enum Status {
|
||||
case open
|
||||
case closed
|
||||
|
||||
func label(xs: [Int]) -> [Int] {
|
||||
let ys = filter(xs, odd)
|
||||
return map(ys, inc)
|
||||
}
|
||||
}
|
||||
|
||||
protocol Saving {
|
||||
func save(order: Order)
|
||||
|
||||
func load(id: Int) -> Order {
|
||||
return cache(id)
|
||||
}
|
||||
}
|
||||
|
||||
func outer(xs: [Int]) -> [Int] {
|
||||
func inner(ys: [Int]) -> [Int] {
|
||||
let kept = filter(ys, odd)
|
||||
return map(kept, inc)
|
||||
}
|
||||
let closure = { (zs: [Int]) -> [Int] in
|
||||
let kept = filter(zs, even)
|
||||
return map(kept, dec)
|
||||
}
|
||||
return inner(xs)
|
||||
}
|
||||
|
||||
let alpha = { (xs: [Int]) -> [Int] in
|
||||
func inner(ys: [Int]) -> [Int] {
|
||||
let kept = filter(ys, odd)
|
||||
return map(kept, inc)
|
||||
}
|
||||
return inner(xs)
|
||||
}
|
||||
"""
|
||||
|
||||
INVOICE = """\
|
||||
struct InvoiceView: View {
|
||||
var title: String
|
||||
var body: some View {
|
||||
VStack {
|
||||
Text(title)
|
||||
Button(action: { save() }) {
|
||||
Text("Save")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
RECEIPT = """\
|
||||
struct ReceiptView: View {
|
||||
var heading: String
|
||||
var body: some View {
|
||||
VStack {
|
||||
Text(heading)
|
||||
Button(action: { save() }) {
|
||||
Text("Done")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
LABEL_VIEW = """\
|
||||
struct LabelView: View {
|
||||
var heading: String
|
||||
var body: some View {
|
||||
VStack {
|
||||
Label(heading)
|
||||
Button(action: { save() }) {
|
||||
Text("Done")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def test_swift_keeps_methods_bodies_and_top_level_closures_only():
|
||||
entries, warning = entries_in_source("swift", APP, "App.swift", "App.swift")
|
||||
assert warning is None
|
||||
assert [(entry.start_line, entry.end_line) for entry in entries] == [
|
||||
(6, 16),
|
||||
(18, 21),
|
||||
(30, 33),
|
||||
(37, 40),
|
||||
(47, 50),
|
||||
(56, 58),
|
||||
(61, 71),
|
||||
(73, 79),
|
||||
]
|
||||
|
||||
|
||||
def test_swiftui_views_match_when_only_the_data_changes(tmp_path):
|
||||
assert _scored(tmp_path, INVOICE, RECEIPT) == 1.0
|
||||
assert _scored(tmp_path, RECEIPT, LABEL_VIEW) < 1.0
|
||||
|
||||
|
||||
def test_swift_report_writes_the_same_snapshot(tmp_path, capsys):
|
||||
write_source(tmp_path, "left.swift", SWIFT_LEFT)
|
||||
write_source(tmp_path, "right.swift", SWIFT_RIGHT)
|
||||
assert run(["--root", str(tmp_path)]) == 0
|
||||
captured = capsys.readouterr()
|
||||
assert "DUPLICATE score=1.00" in captured.out
|
||||
assert "left.swift:1-4" in captured.out
|
||||
assert "right.swift:1-4" in captured.out
|
||||
text = (tmp_path / ".metrics" / "dry.edn").read_text(encoding="utf-8")
|
||||
assert ':language "swift"' in text
|
||||
assert ':file "left.swift"' in text
|
||||
assert "Wrote" in captured.err
|
||||
|
||||
|
||||
def test_a_swift_package_skips_its_tests(tmp_path):
|
||||
body = "func alpha() -> Int {\n return 1\n}\n"
|
||||
write_source(tmp_path, "Sources/App.swift", body)
|
||||
write_source(tmp_path, "Tests/AppTests.swift", body)
|
||||
write_source(tmp_path, "Sources/HiddenTests.swift", body)
|
||||
relative = [path.relative_to(tmp_path).as_posix() for path in iter_source_files([tmp_path])]
|
||||
assert language_of("Sources/App.swift") == "swift"
|
||||
assert relative == ["Sources/App.swift"]
|
||||
|
||||
|
||||
def test_a_deinit_is_compared_and_keeps_its_nested_function(tmp_path):
|
||||
source = """\
|
||||
class Panel {
|
||||
deinit {
|
||||
func hidden() -> Int {
|
||||
return cache()
|
||||
}
|
||||
close(handle)
|
||||
}
|
||||
|
||||
func stop() {
|
||||
close(handle)
|
||||
}
|
||||
}
|
||||
"""
|
||||
entries, warning = entries_in_source("swift", source, "Panel.swift", "Panel.swift")
|
||||
assert warning is None
|
||||
assert [(entry.start_line, entry.end_line) for entry in entries] == [(2, 7), (9, 11)]
|
||||
assert _scored(
|
||||
tmp_path,
|
||||
"class A {\n deinit {\n close(handle)\n release(buffer)\n }\n}\n",
|
||||
"class B {\n deinit {\n close(other)\n release(kept)\n }\n}\n",
|
||||
) == 1.0
|
||||
assert _scored(
|
||||
tmp_path,
|
||||
"class A {\n deinit {\n close(handle)\n }\n}\n",
|
||||
"class B {\n deinit {\n shutdown(other)\n }\n}\n",
|
||||
) < 1.0
|
||||
|
||||
|
||||
def test_a_generic_constraint_name_does_not_keep_the_functions_apart(tmp_path):
|
||||
assert _scored(
|
||||
tmp_path,
|
||||
"""\
|
||||
func alpha<T: Equatable>(xs: [T]) -> [T] {
|
||||
let ys = filter(xs, odd)
|
||||
return map(ys, inc)
|
||||
}
|
||||
""",
|
||||
"""\
|
||||
func beta<U: Hashable>(items: [U]) -> [U] {
|
||||
let kept = filter(items, even)
|
||||
return map(kept, dec)
|
||||
}
|
||||
""",
|
||||
) == 1.0
|
||||
assert _scored(
|
||||
tmp_path,
|
||||
"""\
|
||||
func alpha<T>(xs: [T]) -> [T] where T: Equatable {
|
||||
let ys = filter(xs, odd)
|
||||
return map(ys, inc)
|
||||
}
|
||||
""",
|
||||
"""\
|
||||
func beta<U>(items: [U]) -> [U] where U: Hashable {
|
||||
let kept = filter(items, even)
|
||||
return map(kept, dec)
|
||||
}
|
||||
""",
|
||||
) == 1.0
|
||||
|
||||
|
||||
def test_an_extension_method_matches_its_renamed_copy(tmp_path):
|
||||
assert _scored(
|
||||
tmp_path,
|
||||
"""\
|
||||
extension Array where Element: Equatable {
|
||||
func alpha(xs: [Int]) -> [Int] {
|
||||
let ys = filter(xs, odd)
|
||||
return map(ys, inc)
|
||||
}
|
||||
}
|
||||
""",
|
||||
"""\
|
||||
extension Array where Element: Hashable {
|
||||
func beta(items: [Int]) -> [Int] {
|
||||
let kept = filter(items, even)
|
||||
return map(kept, dec)
|
||||
}
|
||||
}
|
||||
""",
|
||||
) == 1.0
|
||||
|
||||
|
||||
def test_an_async_throws_function_matches_its_renamed_copy(tmp_path):
|
||||
assert _scored(
|
||||
tmp_path,
|
||||
"""\
|
||||
func alpha(xs: [Int]) async throws -> [Int] {
|
||||
let ys = try await filter(xs, odd)
|
||||
return map(ys, inc)
|
||||
}
|
||||
""",
|
||||
"""\
|
||||
func beta(items: [Int]) async throws -> [Int] {
|
||||
let kept = try await filter(items, even)
|
||||
return map(kept, dec)
|
||||
}
|
||||
""",
|
||||
) == 1.0
|
||||
assert _scored(
|
||||
tmp_path,
|
||||
"func alpha() -> Int? {\n return try? cache()\n}\n",
|
||||
"func beta() -> Int {\n return try load()\n}\n",
|
||||
) < 1.0
|
||||
|
||||
|
||||
def test_a_main_actor_function_matches_its_renamed_copy(tmp_path):
|
||||
assert _scored(
|
||||
tmp_path,
|
||||
"""\
|
||||
@MainActor
|
||||
func alpha(xs: [Int]) -> [Int] {
|
||||
let ys = filter(xs, odd)
|
||||
return map(ys, inc)
|
||||
}
|
||||
""",
|
||||
"""\
|
||||
@MainActor
|
||||
func beta(items: [Int]) -> [Int] {
|
||||
let kept = filter(items, even)
|
||||
return map(kept, dec)
|
||||
}
|
||||
""",
|
||||
) == 1.0
|
||||
assert _scored(
|
||||
tmp_path,
|
||||
"""\
|
||||
struct InvoiceView {
|
||||
@MainActor
|
||||
var body: String {
|
||||
return Text(title)
|
||||
}
|
||||
}
|
||||
""",
|
||||
"""\
|
||||
struct ReceiptView {
|
||||
@MainActor
|
||||
var body: String {
|
||||
return Text(heading)
|
||||
}
|
||||
}
|
||||
""",
|
||||
) == 1.0
|
||||
|
||||
|
||||
def test_a_nested_block_comment_is_not_part_of_the_structure(tmp_path):
|
||||
commented = """\
|
||||
func alpha(xs: [Int]) -> [Int] {
|
||||
/* outer /* inner */ still comment */
|
||||
let ys = filter(xs, odd)
|
||||
return map(ys, inc)
|
||||
}
|
||||
"""
|
||||
assert _scored(tmp_path, commented, SWIFT_RIGHT) == 1.0
|
||||
|
||||
|
||||
def test_multiline_interpolation_keeps_the_expression_and_drops_the_name(tmp_path):
|
||||
assert _scored(
|
||||
tmp_path,
|
||||
'''func alpha(order: Order) -> String {\n return """\n \\(order.total)\n """\n}\n''',
|
||||
'''func beta(row: Row) -> String {\n return """\n \\(row.amount)\n """\n}\n''',
|
||||
) == 1.0
|
||||
assert _scored(
|
||||
tmp_path,
|
||||
'''func alpha(order: Order) -> String {\n return """\n \\(order.total)\n """\n}\n''',
|
||||
'func beta() -> String {\n return """\n hello\n """\n}\n',
|
||||
) < 1.0
|
||||
|
||||
|
||||
def test_a_getter_and_setter_match_when_only_the_names_change(tmp_path):
|
||||
assert _scored(
|
||||
tmp_path,
|
||||
"""\
|
||||
struct Left {
|
||||
var value: Int {
|
||||
get { return cache(stored) }
|
||||
set { store(fresh) }
|
||||
}
|
||||
}
|
||||
""",
|
||||
"""\
|
||||
struct Right {
|
||||
var amount: Int {
|
||||
get { return cache(kept) }
|
||||
set { store(next) }
|
||||
}
|
||||
}
|
||||
""",
|
||||
) == 1.0
|
||||
assert _scored(
|
||||
tmp_path,
|
||||
"""\
|
||||
struct Left {
|
||||
var value: Int {
|
||||
get { return cache(stored) }
|
||||
set { store(fresh) }
|
||||
}
|
||||
}
|
||||
""",
|
||||
"""\
|
||||
struct Right {
|
||||
var amount: Int {
|
||||
get { return cache(kept) }
|
||||
set { write(next) }
|
||||
}
|
||||
}
|
||||
""",
|
||||
) < 1.0
|
||||
|
||||
|
||||
def test_negation_and_force_unwrap_stay_in_the_score(tmp_path):
|
||||
assert _scored(
|
||||
tmp_path,
|
||||
"func alpha(xs: Bool) -> Bool {\n return !xs\n}\n",
|
||||
"func beta(items: Bool) -> Bool {\n return !items\n}\n",
|
||||
) == 1.0
|
||||
assert _scored(
|
||||
tmp_path,
|
||||
"func alpha(xs: Bool) -> Bool {\n return !xs\n}\n",
|
||||
"func beta(items: Bool) -> Bool {\n return items\n}\n",
|
||||
) < 1.0
|
||||
assert _scored(
|
||||
tmp_path,
|
||||
"func alpha(xs: Int?) -> Int {\n return xs!\n}\n",
|
||||
"func beta(items: Int?) -> Int {\n return items!\n}\n",
|
||||
) == 1.0
|
||||
assert _scored(
|
||||
tmp_path,
|
||||
"func alpha(xs: Int?) -> Int {\n return xs!\n}\n",
|
||||
"func beta(items: Int?) -> Int {\n return items\n}\n",
|
||||
) < 1.0
|
||||
|
||||
|
||||
def test_a_top_level_swift_closure_matches_its_renamed_copy(tmp_path):
|
||||
left = """\
|
||||
let alpha = { (xs: [Int]) -> [Int] in
|
||||
let ys = filter(xs, odd)
|
||||
return map(ys, inc)
|
||||
}
|
||||
"""
|
||||
right = """\
|
||||
let beta = { (items: [Int]) -> [Int] in
|
||||
let kept = filter(items, even)
|
||||
return map(kept, dec)
|
||||
}
|
||||
"""
|
||||
assert _scored(tmp_path, left, right) == 1.0
|
||||
Reference in New Issue
Block a user