|
| 1 | +"""A command-line interface for the 'foamlib' package.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import asyncio |
| 6 | +import sys |
| 7 | +from pathlib import Path |
| 8 | + |
| 9 | +import typer |
| 10 | + |
| 11 | +if sys.version_info >= (3, 9): |
| 12 | + from typing import Annotated |
| 13 | +else: |
| 14 | + from typing_extensions import Annotated |
| 15 | + |
| 16 | +from . import AsyncFoamCase, AsyncSlurmFoamCase, __version__ |
| 17 | +from ._util import async_to_sync |
| 18 | + |
| 19 | +app = typer.Typer(help=__doc__) |
| 20 | + |
| 21 | + |
| 22 | +@app.command() |
| 23 | +@async_to_sync |
| 24 | +async def run( |
| 25 | + cases: Annotated[ |
| 26 | + list[Path] | None, |
| 27 | + typer.Argument(help="Case directories", show_default="."), |
| 28 | + ] = None, |
| 29 | + slurm: Annotated[ |
| 30 | + bool | None, |
| 31 | + typer.Option( |
| 32 | + help="Use Slurm for running cases.", show_default="use Slurm if available" |
| 33 | + ), |
| 34 | + ] = None, |
| 35 | + max_cpus: Annotated[ |
| 36 | + int, |
| 37 | + typer.Option( |
| 38 | + help="Maximum number of concurrent processes (for non-Slurm runs).", |
| 39 | + ), |
| 40 | + ] = AsyncFoamCase.max_cpus, |
| 41 | +) -> None: |
| 42 | + """Run one or more OpenFOAM cases.""" |
| 43 | + if cases is None: |
| 44 | + cases = [Path.cwd()] |
| 45 | + |
| 46 | + AsyncFoamCase.max_cpus = max_cpus |
| 47 | + |
| 48 | + if slurm is None: |
| 49 | + await asyncio.gather( |
| 50 | + *(AsyncSlurmFoamCase(case).run(fallback=True) for case in cases) |
| 51 | + ) |
| 52 | + elif slurm: |
| 53 | + await asyncio.gather(*(AsyncSlurmFoamCase(case).run() for case in cases)) |
| 54 | + else: |
| 55 | + await asyncio.gather(*(AsyncFoamCase(case).run() for case in cases)) |
| 56 | + |
| 57 | + |
| 58 | +@app.command() |
| 59 | +@async_to_sync |
| 60 | +async def clean( |
| 61 | + cases: Annotated[ |
| 62 | + list[Path] | None, |
| 63 | + typer.Argument(help="Case directories", show_default="."), |
| 64 | + ], |
| 65 | +) -> None: |
| 66 | + """Clean one or more OpenFOAM cases.""" |
| 67 | + if cases is None: |
| 68 | + cases = [Path.cwd()] |
| 69 | + |
| 70 | + await asyncio.gather(*(AsyncFoamCase(case).clean() for case in cases)) |
| 71 | + |
| 72 | + |
| 73 | +def _version_callback(*, show: bool) -> None: |
| 74 | + if show: |
| 75 | + typer.echo(f"foamlib {__version__}") |
| 76 | + raise typer.Exit |
| 77 | + |
| 78 | + |
| 79 | +@app.callback() |
| 80 | +def common( # noqa: D103 |
| 81 | + *, |
| 82 | + version: Annotated[ |
| 83 | + bool, |
| 84 | + typer.Option( |
| 85 | + "--version", help="Show version and exit.", callback=_version_callback |
| 86 | + ), |
| 87 | + ] = False, |
| 88 | +) -> None: |
| 89 | + pass |
| 90 | + |
| 91 | + |
| 92 | +if __name__ == "__main__": |
| 93 | + app() |
0 commit comments