Created
March 28, 2019 08:09
-
-
Save khsing/ab42b9116741ffab09573138517a6fc5 to your computer and use it in GitHub Desktop.
add dependency for maven project
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from xml.etree import ElementTree as ET | |
from argparse import ArgumentParser | |
import os | |
import sys | |
ns = "http://maven.apache.org/POM/4.0.0" | |
ET.register_namespace("", ns) | |
namespaces = {'pom' : ns} | |
def makeProperty(node, value): | |
builder = ET.TreeBuilder() | |
builder.start(node, {}) | |
builder.data(value) | |
return builder.end(node) | |
def makeDepsElement(groupId, artifactId, version): | |
dept = ET.Element("dependency") | |
dept.append(makeProperty("groupId", groupId)) | |
dept.append(makeProperty("artifactId", artifactId)) | |
dept.append(makeProperty("version", version)) | |
return dept | |
def check_deps(root, groupId, artifactId, version): | |
deps = root.find('pom:dependencies', namespaces=namespaces) | |
if deps is not None: | |
has_dep = False | |
for d in deps: | |
artifact_id = d.find("pom:artifactId", namespaces=namespaces) | |
if artifact_id.text.startswith(artifactId): | |
has_dep = True | |
if not has_dep: | |
deps.append(makeDepsElement(groupId, artifactId, version)) | |
else: | |
deps = ET.Element("dependencies") | |
deps.append(makeDepsElement(groupId, artifactId, version)) | |
root.append(deps) | |
def set_args(): | |
parser = ArgumentParser() | |
parser.add_argument("pomfile", help="pom.xml file") | |
parser.add_argument("-g","--group-id", help="groupId", required=True, dest="groupId") | |
parser.add_argument("-a","--artifact-id", help="artifactId", required=True, dest="artifactId") | |
parser.add_argument("-v","--verion", help="version", required=True, dest="version") | |
args = parser.parse_args() | |
return args | |
if __name__ == "__main__": | |
opt = set_args() | |
if os.path.exists(opt.pomfile): | |
tree = ET.parse(opt.pomfile) | |
root = tree.getroot() | |
check_deps(root, opt.groupId, opt.artifactId, opt.version) | |
tree.write(opt.pomfile, encoding="utf-8", xml_declaration=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment