Skip to content

Commit 23da0d6

Browse files
committed
Add: support jinja.
1 parent 8e8e931 commit 23da0d6

File tree

3 files changed

+46
-4
lines changed

3 files changed

+46
-4
lines changed

cmdcomp/app.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ def run(cls, args: list[str] | None = None) -> None:
3333
"-f",
3434
required=True,
3535
type=FileType("rb"),
36-
help="config file ('.json', '.yaml', '.toml' support).",
36+
help="config file ('.json', '.yaml', '.toml', '.jinja2' support).",
3737
)
3838

3939
parser.add_argument(

cmdcomp/config.py

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
import json
22
import os
33
import tomllib
4-
from typing import BinaryIO
4+
from io import StringIO
5+
from typing import IO
56

7+
import jinja2
68
import yaml
79
from pydantic import RootModel
810

@@ -17,8 +19,8 @@ class Config(RootModel):
1719
root: V1Config | V2Config
1820

1921

20-
def load(file: BinaryIO) -> Config:
21-
_, extension = os.path.splitext(file.name)
22+
def load(file: IO) -> Config:
23+
root, extension = os.path.splitext(file.name)
2224
match extension:
2325
case ".json":
2426
data = json.load(file)
@@ -29,6 +31,12 @@ def load(file: BinaryIO) -> Config:
2931
case ".toml":
3032
data = tomllib.load(file)
3133

34+
case ".jinja" | "jinja2" | ".j2":
35+
data = StringIO(jinja2.Template(file.read()).render(os.environ))
36+
data.name = root
37+
38+
return load(data)
39+
3240
case _:
3341
raise ConfigFileExtensionError(extension)
3442

tests/test_config.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
from io import StringIO
2+
from textwrap import dedent
3+
4+
from cmdcomp.config import load
5+
6+
7+
def make_file(filename: str, contents: str) -> StringIO:
8+
file = StringIO(contents)
9+
file.name = filename
10+
11+
return file
12+
13+
14+
class TestConfig:
15+
def test_jinja(self):
16+
config = load(
17+
make_file(
18+
"config.yaml.jinja",
19+
dedent(
20+
"""
21+
{%- set app_name = "mycli" -%}
22+
cmdcomp:
23+
version: "2"
24+
app:
25+
name: {{ app_name }}
26+
root:
27+
arguments:
28+
--help:
29+
"""
30+
),
31+
)
32+
)
33+
34+
assert config.root.app.name == "mycli"

0 commit comments

Comments
 (0)