Skip to content

Commit

Permalink
feat: add prepend and append to inline_function plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
vberlier committed Apr 23, 2021
1 parent a08c73c commit e12347f
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 3 deletions.
22 changes: 19 additions & 3 deletions beet/contrib/inline_function.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

from jinja2.ext import Extension
from jinja2.nodes import DerivedContextReference # type: ignore
from jinja2.nodes import CallBlock, Node
from jinja2.nodes import CallBlock, Node, TemplateData

from beet import Context, Function

Expand All @@ -28,6 +28,16 @@ def parse(self, parser: Any) -> Node:
lineno = next(parser.stream).lineno

args: List[Any] = [DerivedContextReference(), parser.parse_expression()]

if parser.stream.current.test("name:append"):
args.append(TemplateData("append"))
parser.stream.skip()
elif parser.stream.current.test("name:prepend"):
args.append(TemplateData("prepend"))
parser.stream.skip()
else:
args.append(TemplateData("replace"))

body = parser.parse_statements(["name:endfunction"], drop_needle=True)

return CallBlock(
Expand All @@ -38,11 +48,17 @@ def parse(self, parser: Any) -> Node:
lineno=lineno,
)

def _function_handler(self, context: Any, path: str, caller: Any) -> str:
def _function_handler(self, context: Any, path: str, op: str, caller: Any) -> str:
ctx: Context = context["ctx"]

with ctx.override(render_path=path, render_group="functions"):
commands = caller()

ctx.data[path] = Function(commands)
if op == "replace":
ctx.data[path] = Function(commands)
elif op == "append":
ctx.data.functions.setdefault(path, Function()).append(Function(commands))
elif op == "prepend":
ctx.data.functions.setdefault(path, Function()).prepend(Function(commands))

return ""
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ function demo:inner
#!tag "demo:nested"

say from nested {{ i }}
#!function "demo:forward" append
function {{ nested_function }}
#!endfunction
#!function "demo:reverse" prepend
function {{ nested_function }}
#!endfunction
#!endfunction
#!endfor

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
function demo:nested_0
function demo:nested_1
function demo:nested_2
function demo:nested_3
function demo:nested_4
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
function demo:nested_4
function demo:nested_3
function demo:nested_2
function demo:nested_1
function demo:nested_0

0 comments on commit e12347f

Please sign in to comment.