Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Bash script to find unused custom template tags and filters
#!/usr/bin/env bash
#
# Helper script to look for unused template tags and filters.
#
# Run this in the root of your project and it will print out template tags and filters that
# aren't used anywhere.
#
# Requires ripgrep (rg).
set -e
function main() {
echo "Looking for unused template tags"
look_for_dead_tags
echo "Looking for unused template filters"
look_for_dead_filters
}
function look_for_dead_tags() {
local tag
local freq
# Stream input via non-standard file descriptor to avoid stdin-consumption issue from rg.
while read -u9 tag; do
if ! is_tag_used "$tag"
then
echo $tag
fi
done 9< <(tag_names)
}
function look_for_dead_filters() {
local filter
local freq
# Stream input via non-standard file descriptor to avoid stdin-consumption issue from rg.
while read -u9 filter; do
if ! is_filter_used "$filter"
then
echo $filter
fi
done 9< <(filter_names)
}
# Print a stream of template tag names.
function tag_names() {
rg --no-filename "@register.(simple_)tag" -A1 | \
grep "^def " | \
cut -d" " -f2 | cut -d"(" -f1
}
# Print a stream of template filter names.
function filter_names() {
rg --no-filename "@register.filter" -A1 | \
grep "^def " | \
cut -d" " -f2 | cut -d"(" -f1
}
# Test if a passed template tag is in use.
function is_tag_used() {
local tag=$1
[ $(tag_frequency "$tag") -gt 0 ]
}
# Test if a passed template filter is in use.
function is_filter_used() {
local filter=$1
[ $(filter_frequency "$filter") -gt 0 ]
}
# Print the frequency that the passed template tag is used to stdout.
function tag_frequency() {
local tag=$1
rg -F "{% $tag " | wc -l
}
# Print the frequency that the passed template filter is used to stdout.
function filter_frequency() {
local filter=$1
rg "\|\s*$filter" | wc -l
}
main
@LuRsT

This comment has been minimized.

Copy link

@LuRsT LuRsT commented Feb 4, 2020

This was useful to me ❤️

@benhowes

This comment has been minimized.

Copy link

@benhowes benhowes commented Feb 4, 2020

I updated the tag regex to add support for inclusion_tag, meaning the regex on mine is rg --no-filename "@register.(simple_|inclusion_)tag" -A1

Thanks for this 👍

@codeinthehole

This comment has been minimized.

Copy link
Owner Author

@codeinthehole codeinthehole commented Feb 5, 2020

Thanks @benhowes - good tip

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment