最近做项目遇到一个问题,从别的地方拿过来的工程是用maven构建的,而且用了许多自有的依赖包,如果一个个的上传到私服简直是浪费时间,于是用Python 写了一个批量上传的工具,简化自己的工作量。
使用的是Python3,分别依赖了os、subprocess、re包:
- os:读取本地仓库下的jar和pom;
- subprocess:执行mvn deploy命令;
- re:正则识别文件名中的groupId、artifactId、version等信息。
以下为完整代码
import os
import subprocess
import re
REPO_URL = "仓库url"
REPO_ID = "仓库id"
REPO_USERNAME = "用户名"
REPO_PASSWORD = "密码"
FILES_DIR = "本地仓库地址"
def upload_file(file_path):
filename = os.path.basename(file_path)
match = re.match(r'^(.+?)-(?:(\d+\.\d+(?:\.\d+)?(?:-[\w\.]+)?)?(?:-(.*?))?)((?:-SNAPSHOT)?\..+)$', filename)
if match:
artifact_id, version, classifier, packaging = match.groups()
if classifier is None:
classifier = ''
packaging = packaging.replace(".","")
group_id = os.path.relpath(os.path.dirname(os.path.dirname(os.path.dirname(file_path))), FILES_DIR).replace(os.path.sep, ".")
print(f"Uploading {filename} (groupId={group_id}) (artifact_id={artifact_id}) (version={version}) (packaging={packaging})")
if (filename.find("通过文件名过滤") != -1):
subprocess.run([
"mvn", "deploy:deploy-file",
"-DgroupId=" + group_id,
"-DartifactId=" + artifact_id,
"-Dversion=" + version,
"-Dpackaging=" + packaging,
"-Dfile=" + file_path,
"-DrepositoryId=" + REPO_ID,
"-Durl=" + REPO_URL,
"-Drepository.username=" + REPO_USERNAME,
"-Drepository.password=" + REPO_PASSWORD,
# "-DpomFile=" + file_path.replace("jar", "pom")
], check=True)
for root, dirs, files in os.walk(FILES_DIR):
for name in files:
file_path = os.path.join(root, name)
if name.endswith(".jar") or name.endswith(".pom"):
try:
upload_file(file_path)
except Exception as e :
print(e)