Skip to content

Commit

Permalink
Add label-wrap feature (#16)
Browse files Browse the repository at this point in the history
  • Loading branch information
feluelle authored Jan 27, 2022
1 parent 1213056 commit 6061cb1
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 2 deletions.
11 changes: 10 additions & 1 deletion airflow_diagrams/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
load_mappings,
render_jinja,
to_var,
wrap_str,
)

app = Typer()
Expand Down Expand Up @@ -92,6 +93,12 @@ def generate( # dead: disable
"-v",
help="Verbose output i.e. useful for debugging purposes.",
),
label_wrap: Optional[str] = Option(
None,
"--label-wrap",
"-lw",
help="Specify either a number for label width or a separator to indicate when to wrap a label.",
),
) -> None:
if verbose:
echo("💬 Running with verbose output..")
Expand Down Expand Up @@ -133,7 +140,9 @@ def generate( # dead: disable
diagram_nodes.append(
dict(
task_var=to_var(airflow_task.task_id),
task_id=airflow_task.task_id,
task_id=wrap_str(airflow_task.task_id, label_wrap)
if label_wrap
else airflow_task.task_id,
class_name=match_class_ref.class_name,
),
)
Expand Down
14 changes: 14 additions & 0 deletions airflow_diagrams/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from hashlib import md5
from os.path import dirname
from pathlib import Path
from textwrap import wrap

import yaml
from jinja2.environment import Environment
Expand Down Expand Up @@ -66,3 +67,16 @@ def to_var(string: str) -> str:
:returns: a valid python variable name.
"""
return f"_{md5(string.encode()).hexdigest()}" # nosec


def wrap_str(string: str, indicator: str) -> str:
"""
Wrap a string with newline chars based on indicator.
:params string: The string to wrap.
:params indicator: Specify either a number for width or a separator to indicate when to wrap.
:returns: the wrapped string.
"""
if indicator.isdigit():
return "\\n".join(wrap(string, int(indicator), break_on_hyphens=False))
return "\\n".join(string.split(indicator))
12 changes: 11 additions & 1 deletion tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from airflow_diagrams.utils import load_abbreviations, load_mappings, to_var
from airflow_diagrams.utils import load_abbreviations, load_mappings, to_var, wrap_str


def test_load_abbreviations(mocker):
Expand All @@ -23,3 +23,13 @@ def test_to_var():
var = to_var("foo-bar")
assert "-" not in var and "." not in var
assert var.startswith("_")


def test_wrap_str__indicator_number():
"""Test wrapping a string based on number"""
assert wrap_str("foobarfoobar", "10") == "foobarfoob\\nar"


def test_wrap_str__indicator_separator():
"""Test wrapping a string based on separator"""
assert wrap_str("foobarfoobar", "foo") == "\\nbar\\nbar"

0 comments on commit 6061cb1

Please sign in to comment.