Skip to content

Instantly share code, notes, and snippets.

@jaytaylor
Created October 18, 2018 21:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaytaylor/0ee30edc9d57b592e1deec223846fa14 to your computer and use it in GitHub Desktop.
Save jaytaylor/0ee30edc9d57b592e1deec223846fa14 to your computer and use it in GitHub Desktop.
Builds and prints java class dependency graph based on import references.
#!/usr/bin/env bash
#
# Builds and prints java class dependency graph based on import references.
# Could be useful for extracting a portion of java files out of a project.
#
# Arg: <class-name>
#
# e.g. ./java-tree.sh CoreNLP/src TokenizerAnnotator
#
set -o errexit
set -o pipefail
set -o nounset
#set -x
function referencedFiles() {
# arg: <java filename>
local file
local found
file="$1"
found="$(grep '^import ' "${file}" | grep -v '\(^import java\.\|\*\)' | sed -e 's/^import \(.*\);/\1/' -e 's/static //' | tr '.' '/' | sed 's/$/.java/')"
echo -n "${found}"
}
function main() {
local searchPath
local className
local file
local files
local pending
local internals
local externals
searchPath="$1"
className="$2"
file="$(find "${searchPath}" -type f -name "${className}.java")"
if [ -z "${file}" ]; then
echo "ERROR: no src file found for '${className}' under '${searchPath}'" 1>&2
return 1
fi
files="$(referencedFiles "${file}")"
while [ -n "${files}" ]; do
for file in ${files}; do
if ! $(echo -e "${internals:-}\n${externals:-}" | grep -q -F "${file}"); then
file="${searchPath}/${file}"
internals="${internals} ${file}"
if ! [ -e "${file}" ]; then
externals="${externals:-} ${file}"
else
pending="${pending} $(referencedFiles "${file}")"
pending="${pending/ //}"
fi
fi
done
files="${pending}"
pending=''
done
internals="$(echo "${internals}" | tr ' ' $'\n')"
externals="$(echo "${externals}" | tr ' ' $'\n')"
echo -e "internals are:\n${internals}"
echo -e "externals are:\n${externals}"
}
if [ "${BASH_SOURCE[0]}" = "${0}" ]; then
set -o errexit
set -o pipefail
set -o nounset
# Only auto-run when being executed (and don't auto-run functions when being sourced).
main "$@"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment