Skip to content

Instantly share code, notes, and snippets.

@HSGamer
Created June 16, 2025 02:14
Show Gist options
  • Select an option

  • Save HSGamer/662e7b058268c4c83a3b9bb9bae61cbf to your computer and use it in GitHub Desktop.

Select an option

Save HSGamer/662e7b058268c4c83a3b9bb9bae61cbf to your computer and use it in GitHub Desktop.
Python script to automatically set project name based on artifact id
import os
import xml.etree.ElementTree as ET
# Define the root directory to search for pom.xml files
root_dir = "/home/hsgamer/IdeaProjects/Topper"
# Function to convert kebab-case to Pascal Case with spaces
def kebab_to_pascal_with_spaces(s):
return ' '.join(word.capitalize() for word in s.split('-'))
# Function to update the <name> tag based on <artifactId>
def update_pom_name(file_path):
tree = ET.parse(file_path)
root = tree.getroot()
# Define the namespaces used in the pom.xml
namespaces = {'m': 'http://maven.apache.org/POM/4.0.0'}
# Find the <artifactId> tag
artifact_id = root.find('m:artifactId', namespaces)
if artifact_id is not None:
artifact_id_text = artifact_id.text
# Find the <name> tag
name_tag = root.find('m:name', namespaces)
if name_tag is not None:
# If <name> exists, skip
print(f"<name> already exists in {file_path}, skipping.")
return
# Convert artifactId to Pascal Case with spaces
pascal_name = kebab_to_pascal_with_spaces(artifact_id_text)
# Find the index of <artifactId> among root's children
children = list(root)
artifact_id_index = None
for idx, child in enumerate(children):
if child.tag == '{http://maven.apache.org/POM/4.0.0}artifactId':
artifact_id_index = idx
break
# Create the <name> tag with the correct namespace
name_tag = ET.Element('{http://maven.apache.org/POM/4.0.0}name')
name_tag.text = pascal_name
# Insert <name> tag immediately after <artifactId>
if artifact_id_index is not None:
root.insert(artifact_id_index + 1, name_tag)
else:
# Fallback: append at the end if <artifactId> not found (shouldn't happen)
root.append(name_tag)
# Write the changes back to the file, registering the namespace to avoid ns0 prefix
ET.register_namespace('', 'http://maven.apache.org/POM/4.0.0')
tree.write(file_path, encoding="UTF-8", xml_declaration=False)
print(f"Inserted <name> in {file_path}")
else:
print(f"<artifactId> not found in {file_path}")
# Walk through the directory and find all pom.xml files
for subdir, _, files in os.walk(root_dir):
for file in files:
if file == "pom.xml":
file_path = os.path.join(subdir, file)
update_pom_name(file_path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment