Maven插件:exec-maven-plugin-代码执行或者直接输出内置变量信息

概述

官网: https://www.mojohaus.org/exec-maven-plugin/usage.html

依赖: https://mvnrepository.com/artifact/org.codehaus.mojo/exec-maven-plugin

使用

           <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>3.3.0</version> <!-- 请使用最新版本 -->
                <executions>
                    <execution>
                        <id>unique-id-1</id>
                        <phase>validate</phase> <!-- 指定在哪个阶段执行 -->
                        <goals>
                            <goal>exec</goal>
                        </goals>
                        <configuration>
                            <executable>echo</executable>
                            <arguments>
                                <argument>${project.build.outputDirectory}</argument>
                                <argument>${project.basedir}</argument>
                            </arguments>
                        </configuration>
                    </execution>
                    <execution>
                        <id>unique-id-2</id>
                        <phase>validate</phase> <!-- 指定在哪个阶段执行 -->
                        <goals>
                            <goal>java</goal>
                        </goals>
                        <configuration>
                            <mainClass>work.linruchang.chatgptweb.maven.MavenRecordGitInfo</mainClass>
                            <arguments>
                                <argument>lrc</argument>
                                <argument>20240707</argument>
                            </arguments>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

在这里插入图片描述

在这里插入图片描述

应用

自行实现记录项目打包插件

类似同样的功能,可以直接使用Maven的另一款插件:git-commit-id-maven-plugin

MavenRecordGitInfoPlugin.java

@Slf4j
public class MavenRecordGitInfoPlugin {

    private static String pluginName = "打包信息插件";

    /**
     * 获取当前的项目目录
     *
     * @return
     */
    public static File getCurrentProjectDir(MavenRecordGitInfoConfig mavenRecordGitInfoConfig) {

        File targetClassDir = FileUtil.file("").getAbsoluteFile();

        String gitCmd = "{execGitPath} rev-parse --show-toplevel";
        gitCmd = StrUtil.format(gitCmd, Dict.parse(mavenRecordGitInfoConfig));
        Process process = RuntimeUtil.exec(new String[0], targetClassDir, gitCmd);

        String currentProjectDir = StrUtil.trim(IoUtil.readUtf8(process.getInputStream()));

        return FileUtil.file(currentProjectDir);
    }

    /**
     * 项目打包时的信息
     *
     * @return
     */
    public static ProjectPackageInfo getProjectPackageInfo(MavenRecordGitInfoConfig mavenRecordGitInfoConfig) {
        ProjectPackageInfo projectPackageInfo = ProjectPackageInfo.builder()
                .projectPackageTime(DateUtil.now())
                .projectPackageIp(SystemUtil.getHostInfo().getAddress())
                .build();

        String execGitPath = mavenRecordGitInfoConfig.getExecGitPath();
        if (!EnhanceRuntimeUtil.hasCommand(execGitPath)) {
            log.warn("【{}】警告:记录打包信息失败,可执行Git指令({})不生效", pluginName, execGitPath);
            return projectPackageInfo;
        }

        File currentProjectDir = getCurrentProjectDir(mavenRecordGitInfoConfig);
        projectPackageInfo.setProjectPackageDir(FileUtil.getAbsolutePath(currentProjectDir));

        // 输出格式
        // commitId: 4216872
        // commitAuthor: LinRuChang
        // commitTime: 2024-07-06 14:38:57
        // commitBranch:  (HEAD -> master, origin/master, origin/HEAD)
        // commitMessage:  修复:【切换】展示用户默认AI模型问题
        String gitCmd = "{execGitPath} log --format='commitId: %h %ncommitAuthor: %an %ncommitTime: %ad %ncommitBranch: %d %ncommitMessage:  %s' --date=format:'%Y-%m-%d %H:%M:%S' -1";
        gitCmd = StrUtil.format(gitCmd, Dict.parse(mavenRecordGitInfoConfig));

        String gitInfoRawContent = EnhanceRuntimeUtil.execResult(new String[0], currentProjectDir, gitCmd);
        if (StrUtil.isBlank(gitInfoRawContent)) {
            log.warn("【{}】警告:记录打包信息失败,获取不到Git提交信息,请检查", pluginName);
            return projectPackageInfo;
        }
        log.info("【{}】当前Git最新提交信息如下:\n{}", pluginName, gitInfoRawContent);

        // 去除前后缀的单引号
        gitInfoRawContent = StrUtil.strip(gitInfoRawContent, EnhanceStrUtil.singleQuotationMark);

        List<String> gitInfoRawContentS = StrUtil.splitTrim(gitInfoRawContent, StrUtil.LF);
        Map<String, String> gitParseInfoMap = gitInfoRawContentS.stream()
                .filter(StrUtil::isNotBlank)
                .filter(rowContent -> StrUtil.splitTrim(rowContent, EnhanceStrUtil.COLON).size() > 1)
                .collect(CollectorUtil.toMap(
                        rowContent -> StrUtil.trim(StrUtil.subBefore(rowContent, StrUtil.COLON, false)),
                        rowContent -> StrUtil.strip(StrUtil.trim(StrUtil.subAfter(rowContent, StrUtil.COLON, false)), EnhanceStrUtil.singleQuotationMark),
                        (v1, v2) -> v1));
        BeanUtil.copyProperties(gitParseInfoMap, projectPackageInfo, true);
        // 获取具体的分支(HEAD -> master, origin/master, origin/HEAD)
        String commitBranch = projectPackageInfo.getCommitBranch();
        if (StrUtil.isNotBlank(commitBranch)) {
            String branchInfoRawContent = CollUtil.findOne(StrUtil.splitTrim(commitBranch, StrUtil.COMMA), content -> {
                return StrUtil.containsAnyIgnoreCase(content, "->") && StrUtil.containsAnyIgnoreCase(content, "HEAD");
            });

            String simpleCommitBranch = StrUtil.trim(StrUtil.subAfter(branchInfoRawContent, "->", false));
            projectPackageInfo.setCommitBranch(StrUtil.blankToDefault(simpleCommitBranch, commitBranch));
        }


        return projectPackageInfo;
    }


    public static void main(String[] args) {
        try {
            Console.log("\n===============【{}】开始=======================\n", pluginName);
            MavenRecordGitInfoConfig mavenRecordGitInfoConfig = MavenRecordGitInfoConfig.parse(ArrayUtil.get(args, 0));
            log.info("【{}】原始配置参数:{},最终生效的配置参数:{}", pluginName, args, JSONUtil.toJsonStr(mavenRecordGitInfoConfig));

            ProjectPackageInfo projectPackageInfo = getProjectPackageInfo(mavenRecordGitInfoConfig);
            String projectPackageInfoJson = StrUtil.nullToEmpty(JSONUtil.toJsonPrettyStr(projectPackageInfo));

            File packageInfoFile = FileUtil.file(mavenRecordGitInfoConfig.getPackageInfoFileName());
            FileUtil.writeString(projectPackageInfoJson, packageInfoFile, CharsetUtil.UTF_8);
            log.info("【{}】当前项目的打包信息【{}】:{}", pluginName, FileUtil.getAbsolutePath(packageInfoFile), projectPackageInfo);
        } catch (Exception e) {
            // 必须捕获异常,否则这里面有任何的报错都会阻止项目的打包
            log.error("【{}】发生未知错误,导致插件崩溃", pluginName, e);
        } finally {
            Console.log("\n===============【{}】结束=======================\n", pluginName);
        }
    }

}

MavenRecordGitInfoConfig.java

/**
 * @author LinRuChang
 * @version 1.0
 * @date 2024/07/08
 * @since 1.8
 **/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@ApiModel(description = "Git记录插件配置信息")
public class MavenRecordGitInfoConfig {

    private final static String defaultPackageInfoFileName = "package.info";
    private final static String defaultExecGitPath = "git";

    /**
     * 生成的打包信息文件的文件名
     */
    private String packageInfoFileName = defaultPackageInfoFileName;

    /**
     * 生成打包信息时,需使用到Git执行程序,如果未设置成全局可执行命令,必须设置Git绝对路径地址
     */
    private String execGitPath = defaultExecGitPath;

    public static MavenRecordGitInfoConfig parse(String rawContent)  {
        MavenRecordGitInfoConfig mavenRecordGitInfoConfig = new MavenRecordGitInfoConfig();

        if(StrUtil.isBlank(rawContent)) {
            return mavenRecordGitInfoConfig;
        }


        Map<String, String> parseConfigInfo = StrUtil.splitTrim(rawContent, StrUtil.COMMA).stream()
                .filter(StrUtil::isNotBlank)
                .map(StrUtil::trim)
                .filter(rowContent -> StrUtil.isNotBlank(StrUtil.subAfter(rowContent, EnhanceStrUtil.equalMark, false)))
                .collect(CollectorUtil.toMap(
                        rowContent -> StrUtil.subBefore(rowContent, EnhanceStrUtil.equalMark, false),
                        rowContent -> StrUtil.subAfter(rowContent, EnhanceStrUtil.equalMark, false),
                        (v1, v2) -> v1
                ));

        BeanUtil.copyProperties(parseConfigInfo,mavenRecordGitInfoConfig, true);

        return mavenRecordGitInfoConfig;
    }


    public static void main(String[] args) {


        MavenRecordGitInfoConfig parse = MavenRecordGitInfoConfig.parse("packageInfoFileName=package.info2,git=");
        Console.log(parse);
    }

}


ProjectPackageInfo.java

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@ApiModel(description = "项目打包信息")
public class ProjectPackageInfo implements Serializable {
    private static final long serialVersionUID = -7381111550970133734L;

    @ApiModelProperty("提交记录ID")
    String commitId;

    @ApiModelProperty("提交作者")
    String commitAuthor;

    @ApiModelProperty("提交的时间")
    String commitTime;

    @ApiModelProperty("提交记录所处的分支")
    String commitBranch;



    @ApiModelProperty("提交的描述信息")
    String commitMessage;

    @ApiModelProperty("项目打包的时间")
    String projectPackageTime;

    @ApiModelProperty("项目打包时的IP地址")
    String projectPackageIp;

    @ApiModelProperty("项目打包时的项目目录")
    String projectPackageDir;



}

pom.xml


            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>3.3.0</version> <!-- 请使用最新版本 -->
                <executions>
                    <!--<execution>-->
                    <!--    <id>unique-id-1</id>-->
                    <!--    <phase>validate</phase> &lt;!&ndash; 指定在哪个阶段执行 &ndash;&gt;-->
                    <!--    <goals>-->
                    <!--        <goal>exec</goal>-->
                    <!--    </goals>-->
                    <!--    <configuration>-->
                    <!--        <executable>echo</executable>-->
                    <!--        <arguments>-->
                    <!--            <argument>${project.build.outputDirectory}</argument>-->
                    <!--            <argument>${project.basedir}</argument>-->
                    <!--        </arguments>-->
                    <!--    </configuration>-->
                    <!--</execution>-->
                    <execution>
                        <id>unique-id-2</id>
                        <!--<phase>validate</phase> &lt;!&ndash; 指定在哪个阶段执行 &ndash;&gt;-->
                        <!--必须这个阶段,validate代码还未编译完成,第一次运行会报类不存在的现象,故需使用compile这个阶段-->
                        <phase>compile</phase> <!-- 指定在哪个阶段执行 -->
                        <goals>
                            <goal>java</goal>
                        </goals>
                        <configuration>
                            <mainClass>work.linruchang.chatgptweb.maven.MavenRecordGitInfoPlugin</mainClass>
                            <arguments>
                                <argument>packageInfoFileName=package.info,execGitPath=git</argument>
                            </arguments>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

        </plugins>

在这里插入图片描述


@Api(tags = "管理员模块(不对外开放)")
@RestController
@RequestMapping("admin")
@Slf4j
public class AdminController {

    @ApiOperation(value = "查看系统打包版本信息")
    @GetMapping("/systemPackageInfo")
    public ResponseResult<ProjectPackageInfo> systemPackageInfo() {
        String s = ResourceUtil.readUtf8Str(MavenRecordGitInfoPlugin.mavenRecordGitInfoConfigFileName);
        MavenRecordGitInfoConfig mavenRecordGitInfoConfig = JSONUtil.toBean(s, MavenRecordGitInfoConfig.class);

        String packInfoContent = ResourceUtil.readUtf8Str(mavenRecordGitInfoConfig.getPackageInfoFileName());
        ProjectPackageInfo projectPackageInfo = JSONUtil.toBean(packInfoContent,ProjectPackageInfo.class);
        return ResponseResult.success(projectPackageInfo);
    }
}

在这里插入图片描述

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值