Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
add dependency for maven project
#!/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
You can’t perform that action at this time.