From 42e39a2aca8b10208f47130d8e48e0191124a664 Mon Sep 17 00:00:00 2001 From: Yufeng He <40085740+he-yufeng@users.noreply.github.com> Date: Thu, 22 Oct 2026 15:35:48 +0800 Subject: [PATCH] feat: runtime-requirements map (Python/Node floors, services, GPU, OS, Docker) --- README.md | 4 + README_CN.md | 8 + backend/models.py | 9 + backend/routers/project.py | 4 + backend/services/runreqs.py | 373 ++++++++++++++++++++++++++++++++ frontend/src/lib/api.ts | 9 + frontend/src/pages/Overview.tsx | 48 ++++ tests/test_runreqs.py | 150 +++++++++++++ 8 files changed, 605 insertions(+) create mode 100644 backend/services/runreqs.py create mode 100644 tests/test_runreqs.py diff --git a/README.md b/README.md index 7ebd712..c1fa56b 100644 --- a/README.md +++ b/README.md @@ -102,6 +102,10 @@ Not every file needs a comment, but the ones that other files lean on heavily an Hand a folder to someone and get a folder back — what did they actually change? Drop the before and after versions into the comparison page and CodeABC lists every added, deleted and modified file with a readable diff, and tells you whether the new version picked up any new risk warnings along the way. A file it cannot read on one side is reported as "not compared" rather than silently treated as deleted, and the risk delta matches warnings by what they are, not by line number, so a shifted line does not look like a fixed bug. Everything runs locally: no code is executed, no API key is needed, and nothing leaves your machine. +### Will It Run on My Machine? + +Before installing anything, you want to know what you are signing up for: does this project need a specific Python or Node version, a database server running in the background, an NVIDIA graphics card, or a particular operating system? CodeABC reads the version pins in the project's manifests, the service clients in its dependencies and imports, GPU-shaped dependencies and CUDA source files, and OS-specific components, then lays out the answer in plain words, each item linked to the file it came from. A service that only shows up in a manifest but is never used in the code is marked as "maybe only for some features" rather than presented as a hard requirement. And when the project ships a Dockerfile, CodeABC says so, because that is usually the easy way out. Deterministic, no API key needed. + ## Tech Stack | Layer | Choice | Why | diff --git a/README_CN.md b/README_CN.md index 666d95b..1aaaf44 100644 --- a/README_CN.md +++ b/README_CN.md @@ -106,6 +106,14 @@ Cursor/VS Code 是给程序员用的瑞士军刀,码上懂是给普通人用 不是每个文件都需要注释,但那些被很多别的文件依赖、自己却几乎没有任何说明的文件,是最让新人头疼的。码上懂会按"有多核心"对比"有多缺说明"给每个文件打分,挑出那几个"只要有人在开头写几句话就最能帮到大家"的文件。它既是写文档的提示,也是读代码的向导:这几个文件通常正是最值得先搞懂的。 +### 这两个文件夹之间到底改了什么? + +把一个文件夹交出去、再拿回来一个文件夹——对方到底改了什么?把改前改后两个版本拖进对比页,码上懂会列出每个新增、删除和修改的文件,配上看得懂的 diff,并告诉你新版本有没有多出新的风险提醒。某一边读不出来的文件会如实标成"未能对比",不会悄悄当成被删除;风险对比按警告的内容对齐而不是按行号,所以行号挪了也不会看起来像"修好了一个 bug"。一切都在本地完成:不执行任何代码,不需要 API key,也没有任何东西离开你的电脑。 + +### 我的电脑跑得动吗? + +装任何依赖之前,先搞清楚一件事:这个项目要多新的 Python 或 Node?要不要先在后台开一个数据库服务?是不是得有一张英伟达显卡?挑不挑操作系统?码上懂从项目清单里读出版本要求,从依赖和代码里认出数据库等外部服务的客户端,找出 GPU 相关的依赖和 CUDA 源文件,以及只在某个操作系统上才有的组件,用大白话把答案列出来,每条都注明证据来自哪个文件。只在清单里出现、代码里没真用到的服务,会标成"可选/部分功能",不当成硬要求。如果项目带了 Dockerfile,也会直接告诉你——装了 Docker 的话,上面这些要求通常都可以跳过。全程确定性分析,不需要 API key。 + ## 技术栈 | 层 | 选择 | 理由 | diff --git a/backend/models.py b/backend/models.py index d3f73f1..1b1b8f6 100644 --- a/backend/models.py +++ b/backend/models.py @@ -372,6 +372,14 @@ class Dependency(BaseModel): purpose: str | None = None +class RunRequirement(BaseModel): + category: str # "python" | "node" | "service" | "gpu" | "os" | "container" + name: str # short label, e.g. 'Python >=3.10', 'PostgreSQL' + detail: str # the raw evidence (which file, which constraint) + note: str # plain-language explanation of what this means for the reader + required: bool = True # False = "only needed for some features / optional path" + + class ActivityWindow(BaseModel): commits: int = 0 authors: list[str] = [] @@ -493,6 +501,7 @@ class ProjectMeta(BaseModel): licenses: LicenseSummary | None = None complexity_files: list[ComplexFile] = [] dependencies: list[Dependency] = [] + run_requirements: list[RunRequirement] = [] security: SecuritySummary | None = None api_map: ApiMap | None = None activity: ActivitySummary | None = None diff --git a/backend/routers/project.py b/backend/routers/project.py index 2c56ede..6cc3f64 100644 --- a/backend/routers/project.py +++ b/backend/routers/project.py @@ -66,6 +66,7 @@ ReleaseAutomation, ReleaseSummary, RiskHotspot, + RunRequirement, ScheduledTask, SecurityFinding, SecuritySummary, @@ -113,6 +114,7 @@ release_map, report_export, risk, + runreqs, scanner, schedules, security, @@ -269,6 +271,7 @@ def _content_analyses( license_map = licenses.find_licenses(file_contents) complex_files = complexity.scan_complexity(file_contents) deps = dependencies.scan_dependencies(file_contents) + run_reqs = runreqs.scan_run_requirements(file_contents) sec = security.scan_security(file_contents) api = apimap.scan_api_routes(file_contents) doc = docs.assess_doc_coverage(file_contents) @@ -398,6 +401,7 @@ def _content_analyses( ) for d in deps["dependencies"] ], + "run_requirements": [RunRequirement(**r) for r in run_reqs["requirements"]], "security": SecuritySummary( total=sec["total"], critical=sec["critical"], diff --git a/backend/services/runreqs.py b/backend/services/runreqs.py new file mode 100644 index 0000000..e40b479 --- /dev/null +++ b/backend/services/runreqs.py @@ -0,0 +1,373 @@ +"""Runtime requirements: what kind of machine and services a project needs to run. + +The dependency list answers "which libraries get installed"; this map answers the +more basic question a non-programmer asks first: *will this thing run on my +machine at all?* Do I need a specific Python or Node version, a database server +running in the background, an NVIDIA graphics card, a particular operating +system — or is there a Docker escape hatch that skips all of it? + +Everything here is read off files CodeABC already loaded — version pins in +manifests, service client libraries in the dependency lists and imports, +GPU-shaped dependencies and CUDA sources, OS-specific imports, and the presence +of container files. Deterministic, no LLM, no network. + +:func:`scan_run_requirements` is pure over the file-contents mapping, so it is +unit-testable with plain strings and needs no repository. + +Honesty limits, kept on purpose: + +- A service found only in a manifest (not imported by scanned source) is marked + "可能在某些功能里用到" rather than required — plenty of projects declare + clients they barely use. +- The GPU note means "parts of this project expect an NVIDIA GPU". CPU-only + fallbacks are common; when no GPU signal exists we say nothing rather than + promising it runs everywhere. +- OS signals come from a small, honest set of imports/packages; absence of a + signal is not a portability guarantee. +""" + +from __future__ import annotations + +import re + +# --- version floors ----------------------------------------------------------- + +_REQUIRES_PYTHON_RE = re.compile(r"""requires-python\s*=\s*['"]([^'"]+)['"]""") +_PYPROJECT_FLAVOR_RE = re.compile(r"^\s*\[project\]", re.M) +_SETUP_CFG_REQUIRES_RE = re.compile(r"""python_requires\s*=\s*([><=!~0-9., ]+)""") +_PIPFILE_REQUIRES_RE = re.compile(r"""python(?:_full)?_version\s*=\s*['"]([0-9.]+)['"]""") +_RUNTIME_TXT_RE = re.compile(r"^python-([0-9.]+)\s*$", re.M) +_ENGINES_NODE_RE = re.compile(r"""['"]node['"]\s*:\s*['"]([^'"]+)['"]""") + +# --- service clients ---------------------------------------------------------- + +# canonical service -> (manifest package names, importable module names) +_SERVICES: dict[str, tuple[set[str], set[str]]] = { + "PostgreSQL": ( + {"psycopg", "psycopg2", "psycopg2-binary", "pg8000", "asyncpg"}, + {"psycopg", "psycopg2", "pg8000", "asyncpg"}, + ), + "MySQL": ( + {"pymysql", "mysqlclient", "mysql-connector-python", "aiomysql"}, + {"pymysql", "MySQLdb", "mysql", "aiomysql"}, + ), + "Redis": ( + {"redis", "aioredis", "ioredis"}, + {"redis", "aioredis"}, + ), + "MongoDB": ( + {"pymongo", "motor", "mongodb", "mongoose"}, + {"pymongo", "motor"}, + ), + "Elasticsearch": ( + {"elasticsearch", "elasticsearch8", "@elastic/elasticsearch"}, + {"elasticsearch"}, + ), + "Kafka": ( + {"kafka-python", "confluent-kafka", "aiokafka", "kafkajs"}, + {"kafka", "aiokafka", "confluent_kafka"}, + ), + "RabbitMQ": ( + {"pika", "aio-pika", "amqplib"}, + {"pika", "aio_pika", "amqp"}, + ), +} + +_SERVICE_NOTES = { + "PostgreSQL": ( + "一种常用的数据库服务器。光装 Python 包不够," + "还得有一台正在运行的 PostgreSQL(可以装在本机,也可以用云上的)。" + ), + "MySQL": "一种常用的数据库服务器。需要先有一台正在运行的 MySQL(本机安装或云服务都可以)。", + "Redis": "一个跑在后台的内存数据库,常用来做缓存或队列。需要先启动 Redis 服务。", + "MongoDB": "一种文档型数据库服务器。需要先有一台正在运行的 MongoDB。", + "Elasticsearch": "一个搜索引擎服务器,常用于全文检索。需要先部署并启动它。", + "Kafka": "一个消息队列服务器,常见于大型数据管道。需要先部署 Kafka 集群。", + "RabbitMQ": "一个消息队列服务器。需要先启动 RabbitMQ 服务。", +} + +# --- GPU / OS signals ---------------------------------------------------------- + +_GPU_PACKAGES = { + "torch", + "tensorflow", + "jax", + "jaxlib", + "cuda-python", + "cupy", + "vllm", + "flash-attn", +} +_CUDA_DEVICE_RE = re.compile(r"""['"]cuda(?::\d+)?['"]""") + +_OS_SIGNALS: dict[str, tuple[set[str], set[str], str]] = { + "windows_only": ( + {"pywin32", "pywintypes", "winreg"}, + {"winreg", "msvcrt", "pywintypes"}, + "Windows 专属:代码里用到了只有 Windows 才有的组件,其他系统跑不了这部分。", + ), + "mac_only": ( + {"pyobjc", "pyobjc-core"}, + {"pyobjc"}, + "macOS 专属:代码里用到了苹果系统特有的组件。", + ), + "posix_only": ( + set(), + {"fcntl", "termios", "pwd", "grp", "resource"}, + "类 Unix 系统(Linux/macOS)专属:用到了 Windows 没有的系统接口。", + ), +} + +_CONTAINER_FILES = { + "dockerfile", + "containerfile", + "docker-compose.yml", + "docker-compose.yaml", + "compose.yml", + "compose.yaml", +} + +# manifest files we read version pins / package names from +_MANIFEST_NAMES = re.compile( + r"(^|/)(pyproject\.toml|setup\.cfg|setup\.py|Pipfile|runtime\.txt|package\.json|requirements.*\.txt)$", + re.I, +) + +_IMPORT_RES = [ + re.compile(r"""(?m)^\s*(?:from|import)\s+([A-Za-z_][A-Za-z0-9_]*)"""), # python + re.compile(r"""require\(\s*['"]([A-Za-z0-9@][^'"]*)['"]\s*\)"""), # js require + re.compile(r"""(?m)^\s*import\s+.*?from\s+['"]([^'"]+)['"]"""), # js import +] +_PY_EXTS = (".py",) +_JS_EXTS = (".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs") + + +def _basename(path: str) -> str: + return path.rsplit("/", 1)[-1] + + +def _manifest_packages(content: str, name: str) -> set[str]: + """Pull rough package names out of a manifest's text. + + Deliberately tolerant: split requirements-style lines on version specifiers, + and collect quoted names in TOML/JSON dependency arrays. + """ + lower = name.lower() + found: set[str] = set() + if lower.endswith(".txt"): + for line in content.splitlines(): + line = line.strip() + if not line or line.startswith(("#", "-")): + continue + pkg = re.split(r"[<>=!~\[ ;]", line, maxsplit=1)[0].strip() + if pkg: + found.add(pkg.lower()) + else: + for quoted in re.findall(r"""['"]([A-Za-z0-9][A-Za-z0-9._/-]*)['"]""", content): + found.add(quoted.split("/")[-1].lower()) + return found + + +def _imported_modules(file_contents: dict[str, str]) -> set[str]: + """Top-level module/package names imported anywhere in the scanned source.""" + mods: set[str] = set() + for path, content in file_contents.items(): + lower = path.lower() + is_py = lower.endswith(_PY_EXTS) + is_js = lower.endswith(_JS_EXTS) + if not (is_py or is_js): + continue + if is_py: + for m in _IMPORT_RES[0].finditer(content): + mods.add(m.group(1)) + else: + for rx in _IMPORT_RES[1:]: + for m in rx.finditer(content): + name = m.group(1) + if not name.startswith("."): + mods.add(name.split("/")[0].lstrip("@")) + return mods + + +def scan_run_requirements(file_contents: dict[str, str]) -> dict: + """Collect what kind of machine and services the project needs to run. + + Args: + file_contents: mapping of path to file text (as CodeABC already read it). + + Returns ``{"requirements": [...]}`` where each requirement is + ``{"category", "name", "detail", "note", "required"}`` and ``category`` is + one of ``python``, ``node``, ``service``, ``gpu``, ``os`` or ``container``. + ``detail`` is the raw evidence (file + constraint); ``note`` is a + plain-language explanation; ``required`` is False for signals that only + appear in a manifest or dev-only context. + """ + reqs: list[dict] = [] + + # --- version floors --- + python_floor: tuple[str, str] | None = None # (constraint, source file) + node_floor: tuple[str, str] | None = None + + _DOTFILES = (".nvmrc", ".node-version", ".python-version") + for path, content in file_contents.items(): + base = _basename(path) + lower = base.lower() + if not _MANIFEST_NAMES.search(path) and lower not in _DOTFILES: + continue + + if lower == "pyproject.toml" and _PYPROJECT_FLAVOR_RE.search(content): + m = _REQUIRES_PYTHON_RE.search(content) + if m and python_floor is None: + python_floor = (m.group(1).strip(), path) + elif lower in ("setup.cfg", "setup.py"): + m = _SETUP_CFG_REQUIRES_RE.search(content) + if m and python_floor is None: + python_floor = (m.group(1).strip(), path) + elif lower == "pipfile": + m = _PIPFILE_REQUIRES_RE.search(content) + if m and python_floor is None: + python_floor = (f">={m.group(1)}", path) + elif lower == "runtime.txt": + m = _RUNTIME_TXT_RE.search(content) + if m and python_floor is None: + python_floor = (f"=={m.group(1)}", path) + elif lower == ".python-version": + ver = content.strip().splitlines()[0].strip() if content.strip() else "" + if ver and python_floor is None: + python_floor = (f"=={ver}", path) + elif lower == "package.json": + m = _ENGINES_NODE_RE.search(content) + if m and node_floor is None: + node_floor = (m.group(1).strip(), path) + elif lower in (".nvmrc", ".node-version"): + ver = content.strip().lstrip("v") + if ver and node_floor is None: + node_floor = (f"=={ver}", path) + + if python_floor: + constraint, source = python_floor + reqs.append( + { + "category": "python", + "name": f"Python {constraint}", + "detail": f"{source} 里声明了 Python 版本要求", + "note": ( + "电脑上装的 Python 版本要满足这个要求。" + "命令行里输入 python3 --version 就能看自己装的是几。" + ), + "required": True, + } + ) + if node_floor: + constraint, source = node_floor + reqs.append( + { + "category": "node", + "name": f"Node.js {constraint}", + "detail": f"{source} 里声明了 Node.js 版本要求", + "note": ( + "电脑上装的 Node.js 版本要满足这个要求。" + "命令行里输入 node --version 就能看自己装的是几。" + ), + "required": True, + } + ) + + # --- services --- + manifest_pkgs: set[str] = set() + manifest_only_pkgs: set[str] = set() + for path, content in file_contents.items(): + base = _basename(path) + if _MANIFEST_NAMES.search(path): + pkgs = _manifest_packages(content, base) + manifest_pkgs |= pkgs + if "dev" not in base.lower(): + manifest_only_pkgs |= pkgs + imports = _imported_modules(file_contents) + + for service, (pkg_names, mod_names) in _SERVICES.items(): + in_manifest = bool(pkg_names & manifest_pkgs) + # JS imports use the npm package name directly, so check both sets. + in_imports = bool((mod_names | pkg_names) & imports) + if not (in_manifest or in_imports): + continue + reqs.append( + { + "category": "service", + "name": service, + "detail": "代码里直接引入了它的客户端" + if in_imports + else "依赖清单里列了它的客户端", + "note": _SERVICE_NOTES[service], + "required": in_imports, + } + ) + + # --- GPU --- + gpu_pkg = sorted(_GPU_PACKAGES & manifest_pkgs) + has_cu = any(p.lower().endswith((".cu", ".cuh")) for p in file_contents) + has_cuda_device = False + if not gpu_pkg: + for path, content in file_contents.items(): + if path.lower().endswith(_PY_EXTS) and _CUDA_DEVICE_RE.search(content): + has_cuda_device = True + break + if gpu_pkg or has_cu or has_cuda_device: + evidence = ( + f"依赖里有 {', '.join(gpu_pkg[:3])}" + if gpu_pkg + else ("有 .cu CUDA 源文件" if has_cu else "代码里指定了 cuda 设备") + ) + reqs.append( + { + "category": "gpu", + "name": "NVIDIA 显卡(GPU)", + "detail": evidence, + "note": ( + "项目的部分功能需要英伟达显卡才能跑(普通办公电脑的集成显卡不算)。" + "有些项目也提供纯 CPU 的降级用法,但会慢很多。" + ), + "required": True, + } + ) + + # --- OS constraints --- + for _key, (pkgs, mods, note) in _OS_SIGNALS.items(): + if (pkgs & manifest_pkgs) or (mods & imports): + label = { + "windows_only": "仅 Windows", + "mac_only": "仅 macOS", + "posix_only": "仅 Linux / macOS", + }[_key] + reqs.append( + { + "category": "os", + "name": label, + "detail": "代码或依赖里出现了系统专属组件", + "note": note, + "required": True, + } + ) + + # --- container escape hatch --- + container = next( + (p for p in file_contents if _basename(p).lower() in _CONTAINER_FILES), + None, + ) + if container: + reqs.append( + { + "category": "container", + "name": "可以用 Docker", + "detail": f"仓库里有 {container}", + "note": ( + "如果装了 Docker,可以不管上面的版本和服务要求,直接用容器一键起。" + "这通常是最省事的办法。" + ), + "required": False, + } + ) + + order = {"python": 0, "node": 1, "service": 2, "gpu": 3, "os": 4, "container": 5} + reqs.sort(key=lambda r: order[r["category"]]) + return {"requirements": reqs} diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts index 7b5f3d2..062e44e 100644 --- a/frontend/src/lib/api.ts +++ b/frontend/src/lib/api.ts @@ -426,6 +426,14 @@ export interface Dependency { purpose?: string | null; } +export interface RunRequirement { + category: string; // "python" | "node" | "service" | "gpu" | "os" | "container" + name: string; + detail: string; + note: string; + required: boolean; +} + export interface ApiRoute { method: string; path: string; @@ -512,6 +520,7 @@ export interface ProjectMeta { contribution?: ContributionGuide; action_plan?: ActionPlan; dependencies?: Dependency[]; + run_requirements?: RunRequirement[]; api_map?: ApiMap; activity?: ActivitySummary; health_score?: HealthScore; diff --git a/frontend/src/pages/Overview.tsx b/frontend/src/pages/Overview.tsx index c3172b1..bd66077 100644 --- a/frontend/src/pages/Overview.tsx +++ b/frontend/src/pages/Overview.tsx @@ -783,6 +783,54 @@ export default function Overview() { )} + {/* Runtime requirements — what kind of machine and services it needs */} + {project && (project.run_requirements?.length ?? 0) > 0 && ( +
+

+ {t("跑起来需要什么环境", "What it needs to run")} +

+

+ {t( + "在装任何依赖之前先看这个:要多新的 Python/Node、要不要另外开数据库之类的服务、要不要英伟达显卡、挑不挑操作系统。如果有 Docker 那条,通常是最省事的路。", + "Read this before installing anything: how new your Python/Node must be, whether a database or other background service has to be running, whether an NVIDIA GPU is expected, and whether your operating system works. When a Docker entry shows up, it is usually the easiest way.", + )} +

+ +
+ )} + {/* Third-party dependencies — what libraries it installs, each in plain words */} {project && (project.dependencies?.length ?? 0) > 0 && (
diff --git a/tests/test_runreqs.py b/tests/test_runreqs.py new file mode 100644 index 0000000..24e29c3 --- /dev/null +++ b/tests/test_runreqs.py @@ -0,0 +1,150 @@ +from backend.services.runreqs import scan_run_requirements + + +def _cats(data): + return [r["category"] for r in data["requirements"]] + + +def _by_category(data, category): + return [r for r in data["requirements"] if r["category"] == category] + + +def test_empty_project_has_no_requirements(): + assert scan_run_requirements({})["requirements"] == [] + + +def test_pyproject_requires_python_floor(): + files = { + "pyproject.toml": '[project]\nname = "demo"\nrequires-python = ">=3.10"\n', + } + data = scan_run_requirements(files) + reqs = _by_category(data, "python") + assert len(reqs) == 1 + assert reqs[0]["name"] == "Python >=3.10" + assert reqs[0]["required"] is True + assert "pyproject.toml" in reqs[0]["detail"] + + +def test_pyproject_without_project_table_ignored(): + # a pyproject that is only tool config carries no floor + files = {"pyproject.toml": '[tool.ruff]\nline-length = 88\nrequires-python = ">=3.8"\n'} + assert _by_category(scan_run_requirements(files), "python") == [] + + +def test_setup_cfg_python_requires(): + files = {"setup.cfg": "[options]\npython_requires = >=3.9\n"} + reqs = _by_category(scan_run_requirements(files), "python") + assert reqs and ">=3.9" in reqs[0]["name"] + + +def test_pipfile_and_runtime_txt_and_python_version(): + assert ( + _by_category( + scan_run_requirements({"Pipfile": '[requires]\npython_version = "3.11"\n'}), "python" + )[0]["name"] + == "Python >=3.11" + ) + assert ( + _by_category(scan_run_requirements({"runtime.txt": "python-3.12.1\n"}), "python")[0]["name"] + == "Python ==3.12.1" + ) + assert ( + _by_category(scan_run_requirements({".python-version": "3.13\n"}), "python")[0]["name"] + == "Python ==3.13" + ) + + +def test_python_floor_reported_once(): + files = { + "pyproject.toml": '[project]\nrequires-python = ">=3.10"\n', + "runtime.txt": "python-3.12.1\n", + } + assert len(_by_category(scan_run_requirements(files), "python")) == 1 + + +def test_node_engines_and_nvmrc(): + files = {"package.json": '{"name": "x", "engines": {"node": ">=18"}}'} + reqs = _by_category(scan_run_requirements(files), "node") + assert reqs and reqs[0]["name"] == "Node.js >=18" + nvm = _by_category(scan_run_requirements({".nvmrc": "v20.11.0\n"}), "node") + assert nvm and nvm[0]["name"] == "Node.js ==20.11.0" + + +def test_service_from_manifest_only_is_not_required(): + files = {"requirements.txt": "psycopg2-binary>=2.9\n"} + reqs = _by_category(scan_run_requirements(files), "service") + assert len(reqs) == 1 + assert reqs[0]["name"] == "PostgreSQL" + assert reqs[0]["required"] is False + + +def test_service_imported_in_source_is_required(): + files = { + "requirements.txt": "redis>=5\n", + "app/cache.py": "import redis\n\nclient = redis.Redis()\n", + } + reqs = _by_category(scan_run_requirements(files), "service") + assert reqs[0]["name"] == "Redis" + assert reqs[0]["required"] is True + + +def test_js_service_package_from_require_call(): + files = {"src/db.js": 'const { Client } = require("pg")\n'} + # pg is not in the curated map; ioredis is a manifest name, mongodb a module + files2 = {"src/queue.js": 'import IORedis from "ioredis"\n'} + assert _by_category(scan_run_requirements(files), "service") == [] + reqs = _by_category(scan_run_requirements(files2), "service") + assert reqs and reqs[0]["name"] == "Redis" + + +def test_gpu_from_dependency_manifest(): + files = {"requirements.txt": "torch>=2.0\n"} + reqs = _by_category(scan_run_requirements(files), "gpu") + assert len(reqs) == 1 + assert "torch" in reqs[0]["detail"] + + +def test_gpu_from_cuda_source_file(): + files = {"kernels/add.cu": "__global__ void add() {}\n"} + assert _by_category(scan_run_requirements(files), "gpu") + + +def test_gpu_from_cuda_device_string(): + files = {"infer.py": 'model.to("cuda:0")\n'} + assert _by_category(scan_run_requirements(files), "gpu") + + +def test_no_gpu_signal_means_no_gpu_requirement(): + files = {"main.py": "import os\nprint(os.name)\n"} + assert _by_category(scan_run_requirements(files), "gpu") == [] + + +def test_os_windows_only_signal(): + files = {"winreg_tool.py": "import winreg\n"} + reqs = _by_category(scan_run_requirements(files), "os") + assert reqs and reqs[0]["name"] == "仅 Windows" + + +def test_os_posix_only_signal(): + files = {"lock.py": "import fcntl\n"} + reqs = _by_category(scan_run_requirements(files), "os") + assert reqs and reqs[0]["name"] == "仅 Linux / macOS" + + +def test_container_escape_hatch(): + files = {"Dockerfile": "FROM python:3.12\n"} + reqs = _by_category(scan_run_requirements(files), "container") + assert len(reqs) == 1 + assert reqs[0]["required"] is False + files2 = {"deploy/docker-compose.yml": "services: {}\n"} + assert _by_category(scan_run_requirements(files2), "container") + + +def test_ordering_python_before_service_before_container(): + files = { + "Dockerfile": "FROM python:3.12\n", + "requirements.txt": "redis\n", + "pyproject.toml": '[project]\nrequires-python = ">=3.10"\n', + } + cats = _cats(scan_run_requirements(files)) + assert cats == ["python", "service", "container"]