Daniel-4M
4/20/2020 - 12:26 AM

Unused npm package dependency scan

#!/usr/bin/env zsh

# get some color support
autoload colors; colors

# guard against missing jq dependency
if ! command -v jq > /dev/null; then
  echo $fg[red]This script requires jq$reset_color
  echo try: $fg[green]brew install jq$reset_color
  exit
fi

# get into the right folder
cd $(git rev-parse --show-toplevel)/portal

# brew install jq (if you dont already have it)
dependencies=( $(jq -r ".dependencies | keys[]" package.json) )

# header printing function
# first argument is foreground colour, then the count, left padded for total of 4 digits, then the name of package
print_title () {
    echo -n $fg[$1]
    printf "%4d " $2
    echo $3$reset_color
}

echo DEPENDENCY USAGE
echo "$fg[blue](Dependencies with 1 or 2 uses will have their matches shown)$reset_color"

for var in $dependencies
do
  count=0
  
  # recursive extended regex grep ignoring node_modules with colour support and looking for import lines with the package name as the source
  matches=$(grep -Er --exclude-dir=node_modules --color=always "^.*import.*from[ ]+('|\")$var.*" .)
  
  # if any matches are found save the number of lines to a variable
  if [ "$matches" != "" ]; then
    count=$(echo -e $matches | wc -l | tr -d ' ')
  fi
  
  # use different colours depending on number of matches
  if [ "$count" = "0" ]; then
    print_title "red" $count  $var 
  elif [ "$count" = "1" ] || [ "$count" = "2" ]; then
    print_title "magenta" $count  $var
    # prepend spaces to left align match lines with the title lines
    echo $matches | xargs -I% echo "     "%
  else
    #print_title "green" $count $var 
  fi
done