merge main

This commit is contained in:
Lam Wei Lun
2026-10-06 13:08:46 +08:00
parent ccbb73baaf
commit ecbd03fed7
868 changed files with 203633 additions and 35823 deletions
+9 -5
View File
@@ -78,8 +78,9 @@ def load_table():
if not line.startswith('{"'):
continue
# id, name, row, key, action, refusal, accepts, need_bodies, need_sketches, need_sheet,
# sketch_mode, family, ... — split on top-level commas, respecting quotes.
f, cur, q, esc = [], "", False, False
# sketch_mode, family, ... — split on top-level commas, respecting quotes and the
# L(...) / L_CONTEXT(...) translation markers.
f, cur, q, esc, depth = [], "", False, False, 0
for ch in line[1:]:
if esc:
cur += ch; esc = False; continue
@@ -87,15 +88,18 @@ def load_table():
cur += ch; esc = True; continue
if ch == '"':
q = not q
if ch == "," and not q:
if not q:
depth += (ch == "(") - (ch == ")")
if ch == "," and not q and depth == 0:
f.append(cur.strip()); cur = ""; continue
if ch == "}" and not q:
if ch == "}" and not q and depth == 0:
break
cur += ch
f.append(cur.strip())
if len(f) < 12:
continue
lit = lambda s: None if s == "nullptr" else s.strip('"')
# User-facing fields are wrapped in L("...") or L_CONTEXT("...", ...); take the literal.
lit = lambda s: None if s == "nullptr" else re.search(r'"((?:[^"\\]|\\.)*)"', s).group(1)
out.append({"id": lit(f[0]), "name": lit(f[1]), "row": int(f[2]), "key": lit(f[3]),
"action": lit(f[4]), "accepts": int(f[6].rstrip("u"), 0),
"need_bodies": int(f[7]), "need_sketches": int(f[8]),
+33 -6
View File
@@ -37,6 +37,17 @@ def cstr(s):
return '"' + s.replace("\\", "\\\\").replace('"', '\\"') + '"'
def tstr(s):
# User-facing text: wrapped in the no-op L() marker so xgettext puts it in the catalogue.
# The DesignPanel translates it at use; without the marker it compiles and never translates.
return "nullptr" if s is None else "L(" + cstr(s) + ")"
def tstr_design(s):
# Verb name: same msgctxt as the Design panel's own tool labels.
return "L_CONTEXT(" + cstr(s) + ', "Design")'
def validate(A):
"""Refuse an atlas the header cannot represent, naming every fault at once.
@@ -81,6 +92,13 @@ def main():
"",
"#include <cstdint>",
"",
"#ifndef L",
"#define L(s) s // gettext marker, as in slic3r/GUI/I18N.hpp",
"#endif",
"#ifndef L_CONTEXT",
"#define L_CONTEXT(s, context) s",
"#endif",
"",
"namespace Slic3r { namespace GUI {",
"",
"// What the viewport has selected. Ordered as in tool_atlas.json; the bitmask in",
@@ -103,8 +121,8 @@ def main():
"// nullptr -> kernel support exists, no GUI path yet (row shows disabled)",
"struct OfferVerb {",
" const char* id;",
" const char* name; // drawing-office word (L10); translated at use with wxGetTranslation",
" int row; // 0..7, the ratified index — NEVER reorder",
" const char* name; // drawing-office word (L10); msgctxt \"Design\", translated at use",
" int row; // index into kOfferRowNames, the ratified address — NEVER reorder",
" const char* key; // shortcut shown in the row, or nullptr",
" const char* action;",
" const char* refusal; // why this row is greyed, in the product's own words",
@@ -125,11 +143,20 @@ def main():
"// Row labels, in ratified order.",
"static const char* const kOfferRowNames[] = {",
]
# A flat row's label is never shown, so it is not marked for translation.
for s in A["slots"]:
lines.append(f' "{s["label"]}",')
lines.append(f' {cstr(s["label"]) if s.get("flat") else tstr(s["label"])},')
lines += [
"};",
f"static const int kOfferRowCount = {len(slots)};",
"// A flat row is not a family: its verbs come first, at the top level of the offer, each",
"// an item of its own.",
"static const bool kOfferRowFlat[] = {",
]
for s in A["slots"]:
lines.append(f' {"true" if s.get("flat") else "false"},')
lines += [
"};",
"",
"static const OfferVerb kOfferVerbs[] = {",
]
@@ -151,12 +178,12 @@ def main():
n = v.get("needs") or {}
lines.append(
" {%s, %s, %d, %s, %s, %s, 0x%08xu, %d, %d, %s, %s, %s, %s, %s}," % (
cstr(v["id"]), cstr(v["name"]), slots.index(v["slot"]),
cstr(v.get("key")), cstr(v.get("action")), cstr(v.get("refusal")),
cstr(v["id"]), tstr_design(v["name"]), slots.index(v["slot"]),
cstr(v.get("key")), cstr(v.get("action")), tstr(v.get("refusal")),
mask, n.get("bodies", 0), n.get("sketches", 0),
"true" if n.get("sheet") else "false",
"true" if v.get("mode") == "sketch" else "false",
cstr(v.get("family")), cstr(v.get("icon")), cstr(v.get("hint"))))
tstr(v.get("family")), cstr(v.get("icon")), tstr(v.get("hint"))))
lines += [
"};",
f"static const int kOfferVerbCount = {len(A['verbs'])};",
+47 -39
View File
@@ -67,6 +67,12 @@
"angle": 225,
"label": "Modify",
"why": "edits or removes what is already there"
},
{
"id": "top",
"label": "Top",
"flat": true,
"why": "the verbs a selection is opened for most. A flat slot is not a family: its verbs sit first, at the top level of the offer, each an item of its own, and its label is never shown. Appended last, so no ratified index moved."
}
],
"selections": [
@@ -326,7 +332,7 @@
"id": "rib",
"name": "Rib",
"slot": "add",
"key": null,
"key": "R",
"feature": "Rib",
"mcp": "rib",
"accepts": [
@@ -343,7 +349,7 @@
},
{
"id": "boolean",
"name": "Union",
"name": "Join",
"slot": "add",
"key": "Shift+B",
"feature": "Boolean",
@@ -354,7 +360,7 @@
"needs": {
"bodies": 2
},
"refusal": "Boolean needs two bodies — create or import a second solid",
"refusal": "Boolean needs two bodies — add or import a second one",
"gui": true,
"action": "btn:bool#0",
"icon": "design_boolean",
@@ -373,7 +379,7 @@
"needs": {
"bodies": 2
},
"refusal": "Boolean needs two bodies — create or import a second solid",
"refusal": "Boolean needs two bodies — add or import a second one",
"gui": true,
"action": "btn:bool#1",
"mode": null,
@@ -393,7 +399,7 @@
"needs": {
"bodies": 2
},
"refusal": "Boolean needs two bodies — create or import a second solid",
"refusal": "Boolean needs two bodies — add or import a second one",
"gui": true,
"action": "btn:bool#2",
"mode": null,
@@ -483,7 +489,7 @@
"needs": {
"sheet": true
},
"refusal": "target is not a sheet body",
"refusal": "Thicken Surface needs a surface body — make one with a Surface tool first",
"gui": true,
"action": "fly:surface#5",
"icon": "design_thicken",
@@ -507,7 +513,7 @@
"gui": true,
"action": "key:S+H",
"icon": "design_hole",
"hint": "Drill a hole, centred on a picked face or placed on a plane"
"hint": "Drill a hole, centerd on a picked face or placed on a plane"
},
{
"id": "thread",
@@ -543,7 +549,7 @@
"needs": {
"bodies": 1
},
"refusal": "Shell needs a solid body",
"refusal": "Shell needs a solid body — add or import one first",
"gui": true,
"action": "key:S+K",
"icon": "design_shell",
@@ -569,7 +575,7 @@
"needs": {
"bodies": 1
},
"refusal": "Create a solid body to cut first",
"refusal": "Cut needs a solid body — add or import one first",
"gui": true,
"action": "key:S+X",
"icon": "design_cut",
@@ -594,7 +600,7 @@
"needs": {
"bodies": 1
},
"refusal": "Split needs a solid body",
"refusal": "Split needs a solid body — add or import one first",
"gui": false,
"action": null,
"icon": null,
@@ -677,7 +683,7 @@
"needs": {
"sheet": true
},
"refusal": "target is not a sheet body",
"refusal": "Surface Offset needs a surface body — make one with a Surface tool first",
"gui": true,
"action": "fly:surface#4",
"icon": "design_offset",
@@ -699,7 +705,7 @@
"needs": {
"bodies": 1
},
"refusal": "Create a solid body to pattern first",
"refusal": "Pattern needs a solid body — add or import one first",
"gui": true,
"action": "btn:pat#0",
"icon": "design_array",
@@ -721,7 +727,7 @@
"needs": {
"bodies": 1
},
"refusal": "Create a solid body to pattern first",
"refusal": "Pattern needs a solid body — add or import one first",
"gui": true,
"action": "btn:pat#1",
"mode": null,
@@ -768,7 +774,7 @@
"needs": {
"bodies": 1
},
"refusal": "Pattern on curve needs a body and a curve",
"refusal": "Pattern on Curve needs a body and a curve",
"gui": false,
"action": null,
"icon": null,
@@ -816,11 +822,11 @@
"needs": {
"bodies": 2
},
"refusal": "A mate needs two coordinate systems",
"refusal": "Mate needs two coordinate systems — create them first",
"gui": true,
"action": "fly:placement#2",
"icon": "design_c_coincident",
"hint": "Assembly: align two CoordSys features (fastened, planar, revolute, slider, cylindrical)"
"hint": "Assembly: align two coordinate systems (fastened, planar, revolute, slider, cylindrical)"
},
{
"id": "align",
@@ -835,7 +841,7 @@
"needs": {
"bodies": 1
},
"refusal": "Align needs a body",
"refusal": "Align needs a body — add or import one first",
"gui": false,
"action": null,
"icon": null,
@@ -885,7 +891,7 @@
},
{
"id": "coordsys_v",
"name": "Coord Sys",
"name": "Coordinate system",
"slot": "reference",
"key": "Shift+C",
"feature": "CoordSys",
@@ -972,7 +978,7 @@
},
{
"id": "mass_props",
"name": "Mass",
"name": "Volume and area",
"slot": "reference",
"key": null,
"feature": null,
@@ -1003,14 +1009,15 @@
"feature": null,
"mcp": "check_interference",
"accepts": [
"body_solid",
"bodies_2"
],
"needs": {
"bodies": 2
},
"refusal": null,
"gui": false,
"action": null,
"refusal": "Interference needs at least two bodies",
"gui": true,
"action": "btn:interference",
"icon": null,
"hint": "Check whether two bodies overlap — reports, changes nothing"
},
@@ -1043,7 +1050,7 @@
{
"id": "rename",
"name": "Rename…",
"slot": "modify",
"slot": "top",
"key": "F2",
"feature": "Tree",
"mcp": null,
@@ -1082,8 +1089,8 @@
},
{
"id": "colour",
"name": "Colour",
"slot": "modify",
"name": "Color",
"slot": "top",
"key": null,
"feature": null,
"mcp": null,
@@ -1104,7 +1111,7 @@
"gui": true,
"action": "btn:colour",
"icon": "color_palette",
"hint": "Set the selected body's display colour"
"hint": "Set the selected body's display color"
},
{
"id": "delete",
@@ -1227,7 +1234,7 @@
},
{
"id": "sk_rect_center",
"name": "Centre rectangle",
"name": "Center rectangle",
"slot": "create",
"key": null,
"feature": "Sketch",
@@ -1296,7 +1303,7 @@
},
{
"id": "sk_circle",
"name": "Centre circle",
"name": "Center circle",
"slot": "create",
"key": "C",
"feature": "Sketch",
@@ -1411,7 +1418,7 @@
},
{
"id": "sk_arc_center",
"name": "Centre-point arc",
"name": "Center-point arc",
"slot": "create",
"key": null,
"feature": "Sketch",
@@ -1453,7 +1460,7 @@
"action": "key:S",
"family": "Slot",
"icon": "design_slot",
"hint": "Slot — two centerline ends, then end radius"
"hint": "Slot — two centerline ends, then the width"
},
{
"id": "sk_slot_arc",
@@ -1567,7 +1574,7 @@
"mode": "sketch",
"family": "Polygon",
"icon": "design_polygon",
"hint": "Triangle — click centre, then a vertex"
"hint": "Triangle — click center, then a vertex"
},
{
"id": "sk_poly_4",
@@ -1590,7 +1597,7 @@
"mode": "sketch",
"family": "Polygon",
"icon": "design_polygon",
"hint": "Square — click centre, then a vertex"
"hint": "Square — click center, then a vertex"
},
{
"id": "sk_poly_5",
@@ -1613,7 +1620,7 @@
"mode": "sketch",
"family": "Polygon",
"icon": "design_polygon",
"hint": "Pentagon — click centre, then a vertex"
"hint": "Pentagon — click center, then a vertex"
},
{
"id": "sk_polygon",
@@ -1636,7 +1643,7 @@
"action": "btn:poly#6",
"family": "Polygon",
"icon": "design_polygon",
"hint": "Hexagon — click centre, then a vertex"
"hint": "Hexagon — click center, then a vertex"
},
{
"id": "sk_poly_8",
@@ -1659,7 +1666,7 @@
"mode": "sketch",
"family": "Polygon",
"icon": "design_polygon",
"hint": "Octagon — click centre, then a vertex"
"hint": "Octagon — click center, then a vertex"
},
{
"id": "sk_poly_12",
@@ -1682,7 +1689,7 @@
"mode": "sketch",
"family": "Polygon",
"icon": "design_polygon",
"hint": "Dodecagon — click centre, then a vertex"
"hint": "Dodecagon — click center, then a vertex"
},
{
"id": "sk_poly_inscribed",
@@ -1772,7 +1779,7 @@
"action": "btn:text",
"mode": "sketch",
"icon": "design_text",
"hint": "Type text; its outline is added to this sketch as editable lines"
"hint": "Type text; it becomes a Text feature on this sketch's plane, editable later"
},
{
"id": "sk_svg",
@@ -2048,7 +2055,7 @@
{
"id": "constrain",
"name": "Constrain sketch",
"slot": "modify",
"slot": "reference",
"key": null,
"feature": "Sketch",
"mcp": null,
@@ -2067,7 +2074,8 @@
"note": [
"Same verb, model-mode vocabulary: offered when a SKETCH is selected (bit 14, SkLoop), the",
"state a user is in right after finishing one. Without this row the only way in was the",
"toolbar icon, and constraints read as absent — see the Onshape-comparison report."
"toolbar icon, and constraints read as absent — see the Onshape-comparison report.",
"It sits in the Reference row, the address the sketch-mode Constrain has: one verb, one row."
]
},
{
+294
View File
@@ -0,0 +1,294 @@
#!/usr/bin/env python3
"""Run clang-tidy on the C++ files changed since a base revision.
Check findings are reported only on added or modified lines, so existing code
is not held to checks it predates. A changed source file that does not compile
(for example one that only built because the precompiled header supplied an
include) fails wherever the error is. Headers are compiled on their own, and
fail only on errors in their changed lines. Deleting an #include also fails
on every use, changed or not, that now lacks the header it provided.
The checks come from .clang-tidy at the repository root. The compile database
must come from a configure with SLIC3R_PCH=OFF, or the precompiled header hides
missing includes.
python3 scripts/clang_tidy_diff.py -p build-tidy --base origin/main
"""
import argparse
import json
import os
import re
import subprocess
import sys
import tempfile
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field
from pathlib import PurePosixPath
SOURCE_EXTENSIONS = {".cpp", ".cc", ".cxx"}
HEADER_EXTENSIONS = {".hpp", ".h", ".hxx"}
CHECKED_DIRS = ("src/", "tests/")
# Vendored code inside the checked directories.
EXCLUDED_DIRS = ("src/glad/", "tests/catch2/")
# Per file. A deleted include can leave hundreds of follow-on errors.
MAX_REPORTED = 30
# Subprocess output is UTF-8 whatever the locale, which is cp1252 on Windows.
UTF8 = {"encoding": "utf-8", "errors": "replace"}
HUNK_RE = re.compile(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@")
DIAGNOSTIC_RE = re.compile(r"^(.+?):(\d+):(\d+): (error|warning): (.*)$")
FIX_MESSAGE_RE = re.compile(r"^\s+Message:\s+(['\"])(.*)\1$")
FIX_INCLUDE_RE = re.compile(r"^\s+ReplacementText:\s+['\"]#include ([^\\'\"]*)")
REMOVED_INCLUDE_RE = re.compile(r'^-\s*#\s*include\s*[<"]([^>"]+)[>"]')
@dataclass
class FileChange:
lines: list = field(default_factory=list) # [first, last] ranges of added lines
removed_includes: set = field(default_factory=set) # header names whose #include was deleted
@dataclass
class Diagnostic:
file: str
line: int
col: int
level: str
message: str
include: str = "" # header named by the fix, when the fix adds an #include
@property
def is_compile_error(self):
return self.message.endswith("[clang-diagnostic-error]")
def __str__(self):
return self.message + (f" (add #include {self.include})" if self.include else "")
def parse_diff(diff):
"""Map each file in a `git diff -U0` to the lines it adds and the includes it deletes."""
changes = {}
change = None
for line in diff.splitlines():
if line.startswith("+++ "):
# git appends a tab to the header of a path that contains a space.
target = line[4:].removesuffix("\t")
change = changes.setdefault(target[2:], FileChange()) if target.startswith("b/") else None
continue
if change is None:
continue
match = HUNK_RE.match(line)
if match:
first = int(match.group(1))
count = int(match.group(2) or 1)
if count > 0:
change.lines.append([first, first + count - 1])
continue
match = REMOVED_INCLUDE_RE.match(line)
if match:
change.removed_includes.add(match.group(1))
return changes
def is_checked(path):
if not path.startswith(CHECKED_DIRS) or path.startswith(EXCLUDED_DIRS):
return False
return PurePosixPath(path).suffix in SOURCE_EXTENSIONS | HEADER_EXTENSIONS
def changed_files(merge_base):
# Against the working tree, so a local run covers uncommitted edits too.
# core.quotePath=false keeps a non-ASCII path unquoted, so parse_diff sees its b/ prefix.
diff = subprocess.run(["git", "-c", "core.quotePath=false", "diff", "-U0", "--no-color", "--no-ext-diff",
"--diff-filter=AMR", merge_base],
check=True, capture_output=True, **UTF8).stdout
return {path: change for path, change in parse_diff(diff).items() if is_checked(path)}
def compiled_sources(build_dir):
with open(os.path.join(build_dir, "compile_commands.json"), encoding="utf-8") as f:
return {os.path.realpath(os.path.join(entry["directory"], entry["file"])) for entry in json.load(f)}
def run_clang_tidy(clang_tidy, build_dir, path, lines, extra_args):
"""Run clang-tidy on one file, limited to `lines` unless it is None."""
with tempfile.TemporaryDirectory() as tmp:
fixes = os.path.join(tmp, "fixes.yaml")
# The compile database comes from the system clang, which may know warning
# flags a newer clang-tidy has dropped.
cmd = [clang_tidy, "-p", build_dir, "--quiet", "--export-fixes=" + fixes,
"--extra-arg=-Wno-unknown-warning-option", "--extra-arg=-ferror-limit=0", *extra_args, path]
if lines is not None:
# clang-tidy matches the name against the end of the file's native path.
cmd.insert(1, "--line-filter=" + json.dumps([{"name": os.path.normpath(path), "lines": lines}]))
result = subprocess.run(cmd, capture_output=True, **UTF8)
suggestions = parse_suggested_includes(fixes)
output = result.stdout + result.stderr
return result.returncode, output, parse_diagnostics(output, suggestions)
def parse_suggested_includes(fixes_path):
"""Map each message in an --export-fixes file to the header its fix includes."""
if not os.path.exists(fixes_path):
return {}
suggestions = {}
message = None
with open(fixes_path, encoding="utf-8") as f:
for line in f:
match = FIX_MESSAGE_RE.match(line)
if match:
message = match.group(2).replace("''", "'")
continue
match = FIX_INCLUDE_RE.match(line)
if match and message:
suggestions[message] = match.group(1)
message = None
return suggestions
def parse_diagnostics(output, suggestions):
diagnostics = []
for line in output.splitlines():
match = DIAGNOSTIC_RE.match(line)
if match:
file, row, col, level, message = match.groups()
include = suggestions.get(re.sub(r" \[[^]]*\]$", "", message), "")
diagnostics.append(Diagnostic(file, int(row), int(col), level, message, include))
return diagnostics
def in_ranges(line, ranges):
return any(first <= line <= last for first, last in ranges)
def names_removed_include(include, removed):
"""Whether `include` (<a/b.hpp>) is one of the deleted includes, however it was spelled."""
name = include.strip('<>"')
return bool(name) and any(name == r or name.endswith("/" + r) or r.endswith("/" + name) for r in removed)
def own_errors(diagnostics, path):
real = os.path.realpath(path)
return [d for d in diagnostics if d.is_compile_error and os.path.realpath(d.file) == real]
def error_sites(errors, text):
"""Where each error points, as (source line, column): stable across edits to other lines,
unlike line numbers, and across a removed include, unlike clang's wording."""
lines = text.splitlines()
return Counter((lines[d.line - 1].strip() if d.line <= len(lines) else "", d.col) for d in errors)
def errors_alone_at(revision, clang_tidy, build_dir, path):
"""The error sites a header had when compiled on its own at `revision`."""
shown = subprocess.run(["git", "show", f"{revision}:{path}"], capture_output=True, **UTF8)
if shown.returncode != 0:
return Counter()
# Beside the original, so its quoted includes resolve the same way.
p = PurePosixPath(path)
copy = str(p.with_name(f".{p.stem}.clang-tidy-base{p.suffix}"))
try:
with open(copy, "w", encoding="utf-8") as f:
f.write(shown.stdout)
_, _, diagnostics = run_clang_tidy(clang_tidy, build_dir, copy, None, [])
finally:
os.remove(copy)
return error_sites(own_errors(diagnostics, copy), shown.stdout)
def check_file(clang_tidy, build_dir, merge_base, path, change, extra_args):
"""Run clang-tidy on one file and return (failed, output, failing diagnostics)."""
# A deleted include can orphan uses on unchanged lines, so such a file is
# checked whole and the findings narrowed here. --fix keeps the line filter
# so it never rewrites unrelated code.
whole = bool(change.removed_includes) and not extra_args
returncode, output, diagnostics = run_clang_tidy(clang_tidy, build_dir, path,
None if whole else change.lines, extra_args)
real = os.path.realpath(path)
def introduced(d):
return os.path.realpath(d.file) == real and (
in_ranges(d.line, change.lines) or names_removed_include(d.include, change.removed_includes))
if PurePosixPath(path).suffix in HEADER_EXTENSIONS:
# Many existing headers only compile after what their includers include
# first, so a header is held to errors it introduces: on its changed
# lines, or anywhere a deleted include leaves it with new errors.
failing = [d for d in diagnostics if introduced(d)]
errors = own_errors(diagnostics, path)
if errors and change.removed_includes:
with open(path, encoding="utf-8") as f:
text = f.read()
before = errors_alone_at(merge_base, clang_tidy, build_dir, path)
failing += [d for d in errors if d not in failing
and (error_sites([d], text) - before)]
return bool(failing), output, failing
if whole:
failing = [d for d in diagnostics if d.is_compile_error or introduced(d)]
return bool(failing), output, failing
return returncode != 0, output, diagnostics
def main():
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
parser.add_argument("-p", "--build-dir", required=True, help="directory holding compile_commands.json")
parser.add_argument("--base", default="origin/main", help="revision to diff against (default: origin/main)")
parser.add_argument("--clang-tidy", default="clang-tidy", help="clang-tidy executable")
parser.add_argument("-j", "--jobs", type=int, default=os.cpu_count())
parser.add_argument("extra_args", nargs="*", help="passed to clang-tidy after --, e.g. -- --fix")
args = parser.parse_args()
# A piped stdout on Windows is cp1252, which cannot encode every character clang-tidy prints.
sys.stdout.reconfigure(errors="replace")
merge_base = subprocess.run(["git", "merge-base", args.base, "HEAD"], check=True,
capture_output=True, text=True).stdout.strip()
files = changed_files(merge_base)
sources = compiled_sources(args.build_dir)
todo = []
for path, change in sorted(files.items()):
is_source = PurePosixPath(path).suffix in SOURCE_EXTENSIONS
if is_source and os.path.realpath(path) not in sources:
print(f"Skipping {path}: not compiled in this configuration")
elif change.lines or change.removed_includes:
todo.append((path, change))
if not todo:
print("No changed C++ lines to check.")
return 0
print(f"Checking {len(todo)} file(s) with {args.clang_tidy}")
annotate = os.environ.get("GITHUB_ACTIONS") == "true"
root = os.getcwd() + os.sep
failed = []
with ThreadPoolExecutor(max_workers=args.jobs) as pool:
jobs = {path: pool.submit(check_file, args.clang_tidy, args.build_dir, merge_base, path, change, args.extra_args)
for path, change in todo}
for path, job in jobs.items():
file_failed, output, diagnostics = job.result()
if not file_failed:
continue
failed.append(path)
print(f"\n==== {path}")
if not diagnostics:
print(output, end="")
for d in diagnostics[:MAX_REPORTED]:
file = d.file.removeprefix(root)
print(f"{file}:{d.line}:{d.col}: {d.level}: {d}")
if annotate:
print(f"::{d.level} file={file},line={d.line},col={d.col}::{d}")
if len(diagnostics) > MAX_REPORTED:
print(f"... and {len(diagnostics) - MAX_REPORTED} more")
if failed:
print(f"\nclang-tidy failed on {len(failed)} file(s). Add the includes it names, or apply its "
"suggestions locally with scripts/run_clang_tidy.sh --fix (scripts\\run_clang_tidy.ps1 -Fix on Windows).")
return 1
print("clang-tidy passed.")
return 0
if __name__ == "__main__":
sys.exit(main())
+1
View File
@@ -0,0 +1 @@
clang-tidy==22.1.8
+249
View File
@@ -0,0 +1,249 @@
<#
.SYNOPSIS
Runs the clang-tidy check that gates pull requests (.github/workflows/clang_tidy.yml) on
your branch. Windows.
.DESCRIPTION
Configures a separate build directory (build-tidy) without the precompiled header, installs
the pinned clang-tidy into a virtual environment inside it, and runs
scripts/clang_tidy_diff.py the way CI does. Uncommitted changes are checked too.
CI runs on Linux. Here clang-tidy also sees Windows-only code and MSVC's standard library,
so it can report findings CI does not; a change that passes here and on Linux passes CI.
.EXAMPLE
powershell -ExecutionPolicy Bypass -File scripts\run_clang_tidy.ps1
.EXAMPLE
powershell -ExecutionPolicy Bypass -File scripts\run_clang_tidy.ps1 -Fix
#>
param(
# Revision to compare against (default: main of the remote that points at
# OrcaSlicer/OrcaSlicer, else origin/main).
[string]$Base = "",
# Do not fetch that remote's main first.
[switch]$NoFetch,
# Build directory for the compile database.
[string]$BuildDir = "build-tidy",
# Dependency build directory (default: the deps\build* tree build_win.bat made).
[string]$DepsDir = "",
# x64 or arm64 (default: this machine's).
[string]$Arch = "",
# Parallel clang-tidy runs (default: all cores).
[int]$Jobs = 0,
# Apply clang-tidy's fixes (adds the missing includes).
[switch]$Fix,
# Install missing tools without asking.
[switch]$Yes
)
$ErrorActionPreference = "Stop"
$Root = Split-Path -Parent $PSScriptRoot
Set-Location $Root
if (-not [System.IO.Path]::IsPathRooted($BuildDir)) { $BuildDir = Join-Path $Root $BuildDir }
# Ask before installing anything. Without a console, or with "no", print the command
# instead so it can be run by hand.
function Ask([string]$Question) {
if ($Yes) { return $true }
if ([Console]::IsInputRedirected) { return $false }
$reply = Read-Host "$Question [y/N]"
return $reply -match '^[Yy]'
}
function Has([string]$Command) {
return [bool](Get-Command $Command -ErrorAction SilentlyContinue)
}
# Runs a native command with its output, stderr included, streamed to $Log or dropped.
function Invoke-Quiet([scriptblock]$Command, [string]$Log) {
# Under "Stop", 2>&1 turns every stderr line of a native command into a terminating error.
$ErrorActionPreference = "Continue"
$lines = {
& $Command 2>&1 | ForEach-Object {
# "$_" turns a blank stderr line into the text System.Management.Automation.RemoteException.
if ($_ -isnot [System.Management.Automation.ErrorRecord]) { $_ }
elseif ($null -ne $_.TargetObject) { $_.TargetObject }
else { $_.Exception.Message }
}
}
if ($Log) { & $lines | Out-File -Encoding utf8 -LiteralPath $Log } else { & $lines | Out-Null }
}
function Request-Install([string]$What, [string]$Command) {
Write-Host "Missing: $What"
if (Ask "Install it now with: $Command ?") {
& cmd /c $Command
if ($LASTEXITCODE -ne 0) { throw "Installing $What failed." }
Write-Host "Installed. Open a new terminal so PATH picks it up, then run this again."
} else {
Write-Host "To install it yourself, run:"
Write-Host " $Command"
}
exit 1
}
if (-not $Arch) {
if ($env:PROCESSOR_ARCHITECTURE -eq "ARM64") { $Arch = "arm64" } else { $Arch = "x64" }
}
# --- System tools -------------------------------------------------------------
if (-not (Has "git")) { Request-Install "Git" "build_win.bat --install-deps" }
# Python: the py launcher, else a python.exe that is not the Microsoft Store stub.
$Python = $null
if (Has "py") {
Invoke-Quiet { & py -3 --version }
if ($LASTEXITCODE -eq 0) { $Python = @("py", "-3") }
}
if (-not $Python -and (Has "python")) {
Invoke-Quiet { & python --version }
if ($LASTEXITCODE -eq 0) { $Python = @("python") }
}
if (-not $Python) { Request-Install "Python 3" "winget install -e --id Python.Python.3.12" }
$PyExe = $Python[0]
$PyArgs = @($Python | Select-Object -Skip 1)
# Visual Studio provides the compiler, and its CMake component provides CMake and Ninja.
$Vswhere = Join-Path ${env:ProgramFiles(x86)} "Microsoft Visual Studio\Installer\vswhere.exe"
$VsPath = $null
if (Test-Path $Vswhere) {
$VsPath = & $Vswhere -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath
}
if (-not $VsPath) { Request-Install "Visual Studio with the C++ tools" "build_win.bat --install-vs buildtools" }
# Load the developer environment, as build_win.bat does.
$HostArch = if ($env:PROCESSOR_ARCHITECTURE -eq "ARM64") { "arm64" } else { "x64" }
$VsDevCmd = Join-Path $VsPath "Common7\Tools\VsDevCmd.bat"
# Ignores VsDevCmd's exit code, as build_win.bat does, and checks the variables it sets
# before applying any, cleared in cmd so values inherited from a developer shell do not count.
$envLines = & cmd /c "set VCToolsInstallDir=& set WindowsSdkDir=& `"$VsDevCmd`" -arch=$Arch -host_arch=$HostArch -no_logo >nul 2>nul & set"
if (-not ($envLines -match '^VCToolsInstallDir=.') -or -not ($envLines -match '^WindowsSdkDir=.')) {
throw "Loading the Visual Studio $Arch environment failed. Run `"$VsDevCmd`" -arch=$Arch -host_arch=$HostArch in cmd to see why."
}
foreach ($line in $envLines) {
$i = $line.IndexOf("=")
if ($i -gt 0) { Set-Item -Path ("env:" + $line.Substring(0, $i)) -Value $line.Substring($i + 1) }
}
if (-not (Has "cmake")) { Request-Install "CMake" "build_win.bat --install-deps" }
if (-not (Has "ninja")) { Request-Install "Ninja" "winget install -e --id Ninja-build.Ninja" }
# --- clang-tidy ---------------------------------------------------------------
$Requirements = Join-Path $Root "scripts\clang_tidy_requirements.txt"
$Pinned = ((Get-Content $Requirements | Select-String '^clang-tidy==(.+)$').Matches[0].Groups[1].Value).Trim()
$Venv = Join-Path $BuildDir "clang-tidy-venv"
$ClangTidy = $env:CLANG_TIDY
function Test-Pinned([string]$Exe) {
if (-not $Exe -or -not (Test-Path $Exe)) { return $false }
return [bool]((& $Exe --version) -match "version $([regex]::Escape($Pinned))")
}
if (-not $ClangTidy) {
$ClangTidy = Join-Path $Venv "Scripts\clang-tidy.exe"
if (-not (Test-Pinned $ClangTidy)) {
if (Ask "clang-tidy $Pinned (the version CI uses) is not installed. Install it into $Venv?") {
New-Item -ItemType Directory -Force -Path $BuildDir | Out-Null
& $PyExe @PyArgs -m venv $Venv
if ($LASTEXITCODE -ne 0) { throw "Could not create a Python virtual environment." }
& "$Venv\Scripts\python.exe" -m pip install --quiet --upgrade pip
& "$Venv\Scripts\python.exe" -m pip install --quiet -r $Requirements
if ($LASTEXITCODE -ne 0) { throw "Installing clang-tidy $Pinned failed." }
} else {
Write-Host "To install it yourself, run:"
Write-Host " $($Python -join ' ') -m venv $Venv"
Write-Host " $Venv\Scripts\python.exe -m pip install -r scripts\clang_tidy_requirements.txt"
exit 1
}
}
}
if (-not (Test-Pinned $ClangTidy)) {
Write-Warning "$ClangTidy is not clang-tidy $Pinned, so results may differ from CI."
}
# --- Dependencies -------------------------------------------------------------
# build_win.bat names the tree after the compiler and architecture: deps\build for cl,
# deps\build-clang for clang-cl, with -arm64 appended on ARM64.
$Suffix = if ($Arch -eq "arm64") { "-arm64" } else { "" }
$Compiler = "cl"
# A configured build directory remembers where its dependencies are.
$Cache = Join-Path $BuildDir "CMakeCache.txt"
if (-not $DepsDir -and (Test-Path $Cache)) {
$m = Select-String -Path $Cache -Pattern '^DEP_BUILD_DIR:[A-Z]*=(.+)$' | Select-Object -First 1
if ($m) { $DepsDir = $m.Matches[0].Groups[1].Value }
}
if (-not $DepsDir) {
if (Test-Path "deps\build$Suffix\OrcaSlicer_dep") {
$DepsDir = "deps\build$Suffix"
} elseif (Test-Path "deps\build-clang$Suffix\OrcaSlicer_dep") {
$DepsDir = "deps\build-clang$Suffix"
}
}
if ($DepsDir -and ($DepsDir -match 'clang')) { $Compiler = "clang-cl" }
if (-not $DepsDir -or -not (Test-Path (Join-Path $DepsDir "OrcaSlicer_dep"))) {
$BuildDeps = "build_win.bat -d --arch $Arch"
Write-Host "OrcaSlicer's dependencies are not built."
if (Ask "Build them now with $BuildDeps? This takes a while.") {
& cmd /c $BuildDeps
if ($LASTEXITCODE -ne 0) { throw "Building the dependencies failed." }
$DepsDir = "deps\build$Suffix"
} else {
Write-Host "Build them with $BuildDeps, or point to an existing build with -DepsDir."
exit 1
}
}
$DepsDir = (Resolve-Path $DepsDir).Path
if ($Compiler -eq "clang-cl" -and -not (Has "clang-cl")) {
Request-Install "clang-cl (the Visual Studio C++ Clang tools)" "build_win.bat --install-vs buildtools"
}
# --- Compile database ---------------------------------------------------------
# The same configure as CI, with Ninja so CMake writes compile_commands.json. Forward
# slashes keep CMake from reading a backslash as an escape.
$cmakeArgs = @("-S", ".", "-B", $BuildDir, "-G", "Ninja", "-DCMAKE_BUILD_TYPE=Release",
"-DCMAKE_C_COMPILER=$Compiler", "-DCMAKE_CXX_COMPILER=$Compiler",
"-DCMAKE_EXPORT_COMPILE_COMMANDS=ON", "-DSLIC3R_PCH=OFF", "-DORCA_TOOLS=ON", "-DBUILD_TESTS=ON",
"-DDEP_BUILD_DIR=$($DepsDir -replace '\\', '/')")
Write-Host "Configuring $BuildDir with $Compiler"
New-Item -ItemType Directory -Force -Path $BuildDir | Out-Null
$Log = Join-Path $BuildDir "configure.log"
Invoke-Quiet { & cmake @cmakeArgs } $Log
if ($LASTEXITCODE -ne 0) {
Get-Content -LiteralPath $Log -Tail 20
throw "Configuring failed; the full log is in $Log."
}
$HashLog = Join-Path $BuildDir "git_commit_hash.log"
Invoke-Quiet { & cmake --build $BuildDir --target git_commit_hash_header } $HashLog
if ($LASTEXITCODE -ne 0) {
Get-Content -LiteralPath $HashLog -Tail 20
throw "Generating git_commit_hash.h failed; the full log is in $HashLog."
}
# --- Base revision ------------------------------------------------------------
if (-not $Base) {
$Remote = "origin"
foreach ($line in (& git remote -v)) {
if ($line -match '^(\S+)\s+\S*github\.com[:/]OrcaSlicer/OrcaSlicer(\.git)?\s+\(fetch\)') {
$Remote = $Matches[1]
break
}
}
if (-not $NoFetch) {
& git fetch --quiet $Remote main
if ($LASTEXITCODE -ne 0) { throw "git fetch $Remote main failed." }
}
$Base = "$Remote/main"
}
Write-Host "Comparing against $Base"
# --- Run ----------------------------------------------------------------------
$diffArgs = @("scripts\clang_tidy_diff.py", "-p", $BuildDir, "--base", $Base, "--clang-tidy", $ClangTidy)
if ($Jobs -gt 0) { $diffArgs += @("-j", "$Jobs") }
if ($Fix) { $diffArgs += @("--", "--fix") }
& $PyExe @PyArgs @diffArgs
exit $LASTEXITCODE
+233
View File
@@ -0,0 +1,233 @@
#!/usr/bin/env bash
# Runs the clang-tidy check that gates pull requests (.github/workflows/clang_tidy.yml)
# on your branch, so its findings match what CI reports. Linux and macOS.
#
# scripts/run_clang_tidy.sh check your changes against OrcaSlicer's main
# scripts/run_clang_tidy.sh --fix also add the missing includes it names
#
# It configures a separate build directory (build-tidy) without the precompiled
# header, installs the pinned clang-tidy into a virtual environment inside it, and
# runs scripts/clang_tidy_diff.py the way CI does. Uncommitted changes are checked too.
set -euo pipefail
usage() {
cat <<'EOF'
Usage: scripts/run_clang_tidy.sh [options]
-b, --base REV revision to compare against (default: main of the remote that
points at OrcaSlicer/OrcaSlicer, else origin/main)
--no-fetch do not fetch that remote's main first
-B, --build-dir DIR build directory for the compile database (default: build-tidy)
-d, --deps-dir DIR dependency build directory (default: deps/build on Linux,
deps/build/<arch> on macOS)
-j, --jobs N parallel clang-tidy runs (default: all cores)
--fix apply clang-tidy's fixes (adds the missing includes)
-y, --yes install missing tools without asking
-h, --help show this help
EOF
}
ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
cd "$ROOT"
BASE=""
FETCH=1
BUILD_DIR=build-tidy
DEPS_DIR=""
JOBS=""
FIX=0
YES=0
while [ $# -gt 0 ]; do
case "$1" in
-b|--base) BASE="$2"; shift 2 ;;
--no-fetch) FETCH=0; shift ;;
-B|--build-dir) BUILD_DIR="$2"; shift 2 ;;
-d|--deps-dir) DEPS_DIR="$2"; shift 2 ;;
-j|--jobs) JOBS="$2"; shift 2 ;;
--fix) FIX=1; shift ;;
-y|--yes) YES=1; shift ;;
-h|--help) usage; exit 0 ;;
*) echo "Unknown option: $1" >&2; usage >&2; exit 2 ;;
esac
done
case "$BUILD_DIR" in
/*) ;;
*) BUILD_DIR="$ROOT/$BUILD_DIR" ;;
esac
OS=$(uname -s)
case "$OS" in
Linux) ;;
Darwin) ;;
*) echo "Unsupported system $OS. On Windows, use scripts/run_clang_tidy.ps1." >&2; exit 1 ;;
esac
# Ask before installing anything. Without a terminal, or with "no", print the
# command instead so it can be run by hand.
ask() {
[ "$YES" = 1 ] && return 0
[ -t 0 ] || return 1
local reply
read -r -p "$1 [y/N] " reply
[[ "$reply" =~ ^[Yy] ]]
}
# --- System tools -------------------------------------------------------------
missing=()
command -v git >/dev/null || missing+=(git)
command -v python3 >/dev/null || missing+=(python3)
command -v cmake >/dev/null || missing+=(cmake)
command -v ninja >/dev/null || missing+=(ninja)
if [ "$OS" = Linux ]; then
# CI builds its compile database with clang; another compiler's flags change what
# clang-tidy sees.
command -v clang >/dev/null && command -v clang++ >/dev/null || missing+=(clang)
fi
if [ ${#missing[@]} -gt 0 ]; then
echo "Missing: ${missing[*]}"
install_cmd=""
if [ "$OS" = Darwin ]; then
pkgs=()
for m in "${missing[@]}"; do
case "$m" in
git|python3|cmake|ninja) pkgs+=("${m/python3/python}") ;;
esac
done
if command -v brew >/dev/null; then
install_cmd="brew install ${pkgs[*]}"
else
echo "Install Homebrew from https://brew.sh, then run: brew install ${pkgs[*]}" >&2
exit 1
fi
elif command -v apt-get >/dev/null; then
pkgs=()
for m in "${missing[@]}"; do
case "$m" in
ninja) pkgs+=(ninja-build) ;;
python3) pkgs+=(python3 python3-venv) ;;
*) pkgs+=("$m") ;;
esac
done
install_cmd="sudo apt-get install -y ${pkgs[*]}"
elif command -v dnf >/dev/null; then
install_cmd="sudo dnf install -y ${missing[*]/ninja/ninja-build}"
elif command -v pacman >/dev/null; then
install_cmd="sudo pacman -S --needed ${missing[*]/python3/python}"
else
echo "Install ${missing[*]} with your package manager and run this again." >&2
exit 1
fi
if ask "Install them now with: $install_cmd ?"; then
$install_cmd
else
echo "To install them yourself, run:" >&2
echo " $install_cmd" >&2
exit 1
fi
fi
# --- clang-tidy ---------------------------------------------------------------
REQUIREMENTS="$ROOT/scripts/clang_tidy_requirements.txt"
PINNED=$(sed -n 's/^clang-tidy==//p' "$REQUIREMENTS")
VENV="$BUILD_DIR/clang-tidy-venv"
if [ -n "${CLANG_TIDY:-}" ]; then
# Set by the caller: use it as is.
:
else
CLANG_TIDY="$VENV/bin/clang-tidy"
if [ ! -x "$CLANG_TIDY" ] || ! "$CLANG_TIDY" --version | grep -q "version $PINNED"; then
if ask "clang-tidy $PINNED (the version CI uses) is not installed. Install it into $VENV?"; then
mkdir -p "$BUILD_DIR"
if ! python3 -m venv "$VENV"; then
echo "Could not create a Python virtual environment." >&2
[ "$OS" = Linux ] && echo "On Debian or Ubuntu, install it with: sudo apt-get install -y python3-venv" >&2
exit 1
fi
"$VENV/bin/pip" install --quiet --upgrade pip
"$VENV/bin/pip" install --quiet -r "$REQUIREMENTS"
else
echo "To install it yourself, run:" >&2
echo " python3 -m venv $VENV && $VENV/bin/pip install -r scripts/clang_tidy_requirements.txt" >&2
exit 1
fi
fi
fi
if ! "$CLANG_TIDY" --version | grep -q "version $PINNED"; then
echo "Warning: $CLANG_TIDY is not clang-tidy $PINNED, so results may differ from CI." >&2
fi
# --- Dependencies -------------------------------------------------------------
# A configured build directory remembers where its dependencies are.
if [ -z "$DEPS_DIR" ] && [ -f "$BUILD_DIR/CMakeCache.txt" ]; then
DEPS_DIR=$(sed -n 's/^DEP_BUILD_DIR:[A-Z]*=//p' "$BUILD_DIR/CMakeCache.txt")
fi
if [ "$OS" = Darwin ]; then
ARCH=$(uname -m)
DEPS_DIR="${DEPS_DIR:-deps/build/$ARCH}"
BUILD_DEPS_CMD="./build_release_macos.sh -d -a $ARCH"
else
DEPS_DIR="${DEPS_DIR:-deps/build}"
BUILD_DEPS_CMD="./build_linux.sh -d"
fi
case "$DEPS_DIR" in
/*) ;;
*) DEPS_DIR="$ROOT/$DEPS_DIR" ;;
esac
if [ ! -d "$DEPS_DIR/OrcaSlicer_dep/usr/local" ]; then
echo "OrcaSlicer's dependencies are not built in $DEPS_DIR."
if ask "Build them now with $BUILD_DEPS_CMD? This takes a while."; then
$BUILD_DEPS_CMD
else
echo "Build them with $BUILD_DEPS_CMD, or point to an existing build with --deps-dir." >&2
exit 1
fi
fi
# --- Compile database ---------------------------------------------------------
# The same configure as CI. DEP_BUILD_DIR is named outright: CMake would otherwise
# derive it from the build directory's name.
cmake_args=(-S . -B "$BUILD_DIR" -G Ninja -DCMAKE_BUILD_TYPE=Release
-DCMAKE_EXPORT_COMPILE_COMMANDS=ON -DSLIC3R_PCH=OFF -DORCA_TOOLS=ON -DBUILD_TESTS=ON
-DDEP_BUILD_DIR="$DEPS_DIR")
if [ "$OS" = Darwin ]; then
cmake_args+=(-DCMAKE_OSX_ARCHITECTURES="$ARCH" "-DCMAKE_IGNORE_PREFIX_PATH=/opt/local;/usr/local;/opt/homebrew")
else
cmake_args+=(-DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++)
fi
echo "Configuring $BUILD_DIR"
mkdir -p "$BUILD_DIR"
if ! cmake "${cmake_args[@]}" >"$BUILD_DIR/configure.log" 2>&1; then
tail -n 20 "$BUILD_DIR/configure.log" >&2
echo "Configuring failed; the full log is in $BUILD_DIR/configure.log." >&2
[ "$OS" = Linux ] && echo "Missing system libraries? Install them with: ./build_linux.sh -u" >&2
exit 1
fi
cmake --build "$BUILD_DIR" --target git_commit_hash_header >/dev/null
# --- Base revision ------------------------------------------------------------
if [ -z "$BASE" ]; then
REMOTE=$(git remote -v | awk '/github\.com[:\/]OrcaSlicer\/OrcaSlicer(\.git)? \(fetch\)/ { print $1; exit }')
REMOTE="${REMOTE:-origin}"
if [ "$FETCH" = 1 ]; then
git fetch --quiet "$REMOTE" main
fi
BASE="$REMOTE/main"
fi
echo "Comparing against $BASE"
# --- Run ----------------------------------------------------------------------
args=(-p "$BUILD_DIR" --base "$BASE" --clang-tidy "$CLANG_TIDY")
[ -n "$JOBS" ] && args+=(-j "$JOBS")
[ "$FIX" = 1 ] && args+=(-- --fix)
exec python3 scripts/clang_tidy_diff.py "${args[@]}"
+171
View File
@@ -0,0 +1,171 @@
#!/usr/bin/env python3
"""Tests for the diff handling in scripts/clang_tidy_diff.py (stdlib unittest, no
external deps).
Run from the repo root: python -m unittest discover -s scripts/tests -v
"""
import json
import os
import subprocess
import sys
import tempfile
import unittest
from unittest import mock
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
import clang_tidy_diff # noqa: E402
DIFF = """\
diff --git a/src/libslic3r/Color.cpp b/src/libslic3r/Color.cpp
index 1111111..2222222 100644
--- a/src/libslic3r/Color.cpp
+++ b/src/libslic3r/Color.cpp
@@ -3,0 +4 @@
+#include <cassert>
@@ -8 +8,0 @@
-#include "libslic3r/Point.hpp"
@@ -20,2 +21,3 @@ void f()
- old();
- old();
+ a();
+ b();
+ c();
@@ -40 +42,0 @@ void g()
- gone();
diff --git a/src/libslic3r/New.hpp b/src/libslic3r/New.hpp
new file mode 100644
--- /dev/null
+++ b/src/libslic3r/New.hpp
@@ -0,0 +1,2 @@
+#pragma once
+int f();
diff --git a/src/libslic3r/Old.cpp b/src/libslic3r/Renamed.cpp
similarity index 100%
rename from src/libslic3r/Old.cpp
rename to src/libslic3r/Renamed.cpp
"""
class TestParseChangedLines(unittest.TestCase):
def setUp(self):
self.changed = clang_tidy_diff.parse_diff(DIFF)
def test_added_and_replaced_hunks_become_line_ranges(self):
self.assertEqual(self.changed["src/libslic3r/Color.cpp"].lines, [[4, 4], [21, 23]])
def test_deleted_includes_are_collected(self):
self.assertEqual(self.changed["src/libslic3r/Color.cpp"].removed_includes, {"libslic3r/Point.hpp"})
self.assertEqual(self.changed["src/libslic3r/New.hpp"].removed_includes, set())
def test_new_file_covers_every_line(self):
self.assertEqual(self.changed["src/libslic3r/New.hpp"].lines, [[1, 2]])
def test_pure_rename_has_no_changed_lines(self):
self.assertNotIn("src/libslic3r/Renamed.cpp", self.changed)
def test_path_with_a_space_drops_the_tab_git_appends(self):
changed = clang_tidy_diff.parse_diff("+++ b/src/libslic3r/Foo Bar.cpp\t\n@@ -1,0 +2 @@\n+int x;\n")
self.assertEqual(changed["src/libslic3r/Foo Bar.cpp"].lines, [[2, 2]])
class TestNamesRemovedInclude(unittest.TestCase):
def test_matches_however_the_include_was_spelled(self):
removed = {"Point.hpp", "cassert"}
self.assertTrue(clang_tidy_diff.names_removed_include("<cassert>", removed))
self.assertTrue(clang_tidy_diff.names_removed_include("<libslic3r/Point.hpp>", removed))
self.assertTrue(clang_tidy_diff.names_removed_include('"Point.hpp"', {"libslic3r/Point.hpp"}))
def test_other_headers_and_no_suggestion_do_not_match(self):
removed = {"libslic3r/Point.hpp"}
self.assertFalse(clang_tidy_diff.names_removed_include("<libslic3r/MultiPoint.hpp>", removed))
self.assertFalse(clang_tidy_diff.names_removed_include("<vector>", removed))
self.assertFalse(clang_tidy_diff.names_removed_include("", removed))
class TestIsChecked(unittest.TestCase):
def test_project_sources_and_headers(self):
for path in ("src/libslic3r/Color.cpp", "src/slic3r/GUI/Tab.hpp", "tests/fff_print/test_flow.cpp",
"src/libslic3r/Format/bbs_3mf.h"):
self.assertTrue(clang_tidy_diff.is_checked(path), path)
def test_vendored_code_other_languages_and_other_dirs(self):
for path in ("src/glad/src/gl.c", "src/glad/include/glad/gl.h", "tests/catch2/src/catch.hpp",
"deps_src/imgui/imgui.cpp", "src/slic3r/Utils/MacUtils.mm", "src/CMakeLists.txt"):
self.assertFalse(clang_tidy_diff.is_checked(path), path)
FIXES = """\
---
MainSourceFile: '/repo/src/libslic3r/Color.cpp'
Diagnostics:
- DiagnosticName: misc-include-cleaner
DiagnosticMessage:
Message: 'no header providing "assert" is directly included'
FilePath: '/repo/src/libslic3r/Color.cpp'
FileOffset: 1974
Replacements:
- FilePath: '/repo/src/libslic3r/Color.cpp'
Offset: 39
Length: 0
ReplacementText: "#include <cassert>\\n"
Level: Error
- DiagnosticName: misc-include-cleaner
DiagnosticMessage:
Message: 'no header providing "Slic3r::comExpert" is directly included'
FilePath: '/repo/src/libslic3r/Color.cpp'
FileOffset: 2148
Replacements: []
Level: Error
...
"""
class TestParseSuggestedIncludes(unittest.TestCase):
def test_maps_each_message_to_the_include_its_fix_inserts(self):
with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, "fixes.yaml")
with open(path, "w", encoding="utf-8") as f:
f.write(FIXES)
self.assertEqual(clang_tidy_diff.parse_suggested_includes(path),
{'no header providing "assert" is directly included': "<cassert>"})
def test_missing_file_means_no_suggestions(self):
self.assertEqual(clang_tidy_diff.parse_suggested_includes("/nonexistent/fixes.yaml"), {})
class TestSubprocessCalls(unittest.TestCase):
def run_patched(self, function, *args, returncode=0, stdout=""):
done = subprocess.CompletedProcess([], returncode, stdout, "")
with mock.patch.object(clang_tidy_diff.subprocess, "run", return_value=done) as run, \
mock.patch.object(clang_tidy_diff.os.path, "normpath", wraps=os.path.normpath) as normpath:
result = function(*args)
return result, run.call_args, normpath
def test_line_filter_names_the_file_with_native_separators(self):
_, call, normpath = self.run_patched(clang_tidy_diff.run_clang_tidy, "clang-tidy", "build",
"src/libslic3r/Color.cpp", [[4, 4]], [])
line_filter = next(arg for arg in call.args[0] if arg.startswith("--line-filter="))
self.assertEqual(json.loads(line_filter.split("=", 1)[1]),
[{"name": os.path.join("src", "libslic3r", "Color.cpp"), "lines": [[4, 4]]}])
normpath.assert_any_call("src/libslic3r/Color.cpp")
def test_changed_files_reads_non_ascii_paths_and_text_as_utf8(self):
diff = "+++ b/src/libslic3r/Über.cpp\n@@ -1,0 +2 @@\n+// 打印\n"
files, call, _ = self.run_patched(clang_tidy_diff.changed_files, "base", stdout=diff)
self.assertIn("core.quotePath=false", call.args[0])
self.assertEqual(call.kwargs["encoding"], "utf-8")
self.assertEqual(files["src/libslic3r/Über.cpp"].lines, [[2, 2]])
def test_clang_tidy_and_git_show_output_is_decoded_as_utf8(self):
_, call, _ = self.run_patched(clang_tidy_diff.run_clang_tidy, "clang-tidy", "build",
"src/libslic3r/Color.cpp", None, [])
self.assertEqual(call.kwargs["encoding"], "utf-8")
_, call, _ = self.run_patched(clang_tidy_diff.errors_alone_at, "base", "clang-tidy", "build",
"src/libslic3r/Color.hpp", returncode=128)
self.assertEqual(call.kwargs["encoding"], "utf-8")
if __name__ == "__main__":
unittest.main()