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

运行 Maven 插件前缀解析、内置与 AntRun 自定义绑定、官方插件 XML 配置及 Mojo 注解离线核验

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-plugins.py
explore-plugins.py192 行
"""Offline Maven plugin coordinates, lifecycle bindings, configurations & Mojo verifier for Ch12 (plugins)."""
import json
import re
import xml.etree.ElementTree as ET

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 main():
    cases = []

    # Case 1: Plugin GAV coordinates, prefix resolution & goals
    prefix_map = {
        "compiler": ("org.apache.maven.plugins", "maven-compiler-plugin", ["compile", "testCompile"]),
        "surefire": ("org.apache.maven.plugins", "maven-surefire-plugin", ["test"]),
        "clean": ("org.apache.maven.plugins", "maven-clean-plugin", ["clean"]),
    }
    cli_goal = "compiler:compile"
    pfx, goal = cli_goal.split(":")
    gid, aid, valid_goals = prefix_map[pfx]
    cases.append(
        check(
            "plugin_coordinates_and_goal_syntax",
            "Verify official plugin GAV, prefix-to-artifact resolution (compiler:compile), and multi-goal plugins",
            {
                "resolved_artifact": "org.apache.maven.plugins:maven-compiler-plugin",
                "goal_valid": True,
                "compiler_goals": ["compile", "testCompile"],
            },
            {
                "resolved_artifact": f"{gid}:{aid}",
                "goal_valid": goal in valid_goals,
                "compiler_goals": valid_goals,
            },
        )
    )

    # Case 2: Built-in packaging bindings & custom <executions> binding (including antrun on clean)
    builtin_jar = {
        "compile": "maven-compiler-plugin:compile",
        "test": "maven-surefire-plugin:test",
        "package": "maven-jar-plugin:jar",
    }
    builtin_war = {**builtin_jar, "package": "maven-war-plugin:war"}
    antrun_pom = """
    <project>
      <build><plugins><plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-antrun-plugin</artifactId>
        <version>1.1</version>
        <executions>
          <execution>
            <id>id.clean</id>
            <phase>clean</phase>
            <goals><goal>run</goal></goals>
            <configuration><tasks><echo>clean phase</echo></tasks></configuration>
          </execution>
        </executions>
      </plugin></plugins></build>
    </project>
    """
    ex = ET.fromstring(antrun_pom).find("build/plugins/plugin/executions/execution")
    cases.append(
        check(
            "builtin_and_custom_phase_bindings",
            "Verify built-in JAR/WAR phase bindings and custom maven-antrun-plugin execution bound to clean phase",
            {
                "jar_package": "maven-jar-plugin:jar",
                "war_package": "maven-war-plugin:war",
                "custom_execution": {"id": "id.clean", "phase": "clean", "goal": "run", "echo": "clean phase"},
            },
            {
                "jar_package": builtin_jar["package"],
                "war_package": builtin_war["package"],
                "custom_execution": {
                    "id": ex.findtext("id"),
                    "phase": ex.findtext("phase"),
                    "goal": ex.findtext("goals/goal"),
                    "echo": ex.findtext("configuration/tasks/echo"),
                },
            },
        )
    )

    # Case 3: Official plugin configurations (compiler, surefire, jar manifest) & Build vs Reporting types
    plugins_xml = """
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId><version>3.8.1</version>
        <configuration><source>11</source><target>11</target></configuration>
      </plugin>
      <plugin>
        <artifactId>maven-surefire-plugin</artifactId><version>2.22.2</version>
        <configuration><skipTests>true</skipTests><includes><include>**/*Test.java</include></includes></configuration>
      </plugin>
      <plugin>
        <artifactId>maven-jar-plugin</artifactId><version>3.2.0</version>
        <configuration><archive><manifest><mainClass>com.example.Main</mainClass></manifest></archive></configuration>
      </plugin>
    </plugins>
    """
    proot = ET.fromstring(plugins_xml)
    by_aid = {p.findtext("artifactId"): p for p in proot.findall("plugin")}
    core_seven = ["clean", "compiler", "surefire", "jar", "war", "javadoc", "antrun"]
    cases.append(
        check(
            "official_plugins_catalog_and_configs",
            "Parse compiler/surefire/jar plugin XML configs and verify Build (<build>) vs Reporting (<reporting>) plugin types",
            {
                "compiler_source": "11",
                "surefire_skip": True,
                "surefire_include": "**/*Test.java",
                "jar_main_class": "com.example.Main",
                "plugin_sections": {"Build plugins": "<build>", "Reporting plugins": "<reporting>"},
                "core_plugin_count": 7,
            },
            {
                "compiler_source": by_aid["maven-compiler-plugin"].findtext("configuration/source"),
                "surefire_skip": by_aid["maven-surefire-plugin"].findtext("configuration/skipTests") == "true",
                "surefire_include": by_aid["maven-surefire-plugin"].findtext("configuration/includes/include"),
                "jar_main_class": by_aid["maven-jar-plugin"].findtext("configuration/archive/manifest/mainClass"),
                "plugin_sections": {"Build plugins": "<build>", "Reporting plugins": "<reporting>"},
                "core_plugin_count": len(core_seven),
            },
        )
    )

    # Case 4: CLI invocation & -D property override precedence
    pom_compiler_source = "8"
    cli_override = {"maven.compiler.source": "11"}
    effective_source = cli_override.get("maven.compiler.source", pom_compiler_source)
    cases.append(
        check(
            "cli_invocation_and_parameter_override",
            "Verify CLI -Dmaven.compiler.source=11 overrides POM default during direct goal invocation",
            {"effective_source": "11", "modes": ["lifecycle", "direct_goal", "cli_property"]},
            {"effective_source": effective_source, "modes": ["lifecycle", "direct_goal", "cli_property"]},
        )
    )

    # Case 5: Mojo descriptor annotation parsing (@Mojo + @Parameter + AbstractMojo)
    mojo_src = '''
    @Mojo(name = "greet", defaultPhase = LifecyclePhase.COMPILE)
    public class GreetingMojo extends AbstractMojo {
        @Parameter(property = "name", defaultValue = "World")
        private String name;
        public void execute() throws MojoExecutionException {
            getLog().info("Hello, " + name + "!");
        }
    }
    '''
    mojo_name = re.search(r'@Mojo\(name\s*=\s*"([^"]+)",\s*defaultPhase\s*=\s*LifecyclePhase\.(\w+)\)', mojo_src)
    param_m = re.search(r'@Parameter\(property\s*=\s*"([^"]+)",\s*defaultValue\s*=\s*"([^"]+)"\)', mojo_src)
    extends_abstract = "extends AbstractMojo" in mojo_src and "public void execute()" in mojo_src
    greeting_out = f"Hello, {param_m.group(2)}!"
    cases.append(
        check(
            "mojo_plugin_descriptor_validation",
            "Parse @Mojo/@Parameter annotations on GreetingMojo extending AbstractMojo and verify execute() log",
            {
                "goal_name": "greet",
                "default_phase": "COMPILE",
                "param_property": "name",
                "extends_abstract_mojo": True,
                "default_log": "Hello, World!",
            },
            {
                "goal_name": mojo_name.group(1),
                "default_phase": mojo_name.group(2),
                "param_property": param_m.group(1),
                "extends_abstract_mojo": extends_abstract,
                "default_log": greeting_out,
            },
        )
    )

    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-plugins-lab/explore-plugins.py

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

下载课程关联工程包:Maven

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

下载课程关联工程包:Maven

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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