Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find unused properties in a pom

After inheriting a maven project, I would like to check for unused properties and remove them.

One way I dont want to take is to remove them one by one and see the build fail. Another way would be to count the occurences in the whole codebase (to make sure properties for filters and resources are not wrongly seen as unused) with a custom script. Before I do that, I would like to make sure I'm not reinventing the wheel.

There is a way to do that for the dependencies explained here.
Is there something similar for properties that I have missed? Or a better way?

Thank you

I am using maven 3.0.3

like image 391
kostja Avatar asked Sep 14 '12 08:09

kostja


1 Answers

It's a bit complicated but here's a bash script that will parse the properties element from a pom.xml, check if each property is used in the pom, and optionally checks all project files (a deep search).

#!/bin/bash
cmd=$(basename $0)

read_dom () {
  local IFS=\>
  read -d \< entity content
  local retval=$?
  tag=${entity%% *}
  attr=${entity#* }
  return $retval
}

parse_dom () {
  # uncomment this line to access element attributes as variables
  #eval local $attr
  if [[ $tag = "!--" ]]; then # !-- is a comment 
    return
  elif [[ $tag = "properties" ]]; then
    in=true
  elif [[ $tag = "/properties" ]]; then
    in=
  elif [[ "$in" && $tag != /* ]]; then #does not start with slash                         */
    echo $tag
  fi
}

unused_terms () {
  file=$1
  while read p; do
    grep -m 1 -qe "\${$p}" $file
    if [[ $? == 1 ]]; then echo $p; fi
  done
}

unused_terms_dir () {
  dir=$1
  while read p; do
    unused_term_find $dir $p
  done
}

unused_term_find () {
  dir=$1
  p=$2
  echo -n "$p..."
  find $dir -type f | xargs grep -m 1 -qe "\${$p}" 2> /dev/null
  if [[ $? == 0 ]]; then
    echo -ne "\r$(tput el)"
  else
    echo -e "\b\b\b   "
  fi
}

if [[ -z $1 ]]; then
  echo "Usage: $cmd [-d] <pom-file>"
  exit
fi

if [[ $1 == "-d" ]]; then
  deep=true
  shift
fi

file=$1
dir=$(dirname $1)

if [ $deep ]; then
  while read_dom; do
    parse_dom
  done < $file | unused_terms $file | unused_terms_dir $dir
else
  while read_dom; do
    parse_dom
  done < $file | unused_terms $file
fi

The script uses XML parsing code from this thread.

This script won't find any properties that are used by maven or maven plugins directly. It simply looks for the pattern ${property} within project files.

It works on my mac; your milage may vary.

like image 89
pbatey Avatar answered Oct 27 '22 19:10

pbatey