#!/bin/bash
#
# Retroflow
#
# This makes it easier to retrofit Flow type checking onto your existing code.
#
# Given a path argument, it finds all the js/jsx files under that path that
# don't have the Flow (flowtype.org) preamble. It then adds it and runs the
# Flow check. If anything fails, it removes it again.
#
# It's a little hacky and slow but gets it done.
#
# Enjoy,
# Turadg Aleahmad

# About weak mode https://flowtype.org/docs/existing.html
# If you have type annotations already, try running without ' weak' first.
PREAMBLE="/* @flow weak */\n"

try_flow ()
{
  ORIG=$1
  SWAP=$1.swap
  mv $ORIG $SWAP
  printf "$PREAMBLE" | cat - $SWAP > $ORIG
  echo "Testing $ORIG"
  flow force-recheck $ORIG
  flow status
  if [[ $? == 0 ]]; then
    echo "  kept new Flow preamble"
    rm $SWAP
  else
    echo "  restored original"
    mv $SWAP $ORIG
  fi
}

ROOT=$1
echo "Testing Flow preamble in $ROOT"

FILES=`find -E $ROOT -regex '.*\.jsx?'`
FILES_SANS_FLOW=`echo $FILES |xargs grep -L '@flow'`

echo `echo $FILES_SANS_FLOW | wc -w` of `echo $FILES | wc -w` files found without Flow preamble

for jsxfile in $FILES_SANS_FLOW ; do
  try_flow $jsxfile
done