|
| 1 | +# Copyright (c) NiceBots |
| 2 | +# SPDX-License-Identifier: MIT |
| 3 | + |
| 4 | +import argparse |
| 5 | +import sys |
| 6 | +from datetime import UTC, datetime |
| 7 | +from pathlib import Path |
| 8 | + |
| 9 | +from .convert import env_to_yaml, yaml_to_env |
| 10 | + |
| 11 | + |
| 12 | +def main() -> None: # noqa: PLR0912 |
| 13 | + parser = argparse.ArgumentParser(description="Convert config between YAML and env formats.") |
| 14 | + parser.add_argument("-i", "--input", help="Input file path", default=None) |
| 15 | + parser.add_argument("--input-format", help="Input format (yaml, yml, env)", default=None) |
| 16 | + parser.add_argument("--output", help="Output file path", default=None) |
| 17 | + parser.add_argument("--output-format", help="Output format (yaml, yml, env)", default=None) |
| 18 | + parser.add_argument("--terminal", action="store_true", help="Output to terminal instead of file") |
| 19 | + |
| 20 | + args = parser.parse_args() |
| 21 | + |
| 22 | + input_path = Path(args.input) if args.input else None |
| 23 | + output_path = Path(args.output) if args.output else None |
| 24 | + input_format = args.input_format |
| 25 | + output_format = args.output_format |
| 26 | + terminal = args.terminal |
| 27 | + |
| 28 | + if not input_path: |
| 29 | + if Path("config.yaml").exists(): |
| 30 | + input_path = Path("config.yaml") |
| 31 | + elif Path("config.yml").exists(): |
| 32 | + input_path = Path("config.yml") |
| 33 | + elif Path(".env").exists(): |
| 34 | + input_path = Path(".env") |
| 35 | + else: |
| 36 | + print("No input file found.") |
| 37 | + sys.exit(1) |
| 38 | + |
| 39 | + input_format = input_format or input_path.suffix[1:] if input_path.name != ".env" else "env" |
| 40 | + |
| 41 | + if not output_format: |
| 42 | + output_format = "env" if input_format in ["yaml", "yml"] else "yaml" |
| 43 | + |
| 44 | + if terminal: |
| 45 | + output_path = None |
| 46 | + elif not output_path: |
| 47 | + if output_format == "env": |
| 48 | + output_path = Path(".env") |
| 49 | + if output_path.exists() and output_path.stat().st_size != 0: |
| 50 | + response = input(".env file is not empty. Overwrite? (y/n): ") |
| 51 | + if response.lower() != "y": |
| 52 | + output_path = Path(f"{datetime.now(tz=UTC).strftime('%Y%m%d%H%M%S')}.converted.env") |
| 53 | + else: |
| 54 | + output_path = Path("config.yaml") |
| 55 | + |
| 56 | + # Fixed conversion logic |
| 57 | + if input_format in ["yaml", "yml"] and output_format == "env": |
| 58 | + yaml_to_env(input_path, output_path) |
| 59 | + elif input_format == "env" and output_format in ["yaml", "yml"]: |
| 60 | + env_to_yaml(input_path, output_path) |
| 61 | + else: |
| 62 | + print(f"Invalid conversion from '{input_format}' to '{output_format}'") |
| 63 | + print("Supported conversions: yaml->env, yml->env, env->yaml, env->yml") |
| 64 | + sys.exit(1) |
| 65 | + |
| 66 | + |
| 67 | +if __name__ == "__main__": |
| 68 | + main() |
0 commit comments