diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..59e3228 --- /dev/null +++ b/.gitignore @@ -0,0 +1,104 @@ +install_test + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# dotenv +.env + +# virtualenv +.venv +venv/ +ENV/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ diff --git a/AUTHORS.md b/AUTHORS.md new file mode 100644 index 0000000..c25d0a2 --- /dev/null +++ b/AUTHORS.md @@ -0,0 +1,13 @@ +======= +Credits +======= + +Development Lead +---------------- + +* Daigo Tanaka, Anelen Co., LLC + +Contributors +------------ + +None yet. Why not be the first? diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..ea885e8 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,22 @@ +# Contributor Code of Conduct + +As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. + +We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality. + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery +* Personal attacks +* Trolling or insulting/derogatory comments +* Public or private harassment +* Publishing other's private information, such as physical or electronic addresses, without explicit permission +* Other unethical or unprofessional conduct + +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect of managing this project. Project maintainers who do not follow or enforce the Code of Conduct may be permanently removed from the project team. + +This code of conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers. + +This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org), version 1.2.0, available at https://www.contributor-covenant.org/version/1/2/0/code-of-conduct.html diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..29c1ada --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,73 @@ +# Contributing + +Contributions are welcome, and they are greatly appreciated! Every little bit +helps, and credit will always be given. + +You can contribute in many ways: + +## Types of Contributions + +### Report Bugs + +Report bugs at https://github.com/daigotanaka/getschema/issues. + +If you are reporting a bug, please include: + +- Your operating system name and version. +- Any details about your local setup that might be helpful in troubleshooting. +- Detailed steps to reproduce the bug. + +### Fix Bugs + +Look through the GitHub issues for bugs. Anything tagged with "bug" and "help +wanted" is open to whoever wants to implement it. + +### Implement Features + +Look through the GitHub issues for features. Anything tagged with "enhancement" +and "help wanted" is open to whoever wants to implement it. + +### Write Documentation + +getschema could always use more documentation, whether as part of the +official README.md, in docstrings, or even on the web in blog posts, +articles, and such. + +### Submit Feedback + +The best way to send feedback is to file an issue at https://github.com/daigotanaka/getschema/issues. + +If you are proposing a feature: + +- Explain in detail how it would work. +- Keep the scope as narrow as possible, to make it easier to implement. +- Remember that this is a volunteer-driven project, and that contributions + are welcome :) + +## Submit a pull request through the GitHub website. + +### Pull Request Guidelines + +Before you submit a pull request, check that it meets these guidelines: + +1. The pull request should include tests. +2. If the pull request adds functionality, the docs should be updated. Put + your new functionality into a function with a docstring, and add the + feature to the list in README.md. + +TODO: Set up Travis: +3. The pull request should work for Python 3.6, 3.7 and 3.8, and for PyPy. Check + https://travis-ci.org/daigotanaka/getschema/pull_requests + and make sure that the tests pass for all supported Python versions. + +## Deploying + +A reminder for the maintainers on how to deploy. +Make sure all your changes are committed (including an entry in HISTORY.md). +Then run:: + +$ bump2version patch # possible: major / minor / patch +$ git push +$ git push --tags + +TODO: Set up Travis so it will then deploy to PyPI if tests pass. diff --git a/HISTORY.md b/HISTORY.md new file mode 100644 index 0000000..972433c --- /dev/null +++ b/HISTORY.md @@ -0,0 +1,5 @@ +## History + +### 0.1.0 (2020-11-25) + +Initial release diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..82e152d --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,2 @@ +# Add additional files to be included in the package +# recursive-include getschema/data * diff --git a/README.md b/README.md index dcfdb02..22f9079 100644 --- a/README.md +++ b/README.md @@ -6,10 +6,35 @@ Get jsonschema from sample records Command line usage: ``` -json2schema file.json +usage: getschema [-h] [--indent INDENT] [--type TYPE] [--skip SKIP] [--lower] + [--replace_special REPLACE_SPECIAL] [--snakecase] + data + +positional arguments: + data json record file + +optional arguments: + -h, --help show this help message and exit + --indent INDENT, -i INDENT + Number of spaces for indentation + --type TYPE, -t TYPE Record format (json, csv) + --skip SKIP, -s SKIP Skip first n records. Don't skip the header row. + --lower, -l Convert the keys to lower case' + --replace_special REPLACE_SPECIAL, -r REPLACE_SPECIAL + Replace special characters in the keys with the + specified string + --snakecase, -n Convert the keys to 'snake_case' +getschema file.json ``` -Projects using json2schema: +Module functions: +(See impl.py) +- infer_schema +- infer_from_json_file +- infer_from_csv_file +- fix_type + +Example projects using getschema: - https://github.com/anelendata/tap-rest-api - https://github.com/anelendata/tap-bigquery diff --git a/getschema/__init__.py b/getschema/__init__.py new file mode 100644 index 0000000..a0a4762 --- /dev/null +++ b/getschema/__init__.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python3 +import argparse +import simplejson as json +from .impl import * + +# JSON schema follows: +# https://json-schema.org/ +COMMAND = "getschema" + + +def main(): + """ + Entry point + """ + parser = argparse.ArgumentParser(COMMAND) + parser.add_argument("data", type=str, help="json record file") + parser.add_argument("--indent", "-i", default=2, type=int, + help="Number of spaces for indentation") + parser.add_argument("--type", "-t", default="json", type=str, + help="Record format (json, csv)") + parser.add_argument("--skip", "-s", default=0, type=int, + help="Skip first n records. Don't skip the header row.") + parser.add_argument("--lower", "-l", default=False, action="store_true", + help="Convert the keys to lower case'") + parser.add_argument("--replace_special", "-r", default=None, type=str, + help="Replace special characters in the keys with the specified string") + parser.add_argument("--snakecase", "-n", default=False, action="store_true", + help="Convert the keys to 'snake_case'") + args = parser.parse_args() + + schema = infer_from_file(args.data, args.type.lower(), args.skip, + args.lower, args.replace_special, args.snakecase) + + print(json.dumps(schema, indent=args.indent)) + + +if __name__ == "__main__": + main() diff --git a/getschema/impl.py b/getschema/impl.py new file mode 100644 index 0000000..46eead9 --- /dev/null +++ b/getschema/impl.py @@ -0,0 +1,313 @@ +#!/usr/bin/env python3 +import argparse, datetime, dateutil, os, re, sys +from dateutil.tz import tzoffset +import simplejson as json + +# JSON schema follows: +# https://json-schema.org/ +COMMAND = "json2schema" + + +def _convert_key(old_key, lower=False, replace_special=False, snake_case=False): + new_key = old_key + if lower: + new_key = new_key.lower() + if replace_special: + new_key = re.sub('[^ a-zA-Z0-9_]', '_', new_key) + if snake_case: + new_key = new_key.strip().replace(" ", "_") + return new_key + + +def _do_infer_schema(obj, record_level=None, lower=False, + replace_special=False, snake_case=False): + schema = dict() + + # Go down to the record level if specified + if record_level: + for x in record_level.split(","): + obj = obj[x] + + if type(obj) is dict and obj.keys(): + schema["type"] = ["null", "object"] + schema["properties"] = dict() + for key in obj.keys(): + ret = _do_infer_schema(obj[key]) + new_key = _convert_key( + key, lower=lower, replace_special=replace_special, + snake_case=snake_case) + if ret: + schema["properties"][new_key] = ret + + if ret: + schema["properties"][key] = ret + elif type(obj) is list: + if not obj: + return None + # TODO: Check more than the first record + ret = _do_infer_schema( + obj[0], lower=lower, replace_special=replace_special, + snake_case=snake_case) + if ret: + schema["type"] = ["null", "array"] + schema["items"] = ret + else: + try: + float(obj) + except: + schema["type"] = ["null", "string"] + # TODO: This is a very loose regex for date-time. + if (type(obj) is datetime.datetime or + type(obj) is datetime.date or + (type(obj) is str and + re.match("(19|20)\d\d-(0[1-9]|1[012])-([1-9]|0[1-9]|[12][0-9]|3[01])", + obj) is not None)): + schema["format"] = "date-time" + else: + if type(obj) == bool: + schema["type"] = ["null", "boolean"] + elif type(obj) == float or (type(obj) == str and "." in obj): + schema["type"] = ["null", "number"] + # Let's assume it's a code such as zipcode if there is a leading 0 + elif type(obj) == int or (type(obj) == str and obj[0] != "0"): + schema["type"] = ["null", "integer"] + else: + schema["type"] = ["null", "string"] + return schema + + +def _compare_props(prop1, prop2): + if not prop2: + return prop1 + elif not prop1: + return prop2 + prop = prop2 + t1 = prop1["type"] + t2 = prop2["type"] + f1 = prop1.get("format") + f2 = prop2.get("format") + if t1[1] == "object": + assert(t1[1] == t2[1]) + for key in prop["properties"]: + prop["properties"][key] = _compare_props( + prop1["properties"].get(key), prop2["properties"].get(key)) + if t1[1] == "array": + assert(t1[1] == t2[1]) + prop["items"] = _compare_props(prop1["items"], prop2["items"]) + + numbers = ["integer", "number"] + if not (t1[1] == t2[1] and f1 == f2): + if t1[1] in numbers and t2[1] in numbers: + prop["type"] = ["null", "number"] + else: + prop["type"] = ["null", "string"] + if "format" in prop.keys(): + prop.pop("format") + + return prop + + +def _infer_from_two(schema1, schema2): + """ + Compare between currently the most conservative and the new record schemas + and keep the more conservative one. + """ + if schema1 is None: + return schema2 + if schema2 is None: + return schema1 + schema = schema2 + for key in schema1["properties"]: + prop1 = schema1["properties"][key] + prop2 = schema2["properties"].get(key, prop1) + schema["properties"][key] = _compare_props(prop1, prop2) + return schema + + +def _nested_get(input_dict, nested_key): + internal_dict_value = input_dict + for k in nested_key: + internal_dict_value = internal_dict_value.get(k, None) + if internal_dict_value is None: + return None + return internal_dict_value + + +def _parse_datetime_tz(datetime_str, default_tz_offset=0): + d = dateutil.parser.parse(datetime_str) + if not d.tzinfo: + d = d.replace(tzinfo=tzoffset(None, default_tz_offset)) + return d + + +def _on_invalid_property(policy, dict_path, obj_type, obj, err_msg): + if policy == "raise": + raise Exception(err_msg + " dict_path" + str(dict_path) + + " object type: " + obj_type + " object: " + str(obj)) + elif policy == "force": + cleaned = str(obj) + elif policy == "null": + cleaned = None + else: + raise ValueError("Unknown policy: %s" % policy) + return cleaned + + +def infer_schema(obj, record_level=None, + lower=False, replace_special=False, snake_case=False): + """Infer schema from a given object or a list of objects + - record_level: + - lower: Convert the key to all lower case + - replace_special: Replace letters to _ if not 0-9, A-Z, a-z, _ and -, or " " + - snake_case: Replace space to _ + """ + if type(obj) is not list: + obj = [obj] + if type(obj[0]) is not dict: + raise ValueError("Input must be a dict object.") + schema = None + # Go through the entire list of objects and find the most safe type assumption + for o in obj: + cur_schema = _do_infer_schema( + o, record_level, lower, replace_special, snake_case) + # Compare between currently the most conservative and the new record + # and keep the more conservative. + schema = _infer_from_two(schema, cur_schema) + schema["type"] = "object" + return schema + + +def infer_from_json_file( + filename, skip=0, lower=False, replace_special=False, snake_case=False): + with open(filename, "r") as f: + content = f.read() + data = json.loads(content) + if type(data) is list: + data = data[skip:] + schema = infer_schema(data, lower=lower, replace_special=replace_special, + snake_case=snake_case) + + return schema + + +def infer_from_csv_file( + filename, skip=0, lower=False, replace_special=False, snake_case=False): + with open(filename) as f: + count = 0 + while count < skip: + count = count + 1 + f.readline() + reader = csv.DictReader(f) + data = [dict(row) for row in reader] + schema = infer_schema(data, lower=lower, replace_special=replace_special, + snake_case=snake_case) + + return schema + + +def infer_from_file(filename, fmt="json", skip=0, lower=False, + replace_special=False, snake_case=False): + if fmt == "json": + schema = infer_from_json_file( + filename, skip, lower, replace_special, snake_case) + elif fmt == "csv": + schema = infer_from_csv_file(filename, skip, lower, replace_special, snake_case) + else: + raise KeyError("Unsupported format : " + fmt) + return schema + + +def fix_type(obj, schema, dict_path=[], on_invalid_property="raise", + lower=False, replace_special=False, snake_case=False): + """Convert the fields into the proper object types. + e.g. {"number": "1.0"} -> {"number": 1.0} + + - on_invalid_property: ["raise", "null", "force"] + What to do when the value cannot be converted. + - raise: Raise exception + - null: Impute with null + - force: Keep it as is (string) + """ + invalid_actions = ["raise", "null", "force"] + if not on_invalid_property in invalid_actions: + raise ValueError("on_invalid_property is not one of %s" % invalid_actions) + + obj_type = _nested_get(schema, dict_path + ["type"]) + obj_format = _nested_get(schema, dict_path + ["format"]) + + nullable = False + if obj_type is None: + if on_invalid_property == "raise": + raise ValueError("Unknown property found at: %s" % dict_path) + return None + if type(obj_type) is list: + nullable = (obj_type == "null") + obj_type = obj_type[1] + + if obj is None: + if not nullable: + if on_invalid_property == "raise": + raise ValueError("Null object given at %s" % dict_path) + return None + + # Recurse if object or array types + if obj_type == "object": + if not (type(obj) is dict and obj.keys()): + raise KeyError("property type (object) Expected a dict object." + + "Got: %s %s" % (type(obj), str(obj))) + cleaned = dict() + keys = obj.keys() + for key in keys: + ret = fix_type(obj[key], schema, dict_path + ["properties", key], + on_invalid_property) + if ret: + cleaned[key] = ret + new_key = _convert_key(key, lower, replace_special, snake_case) + if key != new_key: + cleaned[new_key] = cleaned.pop(key) + elif obj_type == "array": + assert(type(obj) is list) + cleaned = list() + for o in obj: + ret = fix_type(o, schema, dict_path + ["items"], + on_invalid_property) + if ret: + cleaned.append(ret) + else: + if obj_type == "string": + cleaned = str(obj) + if obj_format == "date-time": + try: + cleaned = _parse_datetime_tz( + obj, default_tz_offset=0).isoformat() + except Exception as e: + cleaned = _on_invalid_property(on_invalid_property, + dict_path, obj_type, obj, + err_msg=str(e)) + elif obj_type == "number": + try: + cleaned = float(obj) + except ValueError as e: + cleaned = _on_invalid_property( + on_invalid_property, dict_path, obj_type, obj, + err_msg=str(e)) + elif obj_type == "integer": + try: + cleaned = int(obj) + except ValueError as e: + cleaned = _on_invalid_property( + on_invalid_property, dict_path, obj_type, obj, + err_msg=str(e)) + elif obj_type == "boolean": + if str(obj).lower() == "true": + cleaned = True + elif str(obj).lower() == "false": + cleaned = False + else: + cleaned = _on_invalid_property( + on_invalid_property, dict_path, obj_type, obj, + err_msg=(str(obj) + + " is not a valid value for boolean type")) + else: + raise Exception("Invalid type in schema: %s" % obj_type) + return cleaned diff --git a/requirements_dev.txt b/requirements_dev.txt new file mode 100644 index 0000000..287d7fd --- /dev/null +++ b/requirements_dev.txt @@ -0,0 +1,10 @@ +bump2version>=0.5.11 +coverage>=4.5.4 +flake8>=3.7.8 +pip>=19.2.3 +pytest>=5.4.3 +Sphinx>=1.8.5 +tox>=3.14.0 +twine>=1.14.0 +watchdog>=0.9.0 +wheel>=0.33.6 diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..b88034e --- /dev/null +++ b/setup.cfg @@ -0,0 +1,2 @@ +[metadata] +description-file = README.md diff --git a/setup.py b/setup.py new file mode 100755 index 0000000..34b27bb --- /dev/null +++ b/setup.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python +from setuptools import setup + +VERSION = "0.1.0" + +with open("README.md", "r") as fh: + long_description = fh.read() + +setup( + name="getschema", + version=VERSION, + description="Get jsonschema from sample records", + long_description=long_description, + long_description_content_type="text/markdown", + author="Daigo Tanaka, Anelen Co., LLC", + url="https://github.com/daigotanaka/getschema", + + classifiers=[ + "Development Status :: 4 - Beta", + "License :: OSI Approved :: Apache Software License", + + "Operating System :: MacOS :: MacOS X", + "Operating System :: POSIX :: Linux", + + "Programming Language :: Python :: 3.6", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + ], + + install_requires=[ + "setuptools>=40.3.0", + "python-dateutil>=2.8.1", + "simplejson==3.11.1" + ], + entry_points=""" + [console_scripts] + getschema=getschema:main + """, + packages=["getschema"], + package_data={ + # Use MANIFEST.ini + }, + include_package_data=True +) diff --git a/tests/install_test.sh b/tests/install_test.sh new file mode 100755 index 0000000..8ecb716 --- /dev/null +++ b/tests/install_test.sh @@ -0,0 +1,51 @@ +#!/bin/bash + +PACKAGE=getschema +COMMAND=getschema + +PYTHON=/opt/python/3.6/bin/python +if [ ! -e $PYTHON ]; then + PYTHON=`which python3` +fi +echo $PYTHON + +if [ -e ./install_test ]; then + rm -fr install_test +fi + +$PYTHON -m venv install_test +source install_test/bin/activate; +find $PACKAGE -name '__pycache__' | xargs rm -fr; +python setup.py clean --all; +rm -fr dist; +rm -fr build; +rm -fr $PACKAGE.egg-info; +python setup.py install; + +SITE_PKG_DIR="./install_test/lib/python3.6/site-packages" +PKG_DIR=`ls $SITE_PKG_DIR | grep $PACKAGE` + +# tree $SITE_PKG_DIR/$PKG_DIR/$PACKAGE +DIFF=`diff --exclude=__pycache__ -r $SITE_PKG_DIR/$PKG_DIR/$PACKAGE ./$PACKAGE` +if [ -z "$DIFF" ] +then + echo "All file are included in the package."; +else + echo $DIFF + echo "Check MANIFEST.in" + exit 1; +fi + +# Note: Don't insert spaces in the next line +$COMMAND&>install_test/msg +CMD_OUT=`cat install_test/msg | grep "usage: $COMMAND"` +if [ -z "$CMD_OUT" ]; then + cat install_test/msg + echo "$PACKAGE is not properly installed" + exit 1; +else + echo "$PACKAGE command is returning the expected message." +fi + +deactivate +echo "Install test finished successfully"