json: rm trailing spaces

This commit is contained in:
ochafik 2024-03-11 00:27:50 +00:00
parent 0e9494183b
commit 11813a6b0a
4 changed files with 21 additions and 22 deletions

View file

@ -77,7 +77,7 @@ class SchemaConverter:
if ref.startswith('https://'): if ref.startswith('https://'):
assert self._allow_fetch, 'Fetching remote schemas is not allowed (use --allow-fetch for force)' assert self._allow_fetch, 'Fetching remote schemas is not allowed (use --allow-fetch for force)'
import requests import requests
frag_split = ref.split('#') frag_split = ref.split('#')
base_url = frag_split[0] base_url = frag_split[0]
@ -94,16 +94,16 @@ class SchemaConverter:
n['$ref'] = ref n['$ref'] = ref
else: else:
raise ValueError(f'Unsupported ref {ref}') raise ValueError(f'Unsupported ref {ref}')
for sel in ref.split('#')[-1].split('/')[1:]: for sel in ref.split('#')[-1].split('/')[1:]:
assert target is not None and sel in target, f'Error resolving ref {ref}: {sel} not in {target}' assert target is not None and sel in target, f'Error resolving ref {ref}: {sel} not in {target}'
target = target[sel] target = target[sel]
self._refs[ref] = target self._refs[ref] = target
else: else:
for v in n.values(): for v in n.values():
visit(v) visit(v)
return n return n
return visit(schema) return visit(schema)
@ -220,7 +220,7 @@ class SchemaConverter:
assert len(nums) == 2 assert len(nums) == 2
min_times = int(nums[0]) if nums[0] else 0 min_times = int(nums[0]) if nums[0] else 0
max_times = int(nums[1]) if nums[1] else None max_times = int(nums[1]) if nums[1] else None
(sub, sub_is_literal) = seq[-1] (sub, sub_is_literal) = seq[-1]
if min_times == 0 and max_times is None: if min_times == 0 and max_times is None:
@ -239,7 +239,7 @@ class SchemaConverter:
seq[-1] = ( seq[-1] = (
' '.join( ' '.join(
([f'"{sub[1:-1] * min_times}"'] if sub_is_literal else [sub] * min_times) + ([f'"{sub[1:-1] * min_times}"'] if sub_is_literal else [sub] * min_times) +
([f'{sub}?'] * (max_times - min_times) if max_times is not None else [f'{sub}*'])), ([f'{sub}?'] * (max_times - min_times) if max_times is not None else [f'{sub}*'])),
False False
) )
@ -265,9 +265,9 @@ class SchemaConverter:
if i < length and pattern[i] not in ('.', '(', ')', '|', '[', '{', '*', '+', '?'): if i < length and pattern[i] not in ('.', '(', ')', '|', '[', '{', '*', '+', '?'):
seq.append((f'"{pattern[i]}"', True)) seq.append((f'"{pattern[i]}"', True))
i += 1 i += 1
return join_seq() return join_seq()
return self._add_rule(name, transform()[0]) return self._add_rule(name, transform()[0])
@ -279,7 +279,7 @@ class SchemaConverter:
ref_name = self.visit(resolved, ref_name) ref_name = self.visit(resolved, ref_name)
self._refs_being_resolved.remove(ref) self._refs_being_resolved.remove(ref)
return ref_name return ref_name
def visit(self, schema, name): def visit(self, schema, name):
schema_type = schema.get('type') schema_type = schema.get('type')
rule_name = name or 'root' rule_name = name or 'root'
@ -289,7 +289,7 @@ class SchemaConverter:
elif 'oneOf' in schema or 'anyOf' in schema: elif 'oneOf' in schema or 'anyOf' in schema:
return self._add_rule(rule_name, self._generate_union_rule(name, schema.get('oneOf') or schema['anyOf'])) return self._add_rule(rule_name, self._generate_union_rule(name, schema.get('oneOf') or schema['anyOf']))
elif isinstance(schema_type, list): elif isinstance(schema_type, list):
return self._add_rule(rule_name, self._generate_union_rule(name, [{'type': t} for t in schema_type])) return self._add_rule(rule_name, self._generate_union_rule(name, [{'type': t} for t in schema_type]))
@ -312,7 +312,7 @@ class SchemaConverter:
def add_component(comp_schema, is_required): def add_component(comp_schema, is_required):
if (ref := comp_schema.get('$ref')) is not None: if (ref := comp_schema.get('$ref')) is not None:
comp_schema = self._refs[ref] comp_schema = self._refs[ref]
if 'properties' in comp_schema: if 'properties' in comp_schema:
for prop_name, prop_schema in comp_schema['properties'].items(): for prop_name, prop_schema in comp_schema['properties'].items():
properties.append((prop_name, prop_schema)) properties.append((prop_name, prop_schema))
@ -369,7 +369,7 @@ class SchemaConverter:
else: else:
rule = f'"[" space {item_rule_name} {successive_items} "]" space' rule = f'"[" space {item_rule_name} {successive_items} "]" space'
return self._add_rule(rule_name, rule) return self._add_rule(rule_name, rule)
elif schema_type in (None, 'string') and 'pattern' in schema: elif schema_type in (None, 'string') and 'pattern' in schema:
return self._visit_pattern(schema['pattern'], rule_name) return self._visit_pattern(schema['pattern'], rule_name)
@ -382,7 +382,7 @@ class SchemaConverter:
for t, r in PRIMITIVE_RULES.items(): for t, r in PRIMITIVE_RULES.items():
self._add_rule(t, r) self._add_rule(t, r)
return 'object' return 'object'
else: else:
assert schema_type in PRIMITIVE_RULES, f'Unrecognized schema: {schema}' assert schema_type in PRIMITIVE_RULES, f'Unrecognized schema: {schema}'
# TODO: support minimum, maximum, exclusiveMinimum, exclusiveMaximum at least for zero # TODO: support minimum, maximum, exclusiveMinimum, exclusiveMaximum at least for zero
@ -390,7 +390,7 @@ class SchemaConverter:
'root' if rule_name == 'root' else schema_type, 'root' if rule_name == 'root' else schema_type,
PRIMITIVE_RULES[schema_type] PRIMITIVE_RULES[schema_type]
) )
def _build_object_rule(self, properties: List[Tuple[str, Any]], required: Set[str], name: str): def _build_object_rule(self, properties: List[Tuple[str, Any]], required: Set[str], name: str):
prop_order = self._prop_order prop_order = self._prop_order
# sort by position in prop_order (if specified) then by original order # sort by position in prop_order (if specified) then by original order
@ -406,9 +406,9 @@ class SchemaConverter:
required_props = [k for k in sorted_props if k in required] required_props = [k for k in sorted_props if k in required]
optional_props = [k for k in sorted_props if k not in required] optional_props = [k for k in sorted_props if k not in required]
rule = '"{" space ' rule = '"{" space '
rule += ' "," space '.join(prop_kv_rule_names[k] for k in required_props) rule += ' "," space '.join(prop_kv_rule_names[k] for k in required_props)
if optional_props: if optional_props:
rule += ' (' rule += ' ('
@ -474,7 +474,7 @@ def main(args_in = None):
action='store_true', action='store_true',
default=False, default=False,
help='Whether to treat dot (".") as matching all chars including line breaks in regular expression patterns') help='Whether to treat dot (".") as matching all chars including line breaks in regular expression patterns')
parser.add_argument('schema', help='file containing JSON schema ("-" for stdin)') parser.add_argument('schema', help='file containing JSON schema ("-" for stdin)')
args = parser.parse_args(args_in) args = parser.parse_args(args_in)

View file

@ -8,7 +8,7 @@ print(subprocess.check_output(
"python", "python",
os.path.join( os.path.join(
os.path.dirname(os.path.realpath(__file__)), os.path.dirname(os.path.realpath(__file__)),
"json-schema-to-grammar.py"), "json-schema-to-grammar.py"),
*rest, *rest,
"-", "-",
], ],
@ -16,4 +16,4 @@ print(subprocess.check_output(
input=json.dumps({ input=json.dumps({
"type": "string", "type": "string",
"pattern": pattern, "pattern": pattern,
}, indent=2))) }, indent=2)))

View file

@ -377,4 +377,4 @@ function* groupBy(iterable, keyFn) {
if (group.length > 0) { if (group.length > 0) {
yield [lastKey, group]; yield [lastKey, group];
} }
} }

View file

@ -17,12 +17,11 @@ SCHEMA_FILE="$TMPDIR/schema.json"
echo "export type MyType = $type" > "$DTS_FILE" echo "export type MyType = $type" > "$DTS_FILE"
# This is a fork of typescript-json-schema, actively maintained as of March 2024: # This is a fork of typescript-json-schema, actively maintained as of March 2024:
# https://github.com/vega/ts-json-schema-generator # https://github.com/vega/ts-json-schema-generator
npx ts-json-schema-generator --no-top-ref --path "$DTS_FILE" --type MyType -e none | tee "$SCHEMA_FILE" >&2 npx ts-json-schema-generator --no-top-ref --path "$DTS_FILE" --type MyType -e none | tee "$SCHEMA_FILE" >&2
# Not actively maintained: # Alternative, not actively maintained as of March 2024:
# https://github.com/YousefED/typescript-json-schema # https://github.com/YousefED/typescript-json-schema
# npx typescript-json-schema --defaultProps --required "$DTS_FILE" MyType | tee "$SCHEMA_FILE" >&2 # npx typescript-json-schema --defaultProps --required "$DTS_FILE" MyType | tee "$SCHEMA_FILE" >&2