Commit 0500ef00 authored by Luke Mewburn's avatar Luke Mewburn
Browse files

reformat all python with "ruff format"

No functional change
parent 8f9a9458
Loading
Loading
Loading
Loading
+26 −10
Changes for 103705/validate.py: 26 added lines, 10 removed lines.
Original line number Diff line number Diff line
@@ -6,7 +6,6 @@ import logging
import argparse



# filename = sys.argv[1]

# def load_json (path):
@@ -38,20 +37,39 @@ import argparse
# validate(json_instance, ext_schema)
# print ("OK")


def handle_uri(u):
    print(u)


def load_json(path: str):
    with open(path) as f:
        return json.load(f)


if __name__ == "__main__":
    parser = argparse.ArgumentParser()

    parser.add_argument('-s','--schemadir', action="append", help="Directory containing supporting schema files to use for validation")
    parser.add_argument('-v', '--verbose', action="count", help="Verbose logging (can be specified multiple times)")
    parser.add_argument('-i', '--input', type=argparse.FileType('r'), default=sys.stdin, help="Path to input file (if absent, stdin is used)")    
    parser.add_argument('schema', help="Primary schema to validate against")    
    parser.add_argument(
        "-s",
        "--schemadir",
        action="append",
        help="Directory containing supporting schema files to use for validation",
    )
    parser.add_argument(
        "-v",
        "--verbose",
        action="count",
        help="Verbose logging (can be specified multiple times)",
    )
    parser.add_argument(
        "-i",
        "--input",
        type=argparse.FileType("r"),
        default=sys.stdin,
        help="Path to input file (if absent, stdin is used)",
    )
    parser.add_argument("schema", help="Primary schema to validate against")

    args = parser.parse_args()

@@ -68,7 +86,7 @@ if __name__ == "__main__":
    instance_doc = json.loads(args.input.read())
    args.input.close()
    main_schema = load_json(args.schema)
    schema_dict = { main_schema['$id'] : main_schema }
    schema_dict = {main_schema["$id"]: main_schema}

    if args.schemadir:
        schema_paths = []
@@ -77,16 +95,14 @@ if __name__ == "__main__":
        logging.info(f"Schema files loaded: {schema_paths}")

        schemas_json = [json.load(p.open()) for p in schema_paths]
        schema_dict = schema_dict | { s['$id'] : s for s in schemas_json }
        schema_dict = schema_dict | {s["$id"]: s for s in schemas_json}

    logging.info(f"Schema IDs loaded: {[k for k in schema_dict.keys()]}")

    logging.debug(f"Instance doc: {instance_doc}")
    logging.debug(f"Main schema: {main_schema}")

    resolver = RefResolver(None, 
                           referrer=None, 
                           store=schema_dict)
    resolver = RefResolver(None, referrer=None, store=schema_dict)

    v = Draft202012Validator(main_schema, resolver=resolver)

+47 −22
Changes for 103705/validation/validate_705.py: 47 added lines, 22 removed lines.
Original line number Diff line number Diff line
@@ -5,9 +5,11 @@ from pathlib import Path
import logging
import argparse


def handle_uri(u):
    print(u)


def load_json(path: str):
    with open(path) as f:
        return json.load(f)
@@ -16,9 +18,25 @@ def load_json(path : str):
if __name__ == "__main__":
    parser = argparse.ArgumentParser()

    parser.add_argument('-s','--schemadir', action="append", help="Directory containing supporting schema files to use for validation")
    parser.add_argument('-v', '--verbose', action="count", help="Verbose logging (can be specified multiple times)")
    parser.add_argument('-i', '--input', type=argparse.FileType('r'), default=sys.stdin, help="Path to input file (if absent, stdin is used)")
    parser.add_argument(
        "-s",
        "--schemadir",
        action="append",
        help="Directory containing supporting schema files to use for validation",
    )
    parser.add_argument(
        "-v",
        "--verbose",
        action="count",
        help="Verbose logging (can be specified multiple times)",
    )
    parser.add_argument(
        "-i",
        "--input",
        type=argparse.FileType("r"),
        default=sys.stdin,
        help="Path to input file (if absent, stdin is used)",
    )

    args = parser.parse_args()

@@ -36,19 +54,19 @@ if __name__ == "__main__":
    args.input.close()

    config = {
        'schema_include_dirs' : [
            '../schema/',
            '../../103280/',
        "schema_include_dirs": [
            "../schema/",
            "../../103280/",
        ],
        'main_schema_doc' : '../schema/response.schema.json'
        "main_schema_doc": "../schema/response.schema.json",
    }

    rootPath = Path(sys.argv[0]).parent
    main_schema = load_json(str(rootPath / config['main_schema_doc']))
    schema_dict = { main_schema['$id'] : main_schema }
    main_schema = load_json(str(rootPath / config["main_schema_doc"]))
    schema_dict = {main_schema["$id"]: main_schema}

    schema_paths = []
    for d in config['schema_include_dirs']:
    for d in config["schema_include_dirs"]:
        schema_paths += [f for f in (rootPath / Path(d)).rglob("*.schema.json")]
    logging.info(f"Core schema files loaded: {schema_paths}")
    if args.schemadir:
@@ -58,38 +76,45 @@ if __name__ == "__main__":
    else:
        logging.info(f"No CSP schema files loaded")
    schemas_json = [json.load(p.open()) for p in schema_paths]
    schema_dict = schema_dict | { s['$id'] : s for s in schemas_json }
    schema_dict = schema_dict | {s["$id"]: s for s in schemas_json}

    logging.info(f"Schema IDs loaded: {[k for k in schema_dict.keys()]}")

    logging.debug(f"Instance doc: {instance_doc}")
    logging.debug(f"Main schema: {main_schema}")

    resolver = RefResolver(None, 
                           referrer=None, 
                           store=schema_dict)
    resolver = RefResolver(None, referrer=None, store=schema_dict)

    logging.info("Performing ETSI validation")
    v = Draft202012Validator(main_schema, resolver=resolver)
    v.validate(instance_doc)

    logging.info("Building record type dictionary")
    type_dict = instance_doc['recordSetDescription']['recordTypes']
    type_dict = instance_doc["recordSetDescription"]["recordTypes"]
    logging.debug(type_dict)
    ref_dict = {k: {"$ref": v} for k, v in type_dict.items()}
    validator_dict = { k : Draft202012Validator(ref_dict[k], resolver=resolver) for k,v in ref_dict.items()}
    validator_dict = {
        k: Draft202012Validator(ref_dict[k], resolver=resolver)
        for k, v in ref_dict.items()
    }
    logging.debug(ref_dict)

    logging.info("Validating records")
    for r in instance_doc['recordSet']:
        type_key = r['type']
    for r in instance_doc["recordSet"]:
        type_key = r["type"]
        if type_key not in type_dict.keys():
            logging.error(f"Record {r['id']} has type {type_key}, not in recordType dict")
            logging.error(
                f"Record {r['id']} has type {type_key}, not in recordType dict"
            )
        type_ref = type_dict[type_key]
        type_schema_id = type_ref.split('#')[0]
        logging.info(f"Using {type_schema_id} to validate {type_ref} in record {r['id']}")
        type_schema_id = type_ref.split("#")[0]
        logging.info(
            f"Using {type_schema_id} to validate {type_ref} in record {r['id']}"
        )
        if not (type_key in validator_dict.keys()):
            logging.error(f'Type key {type_key} from type {type_ref} in record {r["id"]} not in validator dictionary')
            logging.error(
                f"Type key {type_key} from type {type_ref} in record {r['id']} not in validator dictionary"
            )
            print(ref_dict)
        v = validator_dict[type_key]
        v.validate(r)
+9 −14
Changes for 103707/testing/validate_examples.py: 9 added lines, 14 removed lines.
Original line number Diff line number Diff line
@@ -3,39 +3,34 @@ import sys
from pathlib import Path
from pprint import pprint

if __name__ == '__main__':

if __name__ == "__main__":
    if sys.version_info <= (3, 5):
        sys.exit('ERROR: You need at least Python 3.5 to run this tool')
        sys.exit("ERROR: You need at least Python 3.5 to run this tool")

    try:
        from lxml import etree
    except ImportError:
        sys.exit('ERROR: You need to install the Python lxml library')
        sys.exit("ERROR: You need to install the Python lxml library")

    try:
        import xmlschema
    except ImportError:
        sys.exit('ERROR: You need to install the xml schema library')

        sys.exit("ERROR: You need to install the xml schema library")

    extraSchemas = [
        'examples/FooServiceSchema.xsd',
        'TS_103_280_v020301.xsd'
    ]
    extraSchemas = ["examples/FooServiceSchema.xsd", "TS_103_280_v020301.xsd"]

    locations = []
    for schemaFile in extraSchemas:
        xs = xmlschema.XMLSchema(schemaFile, validation='skip')
        xs = xmlschema.XMLSchema(schemaFile, validation="skip")
        locations.append((xs.default_namespace, str(Path(schemaFile))))

    coreSchema = xmlschema.XMLSchema('TS_103_707_v010201.xsd', locations=locations)
    coreSchema = xmlschema.XMLSchema("TS_103_707_v010201.xsd", locations=locations)

    for schema in extraSchemas:
        newSchema = xmlschema.XMLSchema(schema)
        coreSchema.import_schema(newSchema.default_namespace, schema)

    examples = glob.glob('examples/*.xml')
    examples = glob.glob("examples/*.xml")
    for example in examples:
        try:
            coreSchema.validate(example)
@@ -43,4 +38,4 @@ if __name__ == '__main__':
        except Exception as ex:
            print("{0} failed validation: {1}".format(example, ex))

    print ('Done')
 No newline at end of file
    print("Done")
+23 −22
Changes for utils/close_meeting.py: 23 added lines, 22 removed lines.
Original line number Diff line number Diff line
@@ -7,9 +7,11 @@ from forgelib.scrapers.etsi import getSpecHistory

console = Console()


def rprint(s: str):
    console.print(s)


root_url = "https://forge.etsi.org/rep/"
project_number = 586

@@ -17,44 +19,43 @@ project_number = 586
with console.status("Retrieving most recent merge request"):
    gl = gitlab.Gitlab(url=root_url)
    project = gl.projects.get(project_number)
    mr_list = project.mergerequests.list(target_branch = 'main', get_all = True)
    mr_list = [mr for mr in mr_list if mr.source_branch.startswith('meeting')]
    mr_list = project.mergerequests.list(target_branch="main", get_all=True)
    mr_list = [mr for mr in mr_list if mr.source_branch.startswith("meeting")]
    mr = mr_list[0]

meeting_name = mr.source_branch.split('/')[-1]
rprint(f"Most recent meeting branch is [yellow]{mr.source_branch}[/], MR !{mr.iid} ('{mr.title}')")
meeting_name = mr.source_branch.split("/")[-1]
rprint(
    f"Most recent meeting branch is [yellow]{mr.source_branch}[/], MR !{mr.iid} ('{mr.title}')"
)

mr_dict = {}

with console.status(f"Retrieving MR/CRs considered at [yellow]{meeting_name}[/]"):
    mr_list = project.mergerequests.list(target_branch=mr.source_branch, get_all=True)
    mr_list = [mr for mr in mr_list if mr.source_branch.startswith('cr')]
    
    mr_list = [mr for mr in mr_list if mr.source_branch.startswith("cr")]

    for mr in mr_list:
        spec = mr.source_branch.split('/')[1]
        cr = mr.source_branch.split('/')[2]
        spec = mr.source_branch.split("/")[1]
        cr = mr.source_branch.split("/")[2]
        if not (spec in mr_dict.keys()):
            mr_dict[spec] = []
        mr_dict[spec].append(mr)

for spec, mr_list in mr_dict.items():
    table = Table(show_header=False)
    table.add_column('MR', style="bright_blue")
    table.add_column('branch', style="yellow")
    table.add_column('CR', style="bright_cyan")
    table.add_column('title')
    table.add_column('status')
    table.add_column("MR", style="bright_blue")
    table.add_column("branch", style="yellow")
    table.add_column("CR", style="bright_cyan")
    table.add_column("title")
    table.add_column("status")

    for mr in mr_list:
        table.add_row(str(mr.iid), mr.source_branch, mr.source_branch.split('/')[2], mr.title, mr.state)
        table.add_row(
            str(mr.iid),
            mr.source_branch,
            mr.source_branch.split("/")[2],
            mr.title,
            mr.state,
        )
    rprint(f"\nChanges to [bright_green]TS {spec[0:3]} {spec[3:]}[/]")
    console.print(table)







+19 −15
Changes for utils/generate_change_notes.py: 19 added lines, 15 removed lines.
Original line number Diff line number Diff line
@@ -13,8 +13,8 @@ project = gl.projects.get(project_number)

out_str = ""

tags = project.tags.list(search = f"spec/{spec.replace(" ","")}", get_all = True)
tags.sort(key = lambda x: x.commit['created_at'])
tags = project.tags.list(search=f"spec/{spec.replace(' ', '')}", get_all=True)
tags.sort(key=lambda x: x.commit["created_at"])
tags.reverse()

print("Getting spec history from portal (could take a few moments)...")
@@ -22,15 +22,19 @@ spec_history = getSpecHistory(f"TS {spec}")

for tag in tags:
    print(tag.name)
    version = tag.name.split('/')[2]
    version = tag.name.split("/")[2]
    spec_version = next((x for x in spec_history if x.version == version), None)
    out_str += "\n\n"
    out_str += f"# TS {spec} v{tag.name.split('/')[2]}\n"
    out_str += f"{tag.message}, tagged as [{tag.name}]({root_url}li/schemas-definitions/-/tree/{tag.name}/{spec.replace(" ","")}?ref_type=tags)"
    if spec_version is not None and spec_version.pdfLink is not None and spec_version.pdfLink != "":
        out_str += f" and available [from the ETSI portal as a PDF]({spec_version.pdfLink.replace("\\","/")})\n"
    out_str += f"{tag.message}, tagged as [{tag.name}]({root_url}li/schemas-definitions/-/tree/{tag.name}/{spec.replace(' ', '')}?ref_type=tags)"
    if (
        spec_version is not None
        and spec_version.pdfLink is not None
        and spec_version.pdfLink != ""
    ):
        out_str += f" and available [from the ETSI portal as a PDF]({spec_version.pdfLink.replace('\\', '/')})\n"
    out_str += ".  \n  \n"
    commit = project.commits.get(tag.commit['id'])
    commit = project.commits.get(tag.commit["id"])
    mrs = commit.merge_requests()
    if len(mrs) == 0:
        out_str += "No CR information in the Forge.\n"
@@ -40,7 +44,7 @@ for tag in tags:
        print(f"Multiple MRs for {tag.name}...")
        for mr in mrs:
            print(f"  {mr['iid']} {mr['source_branch']} : {mr['title']}")
        mrs = [mr for mr in mrs if mr['source_branch'].startswith("meeting")]
        mrs = [mr for mr in mrs if mr["source_branch"].startswith("meeting")]
        if len(mrs) > 1:
            print("Couldn't work out which MR to use")
            exit(-1)
@@ -51,15 +55,15 @@ for tag in tags:
    mr = mrs[0]

    out_str += f"Includes the following CRs with Forge changes:\n"
    crs = project.mergerequests.list(target_branch = mr['source_branch'], state="merged", get_all = True)
    crs = [cr for cr in crs if cr.source_branch.startswith(f"cr/{spec.replace(" ","")}")]
    crs = project.mergerequests.list(
        target_branch=mr["source_branch"], state="merged", get_all=True
    )
    crs = [
        cr for cr in crs if cr.source_branch.startswith(f"cr/{spec.replace(' ', '')}")
    ]
    for cr in crs:
        out_str += f"* {cr.title} ([MR {cr.iid}]({cr.web_url})).\n"
    out_str += "\n  \nFor all changes, including non-Forge changes, see the change history in the published specification.  \n"

out_file = Path(f"{spec.replace(" ","")}/README.md")
out_file = Path(f"{spec.replace(' ', '')}/README.md")
out_file.write_text(out_str, "utf8")



Loading