|
| 1 | +"""Find bad third-party usage in cmake. |
| 2 | +
|
| 3 | +This script searches for cmake function invocations that might indicate |
| 4 | +the addition of new third-party dependencies outside of the intended |
| 5 | +process (3rdparty/README.md). |
| 6 | +""" |
| 7 | + |
| 8 | +import argparse |
| 9 | +import collections |
| 10 | +import logging |
| 11 | +import os |
| 12 | +import pathlib |
| 13 | +import sys |
| 14 | +from typing import Generator |
| 15 | + |
| 16 | +logger = logging.getLogger(__name__) |
| 17 | + |
| 18 | +IGNORE_PATTERNS = [ |
| 19 | + ".*", # Hidden files and directories, like .git |
| 20 | + # This is where we actually want third-party stuff to go |
| 21 | + "3rdparty/CMakeLists.txt", |
| 22 | + # Historical use of ExternalProject_Add that is not yet migrated to 3rdparty |
| 23 | + "cpp/tensorrt_llm/deep_ep/CMakeLists.txt", |
| 24 | + # Historical build that is not included in the wheel build and thus exempt |
| 25 | + # from the third-party process. |
| 26 | + "triton_backend/inflight_batcher_llm/*", |
| 27 | + "build", # Default build directory |
| 28 | + "cpp/build", # Default extension module build directory |
| 29 | +] |
| 30 | + |
| 31 | + |
| 32 | +class DirectoryFilter: |
| 33 | + """Callable filter for directories. |
| 34 | +
|
| 35 | + This filter excludes any paths matching IGNORE_PATTERNS. |
| 36 | + """ |
| 37 | + |
| 38 | + def __init__(self, parent: pathlib.Path): |
| 39 | + self.parent = parent |
| 40 | + |
| 41 | + def __call__(self, name: str) -> bool: |
| 42 | + path = self.parent / name |
| 43 | + if any(path.match(pat) for pat in IGNORE_PATTERNS): |
| 44 | + return False |
| 45 | + return True |
| 46 | + |
| 47 | + |
| 48 | +class FileFilter: |
| 49 | + """Callable filter for file entries. |
| 50 | +
|
| 51 | + In order of precedence: |
| 52 | +
|
| 53 | + 1. excludes any paths matching IGNORE_PATTERNS |
| 54 | + 2. includes only CMakeLists.txt and *.cmake files |
| 55 | + """ |
| 56 | + |
| 57 | + def __init__(self, parent: pathlib.Path): |
| 58 | + self.parent = parent |
| 59 | + |
| 60 | + def __call__(self, name: str) -> bool: |
| 61 | + path = self.parent / name |
| 62 | + if any(path.match(pat) for pat in IGNORE_PATTERNS): |
| 63 | + return False |
| 64 | + |
| 65 | + if name == "CMakeLists.txt": |
| 66 | + return True |
| 67 | + elif name.endswith(".cmake"): |
| 68 | + return True |
| 69 | + |
| 70 | + return False |
| 71 | + |
| 72 | + |
| 73 | +def yield_sources(src_tree: pathlib.Path): |
| 74 | + """Perform a filesystem walk and yield any paths that should be scanned.""" |
| 75 | + for parent, dirs, files in os.walk(src_tree): |
| 76 | + parent = pathlib.Path(parent) |
| 77 | + relpath_parent = parent.relative_to(src_tree) |
| 78 | + |
| 79 | + # Filter out ignored directories |
| 80 | + dirs[:] = sorted(filter(DirectoryFilter(relpath_parent), dirs)) |
| 81 | + |
| 82 | + for file in sorted(filter(FileFilter(relpath_parent), files)): |
| 83 | + yield parent / file |
| 84 | + |
| 85 | + |
| 86 | +ThirdpartyViolation = collections.namedtuple( |
| 87 | + "ThirdpartyViolation", ["srcfile", "lineno", "note", "line"] |
| 88 | +) |
| 89 | + |
| 90 | + |
| 91 | +def yield_potential_thirdparty( |
| 92 | + fullpath: pathlib.Path, relpath: pathlib.Path |
| 93 | +) -> Generator[ThirdpartyViolation, None, None]: |
| 94 | + """Look for bad patterns with third-party sources. |
| 95 | +
|
| 96 | + Look for patterns that might indicate the addition of new third-party |
| 97 | + sources. |
| 98 | + """ |
| 99 | + with fullpath.open("r", encoding="utf-8") as infile: |
| 100 | + for lineno, line in enumerate(infile): |
| 101 | + lineno += 1 # Make line numbers 1-based |
| 102 | + |
| 103 | + if "FetchContent_Declare" in line: |
| 104 | + note = "Invalid use of FetchContent_Declare outside of 3rdparty/CMakeLists.txt" |
| 105 | + yield ThirdpartyViolation(relpath, lineno, note, line.strip()) |
| 106 | + |
| 107 | + if "ExternalProject_Add" in line: |
| 108 | + note = "Invalid use of ExternalProject_Add outside of 3rdparty/CMakeLists.txt" |
| 109 | + yield ThirdpartyViolation(relpath, lineno, note, line.strip()) |
| 110 | + |
| 111 | + |
| 112 | +def check_sources(src_tree: pathlib.Path) -> int: |
| 113 | + """Common entry-point between main() and pytest. |
| 114 | +
|
| 115 | + Prints any violations to stderr and returns non-zero if any violations are |
| 116 | + found. |
| 117 | + """ |
| 118 | + violations = [] |
| 119 | + for filepath in yield_sources(src_tree): |
| 120 | + for violation in yield_potential_thirdparty(filepath, filepath.relative_to(src_tree)): |
| 121 | + violations.append(violation) |
| 122 | + |
| 123 | + if not violations: |
| 124 | + return 0 |
| 125 | + |
| 126 | + for violation in sorted(violations): |
| 127 | + sys.stderr.write( |
| 128 | + f"{violation.srcfile}:{violation.lineno}: {violation.note}\n" |
| 129 | + + f" {violation.line}\n" |
| 130 | + ) |
| 131 | + |
| 132 | + logger.error( |
| 133 | + "Found %d potential third-party violations. " |
| 134 | + "If you are trying to add a new third-party dependency, " |
| 135 | + "please follow the instructions in 3rdparty/cpp-thirdparty.md", |
| 136 | + len(violations), |
| 137 | + ) |
| 138 | + return 1 |
| 139 | + |
| 140 | + |
| 141 | +def test_cmake_listfiles(): |
| 142 | + """Test that no third-party violations are found in the source tree.""" |
| 143 | + source_tree = pathlib.Path(__file__).parents[1] |
| 144 | + result = check_sources(source_tree) |
| 145 | + assert result == 0 |
| 146 | + |
| 147 | + |
| 148 | +def main(): |
| 149 | + parser = argparse.ArgumentParser(description="__doc__") |
| 150 | + parser.add_argument( |
| 151 | + "--src-tree", |
| 152 | + default=pathlib.Path.cwd(), |
| 153 | + type=pathlib.Path, |
| 154 | + help="Path to the source tree, defaults to current directory", |
| 155 | + ) |
| 156 | + args = parser.parse_args() |
| 157 | + result = check_sources(args.src_tree) |
| 158 | + sys.exit(result) |
| 159 | + |
| 160 | + |
| 161 | +if __name__ == "__main__": |
| 162 | + logging.basicConfig(level=logging.INFO) |
| 163 | + main() |
0 commit comments