Skip to content

Commit

Permalink
adds mkdag
Browse files Browse the repository at this point in the history
  • Loading branch information
bwalsh committed Feb 1, 2025
1 parent ee72101 commit 4cf6296
Show file tree
Hide file tree
Showing 28 changed files with 938 additions and 0 deletions.
30 changes: 30 additions & 0 deletions mkdag/.github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
name: CI

on: [push, pull_request]

jobs:
build:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v2

- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: '3.12'

- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install setuptools wheel black mypy pytest pytest-cov
pip install .
- name: Run Black
run: black --check --verbose mkdag/ tests/

- name: Run Mypy
run: mypy --ignore-missing-imports mkdag/ tests/

- name: Run Pytest
run: pytest
164 changes: 164 additions & 0 deletions mkdag/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
.pdm.toml
.pdm-python
.pdm-build/

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
.idea/
attic/
1 change: 1 addition & 0 deletions mkdag/mkdag/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

70 changes: 70 additions & 0 deletions mkdag/mkdag/cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import subprocess

import click
import yaml
from jinja2 import Environment, FileSystemLoader


@click.command(name="render-dag")
@click.option(
"--config",
"-c",
type=click.Path(exists=True),
required=True,
help="Path to the YAML configuration file.",
)
@click.option(
"--template",
"-t",
type=click.Path(exists=True),
required=True,
help="Path to the Jinja template file.",
)
@click.option(
"--output",
"-o",
type=click.Path(),
default="generated_dag.py",
help="Path where the generated DAG file should be saved (default: generated_dag.py).",
)
def render_dag_cli(config, template, output):
"""CLI tool to render an Airflow DAG from a YAML configuration file using Jinja."""
try:
render_dag(config, output, template)

click.echo(f"✅ DAG file successfully generated: {output}")

except Exception as e:
click.echo(f"❌ Error: {e}", err=True)
exit(1)


def render_dag(config, output, template):
"""Render an Airflow DAG from a YAML configuration file using Jinja."""
# Load YAML config
with open(config, "r") as file:
config_data = yaml.safe_load(file)
assert 'dag_id' in config_data, 'dag_id not found in config file'
# Load Jinja template
env = Environment(loader=FileSystemLoader("."), autoescape=True)
template_obj = env.get_template(template)
# Render template
dag_code = template_obj.render(config_data)
# Save the rendered DAG
with open(output, "w") as dag_file:
dag_file.write(dag_code)
if output.endswith('.py'):
reformat_with_black(output)


def reformat_with_black(output_file):
"""Reformat the output file using black."""
black_result = subprocess.run(['black', output_file], capture_output=True, text=True)
if black_result.returncode == 0:
print(f"Black formatting applied successfully to {output_file}")
else:
print(f"Black formatting failed: {black_result.stdout} {black_result.stderr}")


if __name__ == "__main__":
render_dag_cli()
2 changes: 2 additions & 0 deletions mkdag/mypy.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[mypy]
disable_error_code = import-untyped
7 changes: 7 additions & 0 deletions mkdag/pytest.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# pytest.ini
[pytest]
filterwarnings =
ignore::DeprecationWarning:halo.*
markers =
asyncio: asyncio mark
; addopts = --cov=fhir_query --cov-report=term-missing
6 changes: 6 additions & 0 deletions mkdag/requirements-dev.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
setuptools
wheel
black
mypy
pytest
pytest-cov
3 changes: 3 additions & 0 deletions mkdag/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
click
jinja2
pyyaml
19 changes: 19 additions & 0 deletions mkdag/setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from setuptools import setup, find_packages


def parse_requirements(filename: str) -> list[str]:
with open(filename, "r") as file:
return [line.strip() for line in file if line.strip() and not line.startswith("#")]


setup(
name="mkdag",
version="0.1.0",
packages=find_packages(),
install_requires=parse_requirements("requirements.txt"),
entry_points={
"console_scripts": [
"mkdag=mkdag.cli:render_dag_cli",
],
},
)
1 change: 1 addition & 0 deletions mkdag/tests/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

42 changes: 42 additions & 0 deletions mkdag/tests/fixtures/pop-etl/config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
dag_id: "test2"
schedule_interval: "@daily"
start_date: "2025-01-01"
description: "A POP (plain old python) ETL pipeline"

variables:
dag:
aws_conn_id: test2_dag
bucket_name: EllrottLab
etag_variable_name: test_etag
s3_prefix: tractor/swapi
url: https://swapi.dev/api/
etag: INITIAL-VALUE

connections:
test2_dag:
conn_type: aws
description: connection to ceph bucket for test2
login: CHANGE_ME-aws_access_key_id
password: CHANGE_ME-aws_secret_access_key
extra:
endpoint_url: https://rgw.ohsu.edu

sensor:
description: "Check if the ETag has changed"
type: "http-etag"
poke_interval: 60
timeout: 120

extract:
description: "Download from url, save in S3"
type: "http-s3"

transform:
description: "Transform from json, save in S3 as html"
type: "json-html"

load:
description: "(mock) list the transformed files"
type: "mock"


Loading

0 comments on commit 4cf6296

Please sign in to comment.