|
| 1 | +import random |
| 2 | +import dagger |
| 3 | +from dagger import dag, function, object_type |
| 4 | + |
| 5 | + |
| 6 | +@object_type |
| 7 | +class Book: |
| 8 | + |
| 9 | + @function |
| 10 | + def env(self, source: dagger.Directory) -> dagger.Container: |
| 11 | + """Returns a base image""" |
| 12 | + return ( |
| 13 | + dag.container() |
| 14 | + .from_("python:3.11") |
| 15 | + .with_exec(["sh", "-c", "apt-get update && apt-get install -y libpq-dev"]) |
| 16 | + .with_directory("/app", source) |
| 17 | + .with_workdir("/app") |
| 18 | + .with_mounted_cache("/root/.cache/pip", dag.cache_volume("python-pip")) |
| 19 | + .with_exec(["pip", "install", "-r", "requirements.txt"]) |
| 20 | + .with_exposed_port(8000) |
| 21 | + .with_entrypoint(["fastapi", "run", "main.py", "--port", "8000"]) |
| 22 | + ) |
| 23 | + |
| 24 | + @function |
| 25 | + async def test(self, source: dagger.Directory) -> str: |
| 26 | + """Runs tests""" |
| 27 | + postgres = ( |
| 28 | + dag.container() |
| 29 | + .from_("postgres:15-alpine") |
| 30 | + .with_env_variable("POSTGRES_USER", "app_user") |
| 31 | + .with_env_variable("POSTGRES_PASSWORD", "secret") |
| 32 | + .with_file("/docker-entrypoint-initdb.d/init-dbs.sh", source.file("./init-dbs.sh")) |
| 33 | + .with_exposed_port(5432) |
| 34 | + .as_service(args=[], use_entrypoint=True) |
| 35 | + ) |
| 36 | + |
| 37 | + return await ( |
| 38 | + self.env(source) |
| 39 | + .with_service_binding("db", postgres) |
| 40 | + .with_env_variable("DATABASE_URL", "postgresql://app_user:secret@db/app_db") |
| 41 | + .with_env_variable("TEST_DATABASE_URL", "postgresql://app_user:secret@db/app_db_test") |
| 42 | + .with_exec(["pytest"]) |
| 43 | + .stdout() |
| 44 | + ) |
| 45 | + |
| 46 | + @function |
| 47 | + async def publish(self, source: dagger.Directory) -> str: |
| 48 | + """Publishes the image""" |
| 49 | + await self.test(source) |
| 50 | + return await ( |
| 51 | + self.env(source) |
| 52 | + .publish(f"ttl.sh/my-fastapi-app-{random.randrange(10000)}") |
| 53 | + ) |
| 54 | + |
| 55 | + @function |
| 56 | + def container_echo(self, string_arg: str) -> dagger.Container: |
| 57 | + """Returns a container that echoes whatever string argument is provided""" |
| 58 | + return dag.container().from_("alpine:latest").with_exec(["echo", string_arg]) |
| 59 | + |
| 60 | + @function |
| 61 | + async def grep_dir(self, directory_arg: dagger.Directory, pattern: str) -> str: |
| 62 | + """Returns lines that match a pattern in the files of the provided Directory""" |
| 63 | + return await ( |
| 64 | + dag.container() |
| 65 | + .from_("alpine:latest") |
| 66 | + .with_mounted_directory("/mnt", directory_arg) |
| 67 | + .with_workdir("/mnt") |
| 68 | + .with_exec(["grep", "-R", pattern, "."]) |
| 69 | + .stdout() |
| 70 | + ) |
0 commit comments