1"""Implementation for rules that render d2 diagrams (https://d2lang.org)"""
2
3load("@aspect_bazel_lib//lib:write_source_files.bzl", _write_source_file = "write_source_file")
4
5def _d2_impl(ctx):
6 out = ctx.actions.declare_file("{0}.{1}".format(ctx.label.name, ctx.attr.format))
7
8 args = ctx.actions.args()
9 args.add_all([
10 "--layout",
11 ctx.attr.layout,
12 "--theme",
13 ctx.attr.theme,
14 "--browser",
15 "0",
16 ] + ctx.attr.args, uniquify = True)
17 args.add(ctx.file.src.path)
18 args.add(out)
19
20 ctx.actions.run(
21 outputs = [out],
22 inputs = depset([ctx.file.src] + ctx.files.deps),
23 executable = ctx.executable._d2,
24 arguments = [args],
25 mnemonic = "D2Render",
26 )
27
28 return [DefaultInfo(files = depset([out]))]
29
30_d2 = rule(
31 implementation = _d2_impl,
32 attrs = {
33 "src": attr.label(
34 doc = ".d2 file to render",
35 allow_single_file = True,
36 mandatory = True,
37 ),
38 "deps": attr.label_list(
39 doc = ".d2 files imported by this diagram",
40 allow_files = True,
41 ),
42 "format": attr.string(
43 doc = "Image format to render",
44 default = "svg",
45 values = ["svg", "png"],
46 ),
47 "theme": attr.int(
48 doc = "D2 theme to use",
49 default = 300,
50 ),
51 "layout": attr.string(
52 doc = "D2 layout engine",
53 default = "dagre",
54 values = ["dagre", "elk"],
55 ),
56 "args": attr.string_list(
57 doc = "Additional args to pass to the d2 binary",
58 default = [],
59 ),
60 "_d2": attr.label(
61 default = Label("@com_terrastruct_oss_d2//:d2"),
62 allow_single_file = True,
63 executable = True,
64 cfg = "exec",
65 ),
66 },
67)
68
69def d2(
70 name,
71 deps = None,
72 format = "svg",
73 theme = None,
74 layout = None,
75 args = [],
76 write_to_tree = True,
77 **kwargs):
78 _d2(
79 name = name,
80 deps = deps,
81 format = format,
82 theme = theme,
83 layout = layout,
84 args = args,
85 **kwargs
86 )
87
88 if write_to_tree:
89 _write_source_file(
90 name = "write_{0}_{1}".format(name, format),
91 in_file = name,
92 out_file = "{0}.{1}".format(name, format),
93 )
View as plain text