|
| 1 | +import dagger |
| 2 | +from typing import Annotated |
| 3 | +from dagger import dag, function, object_type, DefaultPath |
| 4 | + |
| 5 | + |
| 6 | +@object_type |
| 7 | +class Book: |
| 8 | + |
| 9 | + source: Annotated[dagger.Directory, DefaultPath(".")] |
| 10 | + |
| 11 | + @function |
| 12 | + def env(self) -> dagger.Container: |
| 13 | + """Returns a Python container with the current source directory mounted and requirements installed""" |
| 14 | + return ( |
| 15 | + dag.container() |
| 16 | + .from_("python:3.11") |
| 17 | + .with_mounted_directory("/app", self.source) |
| 18 | + .with_workdir("/app") |
| 19 | + .with_mounted_cache("/root/.cache/pip", dag.cache_volume("python-pip")) |
| 20 | + .with_exec(["pip", "install", "-r", "requirements.txt"]) |
| 21 | + ) |
| 22 | + |
| 23 | + @function |
| 24 | + async def test(self) -> str: |
| 25 | + """Returns the result of running unit tests using pytest""" |
| 26 | + |
| 27 | + postgresdb = ( |
| 28 | + dag.container() |
| 29 | + .from_("postgres:alpine") |
| 30 | + .with_env_variable("POSTGRES_USER", "app_user") |
| 31 | + .with_env_variable("POSTGRES_DB", "app_test") |
| 32 | + .with_env_variable("POSTGRES_PASSWORD", "secret") |
| 33 | + .with_exposed_port(5432) |
| 34 | + .as_service(args=[], use_entrypoint=True) |
| 35 | + ) |
| 36 | + |
| 37 | + return await ( |
| 38 | + self.env() |
| 39 | + .with_service_binding("db", postgresdb) |
| 40 | + .with_env_variable("DATABASE_URL", "postgresql://app_user:secret@db/app_test") |
| 41 | + .with_exec(["pytest"]) |
| 42 | + .stdout() |
| 43 | + ) |
| 44 | + |
| 45 | + @function |
| 46 | + async def publish(self) -> str: |
| 47 | + """Returns the container address after publishing to ttl.sh""" |
| 48 | + #await self.test() |
| 49 | + ctr = self.env() |
| 50 | + return await ( |
| 51 | + ctr |
| 52 | + .with_exposed_port(8000) |
| 53 | + .with_entrypoint(["fastapi", "run", "main.py"]) |
| 54 | + #.with_registry_auth("docker.io", "my-username", "my-password") |
| 55 | + #.with_registry_auth("ghcr.io", "my-username", "my-password") |
| 56 | + .publish("ttl.sh/fastapi-app-1234") |
| 57 | + ) |
| 58 | + |
| 59 | + |
| 60 | + @function |
| 61 | + def container_echo(self, string_arg: str) -> dagger.Container: |
| 62 | + """Returns a container that echoes whatever string argument is provided""" |
| 63 | + return dag.container().from_("alpine:latest").with_exec(["echo", string_arg]) |
| 64 | + |
| 65 | + @function |
| 66 | + async def grep_dir(self, directory_arg: dagger.Directory, pattern: str) -> str: |
| 67 | + """Returns lines that match a pattern in the files of the provided Directory""" |
| 68 | + return await ( |
| 69 | + dag.container() |
| 70 | + .from_("alpine:latest") |
| 71 | + .with_mounted_directory("/mnt", directory_arg) |
| 72 | + .with_workdir("/mnt") |
| 73 | + .with_exec(["grep", "-R", pattern, "."]) |
| 74 | + .stdout() |
| 75 | + ) |
0 commit comments