最近因为三方代码管理问题,需要手工上传三方的包到maven仓库。但snapshot包是不能通过界面上传的,只能编写脚本。可以那么多jar,一个个写脚本,脚本就得写很多年了。代码整起。
public class UploadPomJar {
// maven用户密码配置
private static final String settingPath = "D:\\maven-setting.xml";
public static void main(String[] args) throws Exception {
String rootPath = "C:\\Users\\34657\\Desktop\\mavenjarrootpath";
// 把上传命令生成到文本内,执行粘贴就行
Path path = Paths.get("C:\\Users\\34657\\Desktop\\pushJar.txt");
File file = new File(rootPath);
List<File> leafFiles = new ArrayList<>();
getLeafFiles(file, leafFiles);
for (File leaf : leafFiles) {
uploadFileJar(path, leaf);
}
}
//将单个jar写入文本一行
private static void uploadFileJar(Path path, File leaf) throws Exception {
String fileName = leaf.getName();
String repository = "public";
if (fileName.endsWith("SNAPSHOT")) {
repository = "snapshots";
}
File jarFile = getJarFile(leaf);
if (null == jarFile) {
return;
}
String fileFullPath = jarFile.getAbsolutePath();
File pomFile = new File(fileFullPath.replace("jar", "pom"));
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(pomFile);
Element rootElement = document.getRootElement();
String groupId = rootElement.elementText("groupId");
String artifactId = rootElement.elementText("artifactId");
String version = rootElement.elementText("version");
String pushCmd = getPushCmd(repository, fileFullPath, groupId, artifactId, version);
Files.write(path, pushCmd.concat("\n").getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
}
//获取jar文件,jar文件需要排除snapshot临时版本文件
private static File getJarFile(File leaf) {
for (File f : leaf.listFiles()) {
if (!f.getName().endsWith(".jar")) {
continue;
}
//jar文件需要排除snapshot临时版本文件
if (f.getName().endsWith(leaf.getName() + ".jar")) {
return f;
}
}
return null;
}
//递归获取叶子节点
private static void getLeafFiles(File file, List<File> leafFiles) {
if (isLeafDir(file)) {
leafFiles.add(file);
return;
}
for (File f : file.listFiles()) {
getLeafFiles(f, leafFiles);
}
}
//判断jar所在文件夹
private static boolean isLeafDir(File file) {
return file.listFiles(File::isDirectory).length == 0;
}
private static String getPushCmd(String repository, String fileFullPath, String groupId, String artifactId, String version) {
return "mvn deploy:deploy-file"
+ " -DgroupId=" + groupId
+ " -DartifactId=" + artifactId
+ " -Dversion=" + version
+ " -Dpackaging=jar "
+ " -Dfile=" + fileFullPath
+ " -DpomFile=" + fileFullPath.replace(".jar",".pom")
// + " -DgeneratePom=true"
+ " -DrepositoryId=maven-" + repository
+ " -Durl=https://maven.com/repository/pubrepo/maven-" + repository + "/"
+ " --settings " + settingPath;
}
}