Skip to content

Instantly share code, notes, and snippets.

@naiquevin
Last active March 8, 2023 17:22
Show Gist options
  • Save naiquevin/0c68ee53b0e4b2690f4787a57c9e7d0e to your computer and use it in GitHub Desktop.
Save naiquevin/0c68ee53b0e4b2690f4787a57c9e7d0e to your computer and use it in GitHub Desktop.
A crude way to find clojure functions usages in a codebase using ripgrep (false positives possible)
#!/usr/bin/env bash
## Script for searching for all references to a particular function in
## a clojure project (A crude implementation of "Find usage"
## functionality commonly found in IDEs such as Intellij) False
## positives are possible.
##
## Usage:
##
## $ clj-fn-usages NAMESPACE_QUALIFIED_FN [ paths ... ]
##
## Example:
##
## $ clj-fn-usages my.namespace/myfunction src test
set -e
function ns2path () {
local segment=$(echo $1 | sed 's/\./\//g' | sed 's/-/_/g')
echo "src/$segment.clj"
}
fqvar=$1
shift;
searchdirs="$@"
if [[ -z "$searchdirs" ]]; then
searchdirs=src
fi
ns=$(echo $fqvar | cut -d '/' -f 1)
fn=$(echo $fqvar | cut -d '/' -f 2)
nsfile=$(ns2path $ns)
# Find aliases in the code base
aliases=$(rg "\[$ns" $searchdirs | grep -Eo ':as \w+' | sed 's/:as //' | sort -u)
echo "Aliases: $aliases" | tr '\n' ' '
echo
echo "Search paths: $searchdirs"
echo
set +e
# Display local usages in the same namespace if any
if rg --pcre2 -l "$fn(?![-|*])" $nsfile; then
rg --pcre2 "$fn(?![-|*])" $nsfile
echo
fi
for al in $aliases
do
rg --pcre2 "$al/$fn(?![-|*])" $searchdirs
echo
done
set -e
referrers=$(rg -U "\[$ns [^]]+" $searchdirs | rg -o ".+:.+$fn" | cut -d ':' -f 1)
echo
set +e
for rf in $referrers
do
rg --pcre2 -l "$fn(?![-|*])" $rf
rg --pcre2 ".*[^/]{1}$fn(?![-|*])" $rf
done
set -e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment