|
| 1 | +# ----------------------------------------------------------------------------- |
| 2 | +# Copyright (C) 2025-2025 The python-ndn authors |
| 3 | +# |
| 4 | +# This file is part of python-ndn. |
| 5 | +# |
| 6 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | +# you may not use this file except in compliance with the License. |
| 8 | +# You may obtain a copy of the License at |
| 9 | +# |
| 10 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | +# |
| 12 | +# Unless required by applicable law or agreed to in writing, software |
| 13 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | +# See the License for the specific language governing permissions and |
| 16 | +# limitations under the License. |
| 17 | +# ----------------------------------------------------------------------------- |
| 18 | +import argparse |
| 19 | +import os |
| 20 | +import sys |
| 21 | + |
| 22 | +import lark |
| 23 | +from ndn.app_support.light_versec import compile_lvs, SemanticError |
| 24 | +from ndn.app_support.light_versec.binary import * |
| 25 | + |
| 26 | + |
| 27 | +def add_parser(subparsers): |
| 28 | + parser = subparsers.add_parser("Compile-Lvs", aliases=["compile-lvs"]) |
| 29 | + parser.add_argument( |
| 30 | + "-o", |
| 31 | + "--output", |
| 32 | + metavar="FILE", |
| 33 | + default="-", |
| 34 | + help="Write compiled result into a file", |
| 35 | + ) |
| 36 | + parser.add_argument( |
| 37 | + "input_file", |
| 38 | + metavar="FILE", |
| 39 | + nargs="?", |
| 40 | + default="-", |
| 41 | + help="file containing the content of the LVS text, '-' for stdin (default)", |
| 42 | + ) |
| 43 | + parser.set_defaults(executor=execute) |
| 44 | + |
| 45 | + |
| 46 | +def execute(args: argparse.Namespace): |
| 47 | + try: |
| 48 | + if args.input_file == "-": |
| 49 | + text = sys.stdin.read() |
| 50 | + else: |
| 51 | + with open(os.path.expandvars(args.input_file), "r") as f: |
| 52 | + text = f.read() |
| 53 | + except (ValueError, OSError, IndexError): |
| 54 | + print("Unable to read the input file") |
| 55 | + return -1 |
| 56 | + |
| 57 | + try: |
| 58 | + lvs_model = compile_lvs(text) |
| 59 | + except (SemanticError, lark.UnexpectedInput) as e: |
| 60 | + print("Unable to compile the LVS text input:", e) |
| 61 | + return -2 |
| 62 | + |
| 63 | + encoded_output = bytes(lvs_model.encode()) |
| 64 | + |
| 65 | + if args.output: |
| 66 | + if args.output == "-": |
| 67 | + sys.stdout.buffer.write(encoded_output) |
| 68 | + else: |
| 69 | + with open(os.path.expandvars(args.output), "wb") as f: |
| 70 | + f.write(encoded_output) |
0 commit comments