Skip to content

Instantly share code, notes, and snippets.

@belchior
Last active September 9, 2018 01:40
Show Gist options
  • Save belchior/339b8add562050ab920275d534fb66a8 to your computer and use it in GitHub Desktop.
Save belchior/339b8add562050ab920275d534fb66a8 to your computer and use it in GitHub Desktop.
Lista imports não utilizados em arquivos .ts
#!/usr/bin/env bash
function delimiterStart() {
echo '********************************************************************************'
}
function delimiterEnd() {
echo '================================================================================'
}
function delimiterThin() {
echo '--------------------------------------------------------------------------------'
}
function title() {
local title=$1
echo $title
delimiterThin
}
countTerm() {
local name=$1
local filePath=$2
local terms=$(grep --only-matching $name $filePath | wc --lines)
printf '%s\n' $terms
}
getImportsFromFile() {
local filePath=$1
grep --no-filename --extended-regexp '^import\s+\{[^}]+\}\s+from[^;]+;*' $filePath
}
extractModuleFromImport() {
while read importLine; do
sed --regexp-extended 's/import.*from\s+(.*)/\1/' <<< $importLine
done
}
extractNamedImports() {
while read importLine; do
sed --regexp-extended -e 's/import\s+\{([^}]+)\}.*/\1/' -e 's/\s*,\s*/\n/g' <<< $importLine
done
}
splitImports() {
while read importLine; do
local module=$(extractModuleFromImport <<< $importLine)
while read name; do
printf 'import { %s } from %s\n' $name $module
done <<< "$(extractNamedImports <<< $importLine)"
done
}
getDistinctImportFromFile() {
local filePath=$1
getImportsFromFile $filePath | splitImports | sort | uniq
}
getDuplicateImportsFromFile() {
local filePath=$1
getImportsFromFile $filePath | \
splitImports | \
sort | \
uniq -cd | \
sed --regexp-extended 's/\s+([0-9]+).*\{([^}]+)\}.*/\1\2/' | \
xargs -i% echo "% $filePath"
}
listUnusedImports() {
local directory=$1
while read filePath; do
local duplicates=$(getDuplicateImportsFromFile $filePath)
while read importLine; do
if [ -n "$importLine" ]; then
while read name; do
local termsNum=$(countTerm $name $filePath)
local duplicatesNum=$(grep --extended-regexp "$name" <<< $duplicates | sed --regexp-extended 's/^([0-9]+).*/\1/')
if [ -n "$duplicatesNum" ]; then
termsNum=$(($termsNum-$duplicatesNum-1))
fi
if [ $termsNum -lt 2 ]; then
# printf '%d %s %s\n' $termsNum $name $filePath
printf '%s %s\n' $name $filePath
fi
done <<< "$(extractNamedImports <<< $importLine)"
fi
done <<< "$(getDistinctImportFromFile $filePath)"
done <<< "$(find $directory -name '*.ts' -type f)"
}
main() {
delimiterStart
title 'Imports não utilizados'
listUnusedImports $src
delimiterEnd
}
main $1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment