当前位置: 首页 > news >正文

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);}
}

在这里插入图片描述

http://www.lryc.cn/news/419376.html

相关文章:

  • https://ffmpeg.org/
  • linux 源码部署polardb-x 错误汇总
  • vscode用快捷键一键生成vue模板
  • ARM 架构硬件新趋势:嵌入式领域的未来
  • 星戈瑞-二油酰磷脂酰乙醇胺标记荧光素 DOPE-FITC
  • 堆的实现(偷懒版)
  • 一键启动,智能分拣:3D视觉系统赋能多SKU纸箱高效混拆作业
  • unity草体渲染方案 GPU Instaning
  • 最近在西安召开的学术会议:EI检索超快,信息系统与计算技术领域!
  • sRGB和伽马矫正
  • Summer School science communication project--Laptop Selection Suggestion
  • 网络编程概念详解模拟回显客户端服务器
  • 代码随想录第二十四天|动态规划(8)
  • 编程-设计模式 3:单例模式
  • Kaniko 构建 Docker 镜像
  • Javascript常见算法(每日两个)
  • Spring -- 事务
  • 生命密码的破译者:AI如何学会读懂DNA语言?
  • 大数据信用报告查询哪家平台的比较好?
  • Java高级Day24-集合最后补充
  • C++入门:C语言到C++的过渡
  • 了解MVCC
  • WPF自定义控件的应用(DynamicResource的使用方法)
  • Postgresql数据库密码忘记的解决
  • Flink SQL 基础操作
  • 海思AE模块Lines_per_500ms参数的意义
  • 【代码随想录】区间和——前缀和方法
  • Bug 解决 | 前端项目无法正确安装依赖?
  • 【mysql 第四篇章】bin log 的作用是啥呢?
  • Linux 操作系统:基于环形队列的生产者消费者模型