Skip to content

Instantly share code, notes, and snippets.

@krystalcampioni
Created November 28, 2024 22:20
Show Gist options
  • Save krystalcampioni/e6b056deff11055b1b7c08a2885eb095 to your computer and use it in GitHub Desktop.
Save krystalcampioni/e6b056deff11055b1b7c08a2885eb095 to your computer and use it in GitHub Desktop.
generateTranslationTypes() {
if [ "$#" -ne 1 ]; then
echo "Usage: generateTranslationTypes <json-file>"
return 1
fi
JSON_FILE="$1"
if [ ! -f "$JSON_FILE" ]; then
echo "File not found: $JSON_FILE"
return 1
fi
JSON_DIR=$(dirname "$JSON_FILE")
FOLDER_NAME=$(basename "$JSON_DIR")
INTERFACE_NAME=$(echo "$FOLDER_NAME" | sed -E 's/[^a-zA-Z0-9]+/ /g' | awk '{ for(i=1;i<=NF;i++) $i=toupper(substr($i,1,1)) substr($i,2); print }' | tr -d ' ')Translations
OUTPUT_FILE="$JSON_DIR/translationTypes.ts"
JSON_CONTENT=$(cat "$JSON_FILE")
echo "JSON Content: $JSON_CONTENT"
generateTypes() {
local obj="$1"
local indent="$2"
local result=""
for key in $(echo "$obj" | jq -r 'keys[]'); do
local value=$(echo "$obj" | jq -r --arg key "$key" '.[$key]')
local formattedKey="\"$key\"" # Wrap key in quotes
local valueType=$(jq -r 'type' <<<"$value")
if [[ "$valueType" == "object" ]]; then
result+="\n$indent $formattedKey: {"
result+="$(generateTypes "$value" " $indent")"
result+="\n$indent },"
elif [[ "$valueType" == "array" ]]; then
local itemType=$(jq -r '.[0] | type' <<<"$value")
if [[ "$itemType" == "object" ]]; then
result+="\n$indent $formattedKey: { [key: string]: any },"
else
result+="\n$indent $formattedKey: string[],"
fi
else
if [[ "$valueType" == "string" ]]; then
if [[ "$value" =~ \{\{.*\}\} ]]; then
result+="\n$indent $formattedKey: string,"
else
result+="\n$indent $formattedKey: string,"
fi
else
case "$valueType" in
"number")
result+="\n$indent $formattedKey: number,"
;;
"boolean")
result+="\n$indent $formattedKey: boolean,"
;;
*)
result+="\n$indent $formattedKey: any,"
;;
esac
fi
fi
done
echo -e "${result%,}" # Remove trailing comma
}
# Generate the TypeScript interface
TYPE_DEFINITION="export interface ${INTERFACE_NAME} {$(generateTypes "$JSON_CONTENT" " ")}"
echo -e "$TYPE_DEFINITION" >"$OUTPUT_FILE"
echo "Created: $OUTPUT_FILE"
if command -v prettier &>/dev/null; then
prettier --write "$OUTPUT_FILE"
echo "Formatted: $OUTPUT_FILE"
else
echo "Prettier is not installed. Please install it to format the output file."
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment