def main( input_file: typer.FileText = typer.Option(..., "--input", "-i"), output_dir: Path = typer.Option(..., "--output", "-o"), model_file: str = typer.Option(None, "--model-file", "-m"), template_dir: Optional[Path] = typer.Option(None, "--template-dir", "-t"), enum_field_as_literal: Optional[LiteralType] = typer.Option( None, "--enum-field-as-literal" ), ) -> None: input_name: str = input_file.name input_text: str = input_file.read() if model_file: model_path = Path(model_file).with_suffix('.py') else: model_path = MODEL_PATH if enum_field_as_literal: return generate_code( input_name, input_text, output_dir, template_dir, model_path, enum_field_as_literal, ) return generate_code(input_name, input_text, output_dir, template_dir, model_path)
def compile(input_file: typer.FileText = typer.Argument(..., help='Cool file'), output_file: typer.FileTextWrite = typer.Argument( 'a.mips', help='Mips file'), verbose: bool = typer.Option(False, help='Run in verbose mode.')): # In case of encoding conflict if input_file.encoding.lower != 'utf-8': input_file = open(input_file.name, encoding='utf-8') program = input_file.read() tokens, lexer = tokenize(program, verbose) if lexer is None or lexer.contain_errors: exit(1) if not tokens[:-1]: # there is always at least the EOF token log_error('(0, 0) - SyntacticError: ERROR at or near EOF') exit(1) ast, parser = parse(tokens, verbose) # parsing process failed if ast is None: exit(1) PositionAssigner(tokens).visit(ast) ast, _, _, errors = check_semantics(ast, Scope(), Context(), []) if errors or parser.contains_errors: for e in errors: log_error(e) exit(1) exit(0)
def main( input_file: typer.FileText = typer.Option(..., "--input", "-i"), output_dir: Path = typer.Option(..., "--output", "-o"), template_dir: Optional[Path] = typer.Option(None, "--template-dir", "-t"), ) -> None: input_name: str = input_file.name input_text: str = input_file.read() return generate_code(input_name, input_text, output_dir, template_dir)
def add_job_html( file: FileText = Argument(..., help="HTML-file 📄 to create a PDF from."), token: str = Argument(..., envvar="PAPERO_API_TOKEN"), ): """ Add a new job to Papero from HTML-file. """ html = file.read() echo("Converting PDF to HTML") echo(handle_post_job(token, html, "html").result())
def add_job_template( template: str = Argument(..., help="Template to create a PDF from."), file: FileText = Argument( ..., help="JSON-file with data for template create."), token: str = Argument(..., envvar="PAPERO_API_TOKEN"), ): """ Add a new job to Papero from HTML-file. """ data = json.loads(file.read()) echo("Creating PDF from template with given data.") echo(handle_post_template_jobs(token, template, [data]).result()[0])
def _import( data: typer.FileText = typer.Argument(...), overwrite: bool = typer.Option( False, "--overwrite", "-w", help="Перезаписать объекты, если есть такой PK"), tables: List[models.TABLES_ENUM] = typer.Option( None, "--tables", "-t", help="Список таблиц в которые сделать записи", case_sensitive=False), ): """ Импорт материалов в базу Структура: {"table": {"column": value, "index": None} }\n index None == Создание новой записи / не None == замена текущей """ _source = orjson.loads(data.read()) with session_scope() as session: for table, raws in _source.items(): if tables and table not in tables: # Пропустить таблицу, если список таблиц регулируется аргументами и этой таблицы там нет continue _object = getattr(models, table) assert _object, f"Таблицы {table} не существует" for _r in raws: _id = _r.pop("id", None) # Добавить проверку существования ID в базе # -> Если такой элемент уже есть, делать обновление _data = _object.model(exclude=["id"]).parse_obj(_r) one = session.query(_object).filter_by(id=_id).one_or_none() if one: if not overwrite: print(f"Объект {table}{_r} не записан") continue session.query(_object).filter(_object.id == _id).update( _data.dict()) session.query(_object).filter(_object.id == _id).update( _data.dict()) else: session.add(_object(**_data.dict()))
def get_input_data(input_file: typer.FileText, input_string: str) -> str: if input_file is not None: if input_string is not None: show_warning( "Warning: The input string is ignored since input file is specified." ) return input_file.read() if input_string is not None: return input_string show_error("Error: Either a string or a file is required as input.") show_info("See help (--help) for more info.") raise typer.Exit(code=1)
def start_server( loader_script: typer.FileText = typer.Option( None, "--loader-script", "-l", help="python script to register models in the API", ), data_dir: Path = typer.Option( None, "--data-dir", "-d", exists=True, help="default directory to look for model's data", ), host: str = typer.Option("localhost", "--host", "-h", help="host address"), port: int = typer.Option(8000, "--port", "-p", min=1, max=65535, help="port"), ): """Start the API server""" if data_dir is not None: if not data_dir.is_dir(): raise typer.BadParameter( "'--data-dir' / '-d' must be a directory.") path = server.models.set_default_data_dir(data_dir) log(f"default model's data directory set to {path}") if loader_script is None: typer.echo("No model to register. Use -l to register models") else: script = loader_script.read() try: exec(script) except Exception as e: typer.echo( f"Failed running loader script '{loader_script.name}': {e}") raise typer.Exit(code=1) # print registered models models = server.models.get_all_model_def() registered_models = ", ".join( [model["model_name"] for model in models]) typer.echo(f"Registered models: {registered_models}") # start serving the API typer.echo("Starting the server now...") server.start(host=host, port=port)
def main( input_file: typer.FileText = typer.Option(..., "--input", "-i"), # type: ignore output_dir: Path = typer.Option(..., "--output", "-o"), # type: ignore template_dir: Optional[Path] = typer.Option(None, "--template-dir", "-t"), # type: ignore ) -> None: input_name: str = input_file.name input_text: str = input_file.read() if not output_dir.exists(): output_dir.mkdir(parents=True) if not template_dir: template_dir = BUILTIN_TEMPLATE_DIR parser = OpenAPIParser(input_name, input_text) parsed_object: ParsedObject = parser.parse() environment: Environment = Environment(loader=FileSystemLoader( template_dir if template_dir else f"{Path(__file__).parent}/template", encoding="utf8", ), ) results: Dict[Path, str] = {} for target in template_dir.rglob("*"): relative_path = target.relative_to(template_dir.absolute()) result = environment.get_template(str(relative_path)).render( operations=parsed_object.operations, imports=parsed_object.imports) results[relative_path] = format_code(result, PythonVersion.PY_38) timestamp = datetime.now(timezone.utc).replace(microsecond=0).isoformat() header = f"""\ # generated by fastapi-codegen: # filename: {Path(input_file.name).name} # timestamp: {timestamp}""" for path, code in results.items(): with output_dir.joinpath(path.with_suffix(".py")).open("wt") as file: print(header, file=file) print("", file=file) print(code.rstrip(), file=file) generate_models( input_name=input_name, input_text=input_text, input_file_type=InputFileType.OpenAPI, output=output_dir.joinpath("models.py"), target_python_version=PythonVersion.PY_38, )
def daemon(conf: typer.FileText = typer.Option(CONFIG_FILE, '--conf', '-c', help='The configuration file.')): """ Start conflict watching daemon. """ with conf: content = conf.read() try: load_conf(toml.loads(content)) except (toml.TomlDecodeError, ValidationError): typer.echo('Error: Invalid configuration file.', err=True) typer.echo('Please check it first.', err=True) raise typer.Abort() from conflict.config import config from conflict.core.live import Worker coros = [] for watcher in config.watchers: worker = Worker(watcher) coros.append(worker.run()) loop = asyncio.get_event_loop() typer.echo('Starting conflict daemon...') loop.run_until_complete(asyncio.gather(*coros))
def check(file: typer.FileText = typer.Argument( CONFIG_FILE, help='The configuration file to check.')): """ Check if the given configuration file is valid. """ with file: content = file.read() try: config = toml.loads(content) Config(**config) except toml.TomlDecodeError as e: typer.echo('', err=True) typer.echo(' ' * 2 + str(e), err=True) typer.echo('', err=True) typer.echo('Invalid TOML file format.', err=True) raise typer.Abort() except ValidationError as e: typer.echo('', err=True) typer.echo(str(e), err=True) typer.echo('', err=True) typer.echo('Invalid configuration file.', err=True) raise typer.Abort()
def load(file: typer.FileText = typer.Argument( ..., help='The new configuration file to load.')): """ Load new configuration file. """ with file: content = file.read() try: config = toml.loads(content) Config(**config) except toml.TomlDecodeError as e: typer.echo('', err=True) typer.echo(' ' * 2 + str(e), err=True) typer.echo('', err=True) typer.echo('Invalid TOML file format.', err=True) raise typer.Abort() except ValidationError as e: typer.echo('', err=True) typer.echo(str(e), err=True) typer.echo('', err=True) typer.echo('Invalid configuration file.', err=True) raise typer.Abort() with CONFIG_FILE.open(mode='w') as f: f.write(content)
def main(config: typer.FileText = typer.Option(..., mode="a")): config.write("This is a single line\n") print("Config line written")
def main() -> None: p = Path("/Users/fabian/bare-repos/numpy.git") with open("commits copy.txt", "rb") as f: c = FileText(f) analyze(p, [AvailableMetrics["filecount"]], c)