【问题标题】:How to find unused properties in a pom如何在 pom 中查找未使用的属性
【发布时间】:2012-09-07 09:09:43
【问题描述】:

继承一个maven项目后,我想检查一下未使用的属性并删除它们。

我不想采取的一种方法是一个一个地删除它们,然后看到构建失败。另一种方法是使用自定义脚本计算整个代码库中的出现次数(以确保过滤器和资源的属性不会被错误地视为未使用)。在我这样做之前,我想确保我没有重新发明轮子。

对于 here 解释的依赖项,有一种方法可以做到这一点。
我错过的房产有类似的东西吗?还是更好的方法?

谢谢

我使用的是 maven 3.0.3

【问题讨论】:

    标签: java maven maven-3 maven-plugin


    【解决方案1】:

    这有点复杂,但这里有一个 bash 脚本,它将解析 pom.xml 中的 properties 元素,检查 pom 中是否使用了每个属性,并可选择检查所有项目文件(深度搜索)。

    #!/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
    

    该脚本使用来自this thread 的 XML 解析代码。

    此脚本不会找到任何由 maven 或 maven 插件直接使用的属性。它只是在项目文件中查找模式 ${property}。

    它适用于我的 Mac;您的里程可能会有所不同。

    【讨论】:

      【解决方案2】:

      不幸的是,没有比手动操作更好的方法...

      【讨论】:

        【解决方案3】:

        如果您使用 IntelliJ,您可以只搜索该属性的用法。只需将光标放在标签上,然后右键单击 -> 查找用法(在我的情况下,键盘快捷键:Alt+F7)。

        还没有找到更好的方法。

        【讨论】:

          猜你喜欢
          • 2018-08-09
          • 1970-01-01
          • 2012-11-25
          • 1970-01-01
          • 2014-09-21
          • 2020-06-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多