#!/usr/bin/env ruby

# Write a JSON string of the dependencies of a Java Maven project
# to stdout using its pom.xml project file

require 'json'
require 'nokogiri'

parsed_file = nil
begin
  parsed_file = Nokogiri::XML(File.read(ARGV[0]))
rescue StandardError
  warn 'Unable to read and parse pom.xml file'
  exit(1)
end

if parsed_file.errors.size.positive?
  err_msgs = 'Errors:
'
  parsed_file.errors.each { |err| err_msgs += "#{err}\n" }
  warn err_msgs
  exit(1)
end

properties = {}

# Parse contents within each <properties> tag and map it to dependency version
# ${logback.version} => 1.2.10
# <dependency>
#    <groupId>ch.qos.logback</groupId>
#    <artifactId>logback-classic</artifactId>
#    <version>${logback.version}</version>
# </dependency>
# <properties>
#   <logback.version>1.2.10</logback.version>
# </properties>
nodes = parsed_file.css('properties')
nodes.each do |node|
  childrens = node.children
  childrens.each do |children|
    properties["${#{children.name}}"] = children.text
  end
end

dependencies = []

# Parse contents within each <dependency> tag
parsed_file.css('dependency').each do |dependency|
  group_id = dependency.at('groupId')
  artifact_id = dependency.at('artifactId')
  version = dependency.at('version')
  version = properties.dig(version.children.to_s) || version.children.to_s unless version.nil?

  dependency_hash = {}
  dependency_hash[:group_id] = group_id.nil? ? nil : group_id.children.to_s
  dependency_hash[:artifact_id] = artifact_id.nil? ? nil : artifact_id.children.to_s
  dependency_hash[:version] = version
  dependencies.append(dependency_hash)
end

puts dependencies.to_json
