蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 Maven 多模块父子 POM 继承、Kahn 反应器拓扑排序、-pl/-am 切片与循环依赖检测离线核验

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-multi-module.py
explore-multi-module.py213 行
"""Offline Maven multi-module POM inheritance, reactor topological sort & cycle verifier for Ch10 (multi-module)."""
import json
import tempfile
import xml.etree.ElementTree as ET
from collections import deque
from pathlib import Path

VERSION = "CPython 3.12.14 offline Maven POM/lifecycle/dependency verifier (mvn CLI absent)"


def check(name, summary, expected, actual):
    return {
        "name": name,
        "summary": summary,
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def reactor_sort(modules, deps_map):
    indeg = {m: 0 for m in modules}
    adj = {m: [] for m in modules}
    for mod, reqs in deps_map.items():
        for req in reqs:
            adj[req].append(mod)
            indeg[mod] += 1
    q = deque([m for m in modules if indeg[m] == 0])
    order = []
    while q:
        cur = q.popleft()
        order.append(cur)
        for nxt in adj[cur]:
            indeg[nxt] -= 1
            if indeg[nxt] == 0:
                q.append(nxt)
    return order, len(order) != len(modules)


def main():
    cases = []

    # Case 1: Parent POM (packaging=pom, <modules>) & child POM (<parent>) layout
    parent_pom = """
    <project>
      <modelVersion>4.0.0</modelVersion>
      <groupId>com.example</groupId>
      <artifactId>parent-project</artifactId>
      <version>1.0.0</version>
      <packaging>pom</packaging>
      <modules>
        <module>module1</module>
        <module>module2</module>
      </modules>
      <dependencyManagement>
        <dependencies>
          <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
          </dependency>
        </dependencies>
      </dependencyManagement>
    </project>
    """
    child1_pom = """
    <project>
      <parent>
        <groupId>com.example</groupId>
        <artifactId>parent-project</artifactId>
        <version>1.0.0</version>
      </parent>
      <modelVersion>4.0.0</modelVersion>
      <artifactId>module1</artifactId>
      <dependencies>
        <dependency><groupId>junit</groupId><artifactId>junit</artifactId></dependency>
      </dependencies>
    </project>
    """
    with tempfile.TemporaryDirectory() as tmp:
        root_dir = Path(tmp) / "parent-project"
        (root_dir / "module1" / "src").mkdir(parents=True)
        (root_dir / "module2" / "src").mkdir(parents=True)
        (root_dir / "pom.xml").write_text(parent_pom, encoding="utf-8")
        (root_dir / "module1" / "pom.xml").write_text(child1_pom, encoding="utf-8")
        p_root = ET.parse(root_dir / "pom.xml").getroot()
        c_root = ET.parse(root_dir / "module1" / "pom.xml").getroot()
    effective_child_gid = c_root.findtext("groupId") or c_root.findtext("parent/groupId")
    effective_child_ver = c_root.findtext("version") or c_root.findtext("parent/version")
    cases.append(
        check(
            "parent_and_child_pom_structure",
            "Parse parent packaging=pom + <modules> and child <parent> inheritance of groupId and version",
            {
                "parent_packaging": "pom",
                "modules": ["module1", "module2"],
                "child_effective_gav": "com.example:module1:1.0.0",
            },
            {
                "parent_packaging": p_root.findtext("packaging"),
                "modules": [m.text.strip() for m in p_root.findall("modules/module")],
                "child_effective_gav": f"{effective_child_gid}:{c_root.findtext('artifactId')}:{effective_child_ver}",
            },
        )
    )

    # Case 2: Inter-module dependency (${project.version}) & inherited dependencyManagement version
    child2_pom = """
    <project>
      <parent>
        <groupId>com.example</groupId>
        <artifactId>parent-project</artifactId>
        <version>1.0.0</version>
      </parent>
      <modelVersion>4.0.0</modelVersion>
      <artifactId>module2</artifactId>
      <dependencies>
        <dependency>
          <groupId>com.example</groupId>
          <artifactId>module1</artifactId>
          <version>${project.version}</version>
        </dependency>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
        </dependency>
      </dependencies>
    </project>
    """
    c2 = ET.fromstring(child2_pom)
    managed = {
        f"{d.findtext('groupId')}:{d.findtext('artifactId')}": (d.findtext("version"), d.findtext("scope") or "compile")
        for d in p_root.findall("dependencyManagement/dependencies/dependency")
    }
    resolved_c2 = []
    for d in c2.findall("dependencies/dependency"):
        ga = f"{d.findtext('groupId')}:{d.findtext('artifactId')}"
        raw_v = d.findtext("version")
        if raw_v == "${project.version}":
            ver = effective_child_ver
            scope = "compile"
        elif raw_v is None:
            ver, scope = managed[ga]
        else:
            ver, scope = raw_v, d.findtext("scope") or "compile"
        resolved_c2.append(f"{ga}:{ver}:{scope}")
    cases.append(
        check(
            "inter_module_dependency_and_inheritance",
            "Resolve module2 -> module1 (${project.version}) and junit version/scope inherited from parent dependencyManagement",
            ["com.example:module1:1.0.0:compile", "junit:junit:4.12:test"],
            resolved_c2,
        )
    )

    # Case 3: Reactor topological build order & -pl / -am CLI selection
    mods = ["module-web", "module-service", "module-dao", "module-common"]
    dep_graph = {
        "module-common": [],
        "module-dao": ["module-common"],
        "module-service": ["module-dao", "module-common"],
        "module-web": ["module-service"],
    }
    topo, has_cycle = reactor_sort(mods, dep_graph)
    # -pl module-service -am
    needed = {"module-service"}
    q = deque(["module-service"])
    while q:
        cur = q.popleft()
        for req in dep_graph[cur]:
            if req not in needed:
                needed.add(req)
                q.append(req)
    am_order = [m for m in topo if m in needed]
    cases.append(
        check(
            "reactor_topological_sort_and_cli_selection",
            "Compute Maven reactor topological build order and -pl module-service -am build slice",
            {
                "has_cycle": False,
                "full_reactor_order": ["module-common", "module-dao", "module-service", "module-web"],
                "pl_service_am_order": ["module-common", "module-dao", "module-service"],
            },
            {
                "has_cycle": has_cycle,
                "full_reactor_order": topo,
                "pl_service_am_order": am_order,
            },
        )
    )

    # Case 4: Circular dependency detection & extraction of common module fix
    cyclic_order, cyclic_flag = reactor_sort(["moduleA", "moduleB"], {"moduleA": ["moduleB"], "moduleB": ["moduleA"]})
    fixed_order, fixed_flag = reactor_sort(
        ["moduleA", "moduleB", "moduleCommon"],
        {"moduleCommon": [], "moduleA": ["moduleCommon"], "moduleB": ["moduleCommon"]},
    )
    cases.append(
        check(
            "cycle_detection_and_version_alignment",
            "Detect circular dependency (A <-> B) and verify cycle-free graph after extracting moduleCommon",
            {"cyclic_detected": True, "fixed_has_cycle": False, "first_built_after_fix": "moduleCommon"},
            {"cyclic_detected": cyclic_flag, "fixed_has_cycle": fixed_flag, "first_built_after_fix": fixed_order[0]},
        )
    )

    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/maven-multi-module-lab/explore-multi-module.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-multi-module.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Maven

课程关联工程包(登记关联25章) · 含当前章节或实例 · mbskycom202612a2175.zip

下载课程关联工程包:Maven

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2189.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习