Site icon PlusMagi's Blog By Pitt Phunsanit

Java: list package, dependency, version

วิธีที่ง่ายและรวดเร็วที่สุด ในการสรุป pom.xaml ใน microservice คือใช้ Python script เพื่อดึง groupId, artifactId, version จากทุก pom.xml ในโปรเจกต์ แล้วรวมเป็นไฟล์เดียว เช่น pom-list-all.txt
pom-list-all.py

import os
import xml.etree.ElementTree as ET

root_dir = os.path.dirname(os.path.abspath(__file__))
output_file = os.path.join(root_dir, "pom-list-all.txt")
result = set()

for dirpath, _, filenames in os.walk(root_dir):
	for filename in filenames:
		if filename == "pom.xml":
			pom_path = os.path.join(dirpath, filename)
			try:
				tree = ET.parse(pom_path)
				root = tree.getroot()
				ns = {'m': 'http://maven.apache.org/POM/4.0.0'}
				for dep in root.findall(".//m:dependency", ns):
					groupId = dep.find("m:groupId", ns)
					artifactId = dep.find("m:artifactId", ns)
					version = dep.find("m:version", ns)
					g = groupId.text if groupId is not None else ""
					a = artifactId.text if artifactId is not None else ""
					v = version.text if version is not None else ""
					result.add(f"{g}:{a}:{v}")
			except Exception as e:
				print(f"Error parsing {pom_path}: {e} - pom-list-all.py:25")

with open(output_file, "w") as f:
	for line in sorted(result):
		f.write(line + "\n")

print(f"Exported to {output_file} - pom-list-all.py:31")

วิธีใช้

  1. เซฟ script นี้เป็นไฟล์ เช่น pom-list-all.py ใน root project
  2. เปิด terminal ที่ root ของโปรเจกต์
  3. รัน python3 pom-list-all.py
  4. จะได้ไฟล์ pom-list-all.txt ที่รวมรายชื่อ dependency ทั้งหมด ( package, dependency, version ) แบบครบถ้วน

อ่านเพิ่มเติม

Exit mobile version