Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Last active January 31, 2016 00:58
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 JoshCheek/5fb8959ef16e601c42a1 to your computer and use it in GitHub Desktop.
Save JoshCheek/5fb8959ef16e601c42a1 to your computer and use it in GitHub Desktop.
Pretty printing the interfaces from classes in jar (java archive) files.
#!/bin/bash
# Pic of output at https://twitter.com/josh_cheek/status/693598961026793472
jarfile="$1"
if test -z "$jarfile"
then
echo "You must provide a jarfile as an argument" >&2
exit 1
elif test ! -f "$jarfile"
then
echo "The file you provided" `ruby -e 'print ARGV[0].inspect' "$jarfile"` "does not map to a jarfile" >&2
exit 1
fi
# do the work in a temporary directory
dir=`mktemp -d -t jar-prettyprint`
cp "$jarfile" "$dir"
pushd "$dir" >/dev/null
# extract the contents of the jar
jar xf "$jarfile"
# Pretty print the class files
find . -type f -name '*.class' | # list the files that end in .class
xargs javap | # disassemble them
ruby -r coderay -ne '
# Aggregate disassembled info in @code
BEGIN { @code = "" }
# Pretty print the disassembled code and reset the var
def next_class
print CodeRay.encode(@code, :java, :terminal)
@code = ""
end
# Print previous code and header for next piece of code
if /^Compiled from/
next_class
puts "\e[1;92m#{$_.chomp}\e[0m"
else
@code << $_
end
# Print last chunk of code (there is no header after it to trigger this)
END { next_class }
'
# Return from the temp dir
popd >/dev/null
# Clean up the temp dir
rm -r "$dir"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment