Skip to content

Instantly share code, notes, and snippets.

@bpatram
Last active February 15, 2020 21:22
Show Gist options
  • Save bpatram/76364725f389ef0f5507b6d7140ccb77 to your computer and use it in GitHub Desktop.
Save bpatram/76364725f389ef0f5507b6d7140ccb77 to your computer and use it in GitHub Desktop.
Strip Flowtype Types from JS files
#!/bin/bash
# ---------------------------
# Author: Brandon Patram
# Date: 2020-02-15
#
# Description: Strip flowtype types from js files
#
# Usage: strip-flowtype.sh [path to directory]
# Examples:
# ./strip-flowtype.sh path/to-dir
# ./strip-flowtype.sh path/to-dir path/to-another-dir
# ---------------------------
parallel_jobs=$(sysctl -n hw.physicalcpu)
stripper_command="npx flow-remove-types"
prettier_command="npx prettier"
function build_file_list() { (
set -e
local files search_dirs
files=()
search_dirs=("$@")
for search_dir in "${search_dirs[@]}"; do
files+=($(find "$search_dir" -type f -name "*.js"))
done
echo "${files[*]}"
); }
function strip_file() {
local file_path new_file_path
file_path="$1"
new_file_path=${file_path//.js/.temp.js}
# strip types and prettierify them.
# the flowtype stripper replaces the "// @flow" comments with an empty comment "//".
# prettier doesn't remove that empty comment for us, so we will remove that bit manually via sed
if (
eval "$stripper_command" "$file_path" |
sed -E '/\/\/[[:space:]]*$/d' |
eval "$prettier_command" "--stdin-filepath" "$file_path" "--write"
) >"$new_file_path" &&
# overwrite original file with transformed file
mv "$new_file_path" "$file_path"; then
printf "%s ... \e[32m%s\e[39m\n" "$file_path" "success!"
return 0
else
# attempt to clean up tmp file
rm -f "$new_file_path"
printf "%s ... \e[91m%s\e[39m\n" "$file_path" "failure!"
return 1
fi
}
function strip_files() {
local files has_failures
files=("$@")
has_failures=0
# run in batches of $parallel_jobs
for ((i = 0; i < ${#files[@]}; i += parallel_jobs)); do
batch=("${files[@]:i:parallel_jobs}")
for file_path in "${batch[@]}"; do
# run in the background to transform files in parallel
strip_file "$file_path" &
done
# wait for all background'd tasks to finish. then proceed to next batch
if ! wait; then
has_failures=1
fi
done
return $has_failures
}
function main() {
printf "%s" "Traversing search paths... "
js_files=($(build_file_list "$@")) || exit 1
echo "found ${#js_files[@]} files"
echo "Starting..."
if strip_files "${js_files[@]}"; then
echo "Done!"
exit 0
else
echo "Partially completed!"
exit 1
fi
}
# do work
main "$@"
@bpatram
Copy link
Author

bpatram commented Feb 15, 2020

If you trust Github and this script but don't want to be bothered downloading this file to run it, you can do:

bash <(curl -s https://gist.githubusercontent.com/bpatram/76364725f389ef0f5507b6d7140ccb77/raw/strip-flowtype.sh) path/to/directory path/to/another-directory

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment