"""Implementation for rules that render d2 diagrams (https://d2lang.org)""" load("@aspect_bazel_lib//lib:write_source_files.bzl", _write_source_file = "write_source_file") def _d2_impl(ctx): out = ctx.actions.declare_file("{0}.{1}".format(ctx.label.name, ctx.attr.format)) args = ctx.actions.args() args.add_all([ "--layout", ctx.attr.layout, "--theme", ctx.attr.theme, "--browser", "0", ] + ctx.attr.args, uniquify = True) args.add(ctx.file.src.path) args.add(out) ctx.actions.run( outputs = [out], inputs = depset([ctx.file.src] + ctx.files.deps), executable = ctx.executable._d2, arguments = [args], mnemonic = "D2Render", ) return [DefaultInfo(files = depset([out]))] _d2 = rule( implementation = _d2_impl, attrs = { "src": attr.label( doc = ".d2 file to render", allow_single_file = True, mandatory = True, ), "deps": attr.label_list( doc = ".d2 files imported by this diagram", allow_files = True, ), "format": attr.string( doc = "Image format to render", default = "svg", values = ["svg", "png"], ), "theme": attr.int( doc = "D2 theme to use", default = 300, ), "layout": attr.string( doc = "D2 layout engine", default = "dagre", values = ["dagre", "elk"], ), "args": attr.string_list( doc = "Additional args to pass to the d2 binary", default = [], ), "_d2": attr.label( default = Label("@com_terrastruct_oss_d2//:d2"), allow_single_file = True, executable = True, cfg = "exec", ), }, ) def d2( name, deps = None, format = "svg", theme = None, layout = None, args = [], write_to_tree = True, **kwargs): _d2( name = name, deps = deps, format = format, theme = theme, layout = layout, args = args, **kwargs ) if write_to_tree: _write_source_file( name = "write_{0}_{1}".format(name, format), in_file = name, out_file = "{0}.{1}".format(name, format), )