#!/bin/bash -e

# Run this script to find code that is exported from our TS files but not
# actually referenced by any other code.  In general, that code doesn't need to
# be exported, and likely can be deleted.
#
# This script excludes operations.ts and resolverTypes.ts files, since they're
# generated by script and end up exporting a bunch of things on spec, which is
# fine.  It also ignores the opensource directory, since we export lots of stuff
# there that is intended to be used by customers.
#
# Tips:
#
# Often removing unused code will cause other code to become unused,
# necessitating a few rounds.  To make that easier, you can save the initial run
# and then diff against it to find things that have newly become unused:
#
# $ find-unused-code.sh > unused-v1
# # remove some unused code
# $ diff unused-v1 <(find-unused-code.sh)

# We combine two different searches together:
#
# 1. ts-prune with default arguments, which simply finds code that's never
#    called (or never called from outside its module)
# 2. ts-prune with arguments that say not to consider usages coming from test
#    files (as matched by a path regex) and also to not output stuff that's not
#    called from outside the module.
# 
# Together, that means we'll mark as unused code that's only called from tests,
# but we won't mark as unused exported code that is only exported because it's
# used in a test.

cat <( npx ts-prune ) <( npx ts-prune -u -s '(/tests/)|(test.ts$)' ) \
  | grep -v 'operations.ts:' \
  | grep -v 'resolverTypes.ts:' \
  | grep -v '^opensource/' \
  | sort \
  | uniq
