Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from ruamel.yaml import YAML
- from schema import Schema, And, Or
- import os
- import re
- import fire
- CONTACTS = "contacts.yml"
- PEOPLE = "people.yml"
- # helper functions
- def load_yaml(yamlfile):
- """load yaml file"""
- yamlloader = YAML()
- with open(yamlfile, "r") as fileobj:
- db = yamlloader.load(fileobj)
- return db
- def is_there(ymlfile):
- """Check if a yaml file is in the current working directory."""
- curr_dir = os.getcwd()
- for item in os.listdir(curr_dir):
- if os.path.isfile(item) and item == ymlfile:
- return ymlfile
- else:
- print(f"There is no {ymlfile} in directory.")
- return None
- # class and functions for checking
- class PesronValidator:
- """A class to validate person."""
- def __init__(self, contactsfile=CONTACTS, peoplefile=PEOPLE):
- self.contactsfile = contactsfile
- self.peoplefile = peoplefile
- self.contacts = load_yaml(contactsfile).keys() if is_there(contactsfile) else None
- self.people = load_yaml(peoplefile).keys() if is_there(peoplefile) else None
- def validate(self, person):
- in_contacts = person in self.contacts if self.contacts else False
- in_people = person in self.people if self.people else False
- if in_contacts or in_people:
- return True
- else:
- print(f"There is no {person} in known contacts or people.")
- return False
- def is_proposal_id(some_id: str):
- """Check if proposal id is valid."""
- if re.match(r"\d\d\d\d\d\d", some_id):
- return True
- else:
- print(f"The proposal id should be 6 digits but this is {id}.")
- return False
- # Options for properties
- MONTHS = ["Jan", "Feb", "Mar", "Apr", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
- STATUS = ["submitted", "in progress", "closed"]
- TITLE_WORD_LIMIT = 500
- VALID_YEAR_RANGE = [1999, 2100]
- # schema for properties
- PROPERTIES = {"id": And(str, is_proposal_id),
- "authors": [And(str, PesronValidator().validate)],
- "day": And(int, lambda x: 0 < x < 32),
- "full": {"narrative": str},
- "instrument": Or(str, None),
- "month": And(Or(str, int), lambda x: x in MONTHS),
- "notes": [str],
- "project": str,
- "status": And(str, lambda x: x in STATUS),
- "title": str,
- "title_short": And(str, lambda x: len(x) < TITLE_WORD_LIMIT),
- "year": And(int, lambda x: VALID_YEAR_RANGE[0] < x < VALID_YEAR_RANGE[1])}
- # the schema template
- SCHEMA = {str: PROPERTIES}
- # main function
- def validate(yamlfile: str, schema=None):
- """Validate yamlfile using a schema. The schema is a python object acceptable for module schema."""
- db = load_yaml(yamlfile)
- if schema:
- pass
- else:
- schema = SCHEMA
- schemaobj = Schema(schema, ignore_extra_keys=True)
- schemaobj.validate(db)
- print(f"{yamlfile} is validated.")
- return
- def main():
- """Make a CLI using fire"""
- fire.Fire(validate)
- return
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement