Skip to content

Instantly share code, notes, and snippets.

@tlmurphy
Last active June 2, 2021 22:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tlmurphy/71b58c71e594899120da365159d7d40d to your computer and use it in GitHub Desktop.
Save tlmurphy/71b58c71e594899120da365159d7d40d to your computer and use it in GitHub Desktop.
Fix missing parameter for JsonObject when using json2typescript 1.4.0+
from io import TextIOWrapper
import sys
import re
import glob
Q = "'"
REGEX = f'@JsonObject\({Q}{Q}\)|@JsonObject\(\)|^@JsonObject$'
def no_class_descriptor(line):
pattern = re.compile(REGEX)
if pattern.search(line):
return True
return False
'''
Read lines until the class token is found, then return that line.
Appends each read line to the extra_lines list along the way just in
case there are extra lines between the JsonObject decorator and the class
declaration.
Exits the script with an error if no class declaration was found for
the JsonObject decorator.
'''
def get_class_line(read_object: TextIOWrapper, extra_lines: list, filename: str):
line = read_object.readline()
while line:
tokens = line.split()
for i in range(len(tokens)):
if tokens[i] == 'class':
return line
extra_lines.append(line)
line = read_object.readline()
# Invalid JsonObject decorator
read_object.close()
sys.exit(f"Invalid JsonObject decorator found in file: {filename}!")
def get_class_name(class_line: str):
tokens = class_line.split()
for i in range(len(tokens)):
if tokens[i] == 'class':
return tokens[i+1]
def add_class_descriptor(line, class_name):
return re.sub(
REGEX,
f'@JsonObject({Q}{class_name}{Q})',
line
)
def fix_class_decorators(filename):
read_object = open(filename, 'r')
updated_lines = []
line = read_object.readline()
while line:
if no_class_descriptor(line):
extra_lines = []
class_line = get_class_line(read_object, extra_lines, filename)
class_name = get_class_name(class_line)
updated_lines.append(add_class_descriptor(line, class_name))
updated_lines.extend(extra_lines)
updated_lines.append(class_line)
else:
updated_lines.append(line)
line = read_object.readline()
read_object.close()
write_object = open(filename, 'w')
write_object.writelines(updated_lines)
write_object.close()
ts_files = glob.glob('src/**/*.ts', recursive=True)
for f in ts_files:
fix_class_decorators(f)
@tlmurphy
Copy link
Author

tlmurphy commented Jun 1, 2021

This Gist replaces empty JsonObject decorators with the decorator plus the class name as the first parameter. This resolves issues in upgrading to json2typescript 1.4.0+

Some things to note:

  1. Q can be replaced with double quotes if your project uses double quotes.
  2. This script assumes all the files needing to be replaced reside under src, but that can be easily modified by users of this script.

Usage:
python3 fix_class_decorators.py

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