nut/chipnut/__main__.py
2026-04-04 12:02:15 +02:00

108 lines
2.9 KiB
Python

from .cli import CLI
from .config import ConfigError, load_config
from .commands.setup import is_chipnut_workspace, find_template_conflicts, copy_template_files
from .commands.compiler import compile as compile_project
def help_text():
return [
"%bold%%cyan%chipnut CLI: tiny shell, big squirrel energy :3%reset%",
]
def main() -> int:
cli = CLI(help_callback=help_text)
cli.command(
"init",
help="Create an empty chipnut workspace or reinitialize with --force",
description=(
"Initialize a chipnut development workspace by creating a Nutfile and default project files. "
"If a Nutfile already exists, initialization should fail unless --force is used."
),
).flag(
"force",
"f",
help="Reinitialize even when a Nutfile already exists",
).arg(
"path",
nargs="?",
default=".",
help="Directory to initialize (default: current directory)",
).handle(cmd_init)
cli.command(
"build",
help="Compile the project",
description=(
"Compile the project according to the configuration in the Nutfile. "
),
).option(
"config",
"c",
default="Nutfile",
help="Path to Nutfile (default: ./Nutfile)",
).option(
"build-folder",
"o",
default=None,
help="Override output build folder from config",
).option(
"name",
"n",
default=None,
help="Override output file name from config",
).handle(cmd_build)
return cli.run()
def cmd_build(args, flags) -> int:
config_path = flags["config"]
build_folder_override = flags["build_folder"]
file_name_override = flags["name"]
if config_path == "Nutfile" and not is_chipnut_workspace():
print("Error: No Nutfile found. Please run 'chipnut init' to create a workspace.")
return 1
try:
config = load_config(config_path)
except FileNotFoundError:
print(f"Error: Config file not found: {config_path}")
return 1
except ConfigError as error:
print(f"Error: Invalid Nutfile: {error}")
return 1
try:
compile_project(
config,
build_folder=build_folder_override,
file_name=file_name_override,
)
except (RuntimeError, OSError) as error:
print(f"Error: Build failed: {error}")
return 1
return 0
def cmd_init(args, flags) -> int:
dest_dir = args[0]
force = flags["force"]
conflicts = find_template_conflicts(dest_dir)
if conflicts and not force:
print("Some files already exist that would be overwritten:")
for file in conflicts:
print(f" {file}")
print("Use --force to overwrite existing files.")
return 1
copy_template_files(dest_dir, force=force, checked=True)
return 0
if __name__ == "__main__":
raise SystemExit(main())