Created
June 18, 2021 20:39
-
-
Save vacas/3aeb79ee5c0d68147c122dc542a67757 to your computer and use it in GitHub Desktop.
To duplicate components
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# $1=<new template component name> | |
# $2=<new template function name> | |
# expected file structure | |
# components | |
# / TemplateComponent | |
# / index.ts | |
# / TemplateComponent.tsx | |
# / TemplateComponent.test.tsx | |
# / TemplateComponent.module.scss | |
# / templateFunction.ts | |
# / templateFunction.test.ts | |
# COMPONENT_DIR=<path/to/components> | |
COMPONENT_DIR=. | |
TEMPLATE_COMPONENT="TemplateComponent" | |
TEMPLATE_FUNCTION="templateFunction" | |
INDEX_FILE="index.ts" | |
NEW_COMPONENT_NAME=$1 | |
NEW_FUNCTION_NAME=$2 | |
OLD_DIR=$COMPONENT_DIR/__$TEMPLATE_COMPONENT | |
NEW_DIR=$COMPONENT_DIR/$NEW_COMPONENT_NAME | |
# getting all template file names in templates directory | |
TEMPLATE_NAMES=$(ls $OLD_DIR) | |
[ -d "$NEW_DIR" ] && rm -rf $NEW_DIR && echo "> $NEW_DIR already existed and has been replaced" | |
cp -r $OLD_DIR $NEW_DIR | |
echo "> duplicated $OLD_DIR with $NEW_DIR" | |
# replaces all instances of template name with new name | |
replace_instances () { | |
local file="$1" | |
local template_name="$2" | |
local new_name="$3" | |
sed -i '' -e "s/${template_name}/${new_name}/g" $NEW_DIR/$file | |
echo "> replaced all instances of $template_name with $new_name inside of $NEW_DIR/$file" | |
} | |
replace_name () { | |
local file="$1" | |
local template_name="$2" | |
local new_name="$3" | |
# replaces string of current filename with new filename and stores in variable | |
NEW_FILENAME=${file/${template_name}/${new_name}} | |
# renames current filename with new filename | |
mv $NEW_DIR/$file $NEW_DIR/$NEW_FILENAME | |
echo "> renamed $file to $NEW_FILENAME" | |
replace_instances $NEW_FILENAME $template_name $new_name | |
} | |
for file in $TEMPLATE_NAMES | |
do | |
case $file in | |
(*$TEMPLATE_COMPONENT*) | |
replace_name $file $TEMPLATE_COMPONENT $NEW_COMPONENT_NAME | |
;; | |
(*$TEMPLATE_FUNCTION*) | |
# if second variable does not exist, remove from file system | |
if [ -z ${2+x} ]; | |
then | |
rm $NEW_DIR/$file | |
echo "> removed $NEW_DIR/$file" | |
else | |
replace_name $file $TEMPLATE_FUNCTION $NEW_FUNCTION_NAME | |
fi | |
;; | |
$INDEX_FILE) | |
# index.ts is a separate case and only needs to replace | |
replace_instances $file $TEMPLATE_COMPONENT $NEW_COMPONENT_NAME | |
esac | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment