├── LICENSE-APACHE.md ├── LICENSE-MIT.md ├── README.md ├── build.zig └── src └── main.zig /LICENSE-APACHE.md: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. -------------------------------------------------------------------------------- /LICENSE-MIT.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Haze Booth 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ### what 2 | Zigbo is a custom build step for the Zig build system. You can use this step to render a diagram of the Zig build graph. 3 | 4 | ### example build graph (zigbo's) 5 | 6 | ``` mermaid 7 | flowchart TD 8 | subgraph tls_0 [Copy build artifacts to prefix path] 9 | step_0[Opaque Top Level Step] 10 | step_0 --> step_1["InstallArtifactStep: (install zigbo)\ndestination: build.InstallDir{ .lib = void }"] 11 | step_1 --> step_2["LibExeObjStep (zigbo)\nkind: lib\nmode: Debug\nlinkage: static\nroot_src: '/Users/haze/Code/zigbo/src/main.zig'"] 12 | end 13 | subgraph tls_1 [Remove build artifacts from prefix path] 14 | step_3[Opaque Top Level Step] 15 | end 16 | subgraph tls_2 [Run library tests] 17 | step_4[Opaque Top Level Step] 18 | step_4 --> step_5["LibExeObjStep (test)\nkind: test\nmode: Debug\nroot_src: '/Users/haze/Code/zigbo/src/main.zig'"] 19 | end 20 | subgraph tls_3 [Output the build graph as a mermaid diagram] 21 | step_6[Opaque Top Level Step] 22 | step_6 --> step_7["Opaque Custom Step (Graph Output)"] 23 | end 24 | ``` 25 | 26 | ### usage 27 | Zigbo exports a `GraphOutputStep` comptime function, which accepts a type of a reader. You can use this to configure the output of the diagram. Below is a simple example of configuring a top level `graph` step to export the graph to stdout. 28 | 29 | ``` zig 30 | const stdout = std.io.getStdOut().writer(); 31 | const build_graph = zigbo.graphOutputStep(b, stdout); 32 | const build_graph_step = b.step("graph", "Output the build graph as a mermaid diagram"); 33 | build_graph_step.dependOn(&build_graph.step); 34 | ``` 35 | 36 | If you have custom steps within your build graph, Zigbo by default cannot display all the details of your step (all of the information is opt-in). Below is an example of using a callback function to provide information for specific steps based on their step name. 37 | 38 | ```zig 39 | build_graph.setCustomStepCallback(struct{ 40 | fn customCallback(step: *std.build.Step, writer: anytype) !?zigbo.GraphOutputWriteFnInstruction { 41 | if (std.mem.startsWith(u8, step.name, "has-")) { 42 | libressl_build.CDependencyTestStep.mermaidDescribe(step, writer) catch |err| { 43 | try writer.print("error.{s}", .{@errorName(err)}); 44 | }; 45 | return null; 46 | } else if (std.mem.endsWith(u8, step.name, "WideCDependencyStep")) { 47 | libressl_build.WideCDependencyStep.mermaidDescribe(step, writer) catch |err| { 48 | try writer.print("error.{s}", .{@errorName(err)}); 49 | }; 50 | return null; 51 | } else if (std.mem.endsWith(u8, step.name, "DeferredLibExeObjStep")) { 52 | libressl_build.DeferredLibExeObjStep.mermaidDescribe(step, writer) catch |err| { 53 | try writer.print("error.{s}", .{@errorName(err)}); 54 | }; 55 | return null; 56 | } 57 | 58 | return .use_default_implementation; 59 | } 60 | }.customCallback); 61 | ``` 62 | 63 | ### how 64 | The Zig build system only asks you to not modify the build graph during "maketime" (build step execution). We are allowed to **READ** it then. Knowing this, we can traverse the build graph (in the same way that calling `make` would) and output a diagram (for now, only [mermaid](https://mermaid.js.org/#/)) allowing you to analyse, inspect, and digest your entire build graph. 65 | 66 | ### who 67 | Zigbo was originally written by [haze](https://github.com/haze) and donated to [InKryption](https://github.com/InKryption) for maintenance. 68 | 69 | ### when 70 | Zigbo was initially built between January 21st and January 24th. 71 | 72 | ### where 73 | Zigbo was proudly built in New York City. 74 | 75 | 76 | Licensed under either of Apache License, Version 77 | 2.0 or MIT license at your option. 78 | 79 | 80 |
81 | 82 | 83 | Unless you explicitly state otherwise, any contribution intentionally submitted 84 | for inclusion in this package by you, as defined in the Apache-2.0 license, shall 85 | be dual licensed as above, without any additional terms or conditions. 86 | 87 | -------------------------------------------------------------------------------- /build.zig: -------------------------------------------------------------------------------- 1 | const std = @import("std"); 2 | const zigbo = @import("src/main.zig"); 3 | 4 | pub fn build(b: *std.Build) void { 5 | const target = b.standardTargetOptions(.{}); 6 | const optimize = b.standardOptimizeOption(.{}); 7 | 8 | const lib = b.addStaticLibrary(.{ 9 | .name = "zigbo", 10 | .root_source_file = .{ .path = "src/main.zig" }, 11 | .target = target, 12 | .optimize = optimize, 13 | }); 14 | lib.install(); 15 | 16 | const main_tests = b.addTest(.{ 17 | .root_source_file = .{ .path = "src/main.zig" }, 18 | .target = target, 19 | .optimize = optimize, 20 | }); 21 | 22 | const test_step = b.step("test", "Run library tests"); 23 | test_step.dependOn(&main_tests.step); 24 | 25 | const stdout = std.io.getStdOut().writer(); 26 | const build_graph = zigbo.graphOutputStep(b, stdout); 27 | build_graph.setCustomStepCallback(customCallback); 28 | 29 | const build_graph_step = b.step("graph", "Output the build graph as a mermaid diagram"); 30 | build_graph_step.dependOn(&build_graph.step); 31 | } 32 | 33 | fn customCallback(step: *std.Build.Step, writer: anytype) !?zigbo.GraphOutputWriteFnInstruction { 34 | _ = writer; 35 | if (std.mem.eql(u8, step.name, "foobarbaz\x00" ** 23)) return null; 36 | return .use_default_implementation; 37 | } 38 | -------------------------------------------------------------------------------- /src/main.zig: -------------------------------------------------------------------------------- 1 | const std = @import("std"); 2 | 3 | pub const GraphOutputWriteFnInstruction = enum { 4 | /// Simply print out "Opaque Custom Step (step_name)" 5 | use_default_implementation, 6 | }; 7 | 8 | pub fn graphOutputStep(builder: *std.Build, writer: anytype) *GraphOutputStep(@TypeOf(writer)) { 9 | return GraphOutputStep(@TypeOf(writer)).init(builder, writer); 10 | } 11 | 12 | /// Outputs a mermaid diagram describing the build graph 13 | pub fn GraphOutputStep(comptime WriterType: type) type { 14 | return struct { 15 | const Self = @This(); 16 | writer: Writer, 17 | builder: *std.Build, 18 | step: std.Build.Step, 19 | custom_step_callback: *const GraphOutputWriteFn = defaultCustomStepCallback, 20 | 21 | pub const Writer = WriterType; 22 | 23 | pub fn defaultCustomStepCallback(step: *std.Build.Step, writer: Writer) Writer.Error!?GraphOutputWriteFnInstruction { 24 | _ = writer; 25 | _ = step; 26 | return .use_default_implementation; 27 | } 28 | 29 | pub fn init(builder: *std.Build, writer: Writer) *Self { 30 | var graph_output_step = builder.allocator.create(Self) catch unreachable; 31 | graph_output_step.* = Self{ 32 | .writer = writer, 33 | .builder = builder, 34 | .step = std.Build.Step.init(.custom, "zigbo graph", builder.allocator, Self.make), 35 | }; 36 | return graph_output_step; 37 | } 38 | 39 | pub fn setCustomStepCallback(self: *Self, comptime callback: anytype) void { 40 | switch (@typeInfo(@TypeOf(callback))) { 41 | .Fn => {}, 42 | else => @compileError("Expected function, got " ++ @typeName(@TypeOf(callback))), 43 | } 44 | 45 | const gen = struct { 46 | fn callbackWrapper(step: *std.Build.Step, writer: Writer) Writer.Error!?GraphOutputWriteFnInstruction { 47 | return @call(.always_inline, callback, .{ step, writer }); 48 | } 49 | }; 50 | 51 | self.custom_step_callback = gen.callbackWrapper; 52 | } 53 | 54 | pub const AnnotatedBuiltinStep = struct { 55 | step: *std.Build.Step, 56 | graph_output_step: *Self, 57 | 58 | pub fn format( 59 | annotated_builtin_step: AnnotatedBuiltinStep, 60 | comptime fmt: []const u8, 61 | options: std.fmt.FormatOptions, 62 | writer: Writer, 63 | ) !void { 64 | _ = fmt; 65 | _ = options; 66 | 67 | return switch (annotated_builtin_step.step.id) { 68 | .top_level => step_inspection_functions.annotateTopLevelStep(annotated_builtin_step.step, writer), 69 | .install_artifact => step_inspection_functions.annotateInstallArtifactStep(annotated_builtin_step.step, writer), 70 | .compile => step_inspection_functions.annotateCompileStep(annotated_builtin_step.step, writer, .{ 71 | .print_newlines = true, 72 | .print_in_between_quotes = true, 73 | }), 74 | .run => step_inspection_functions.annotateRunStep(annotated_builtin_step.step, writer), 75 | .custom => blk: { 76 | const customFormatFn = annotated_builtin_step.graph_output_step.custom_step_callback; 77 | const maybe_instruction = try customFormatFn(annotated_builtin_step.step, writer); 78 | const instruction = maybe_instruction orelse break :blk; 79 | switch (instruction) { 80 | .use_default_implementation => try writer.print("\"{s} (Custom)\"", .{annotated_builtin_step.step.name}), 81 | } 82 | }, 83 | 84 | // TODO(haze): better messages for these 85 | .options => try writer.writeAll("Options step"), 86 | .objcopy => try writer.writeAll("ObjCopy step"), 87 | .config_header => try writer.writeAll("Configure Header step"), 88 | .check_object => try writer.writeAll("CHeck Object step"), 89 | .check_file => try writer.writeAll("Check File step"), 90 | .emulatable_run => try writer.writeAll("Emulatable Run step"), 91 | .write_file => try writer.writeAll("Write File step"), 92 | .translate_c => try writer.writeAll("Translate-C step"), 93 | .fmt => try writer.writeAll("Format step"), 94 | .remove_dir => try writer.writeAll("Remove Directory step"), 95 | .log => try writer.writeAll("Log step"), 96 | .install_dir => try writer.writeAll("Install Directory step"), 97 | .install_file => try writer.writeAll("Install File step"), 98 | }; 99 | } 100 | }; 101 | 102 | pub const Header = struct { 103 | direction: Direction, 104 | 105 | pub const Direction = enum { 106 | top_to_bottom, 107 | top_down, 108 | bottom_to_top, 109 | right_to_left, 110 | left_to_right, 111 | 112 | pub fn format( 113 | direction: Direction, 114 | comptime fmt: []const u8, 115 | options: std.fmt.FormatOptions, 116 | writer: Writer, 117 | ) !void { 118 | _ = options; 119 | _ = fmt; 120 | try writer.writeAll(switch (direction) { 121 | .top_to_bottom => "TB", 122 | .top_down => "TD", 123 | .bottom_to_top => "BT", 124 | .right_to_left => "RL", 125 | .left_to_right => "LR", 126 | }); 127 | } 128 | }; 129 | 130 | pub fn format( 131 | header: Header, 132 | comptime fmt: []const u8, 133 | options: std.fmt.FormatOptions, 134 | writer: Writer, 135 | ) !void { 136 | _ = options; 137 | _ = fmt; 138 | try writer.print("flowchart {}", .{header.direction}); 139 | } 140 | }; 141 | 142 | pub const Subgraph = struct { 143 | pub const Start = struct { 144 | name: []const u8, 145 | id: usize, 146 | 147 | pub fn format( 148 | start: Start, 149 | comptime fmt: []const u8, 150 | options: std.fmt.FormatOptions, 151 | writer: Writer, 152 | ) !void { 153 | _ = options; 154 | _ = fmt; 155 | try writer.print("subgraph tls_{} [{s}]", .{ start.id, start.name }); 156 | } 157 | }; 158 | pub const End = struct { 159 | pub fn format( 160 | end: End, 161 | comptime fmt: []const u8, 162 | options: std.fmt.FormatOptions, 163 | writer: Writer, 164 | ) !void { 165 | _ = end; 166 | _ = options; 167 | _ = fmt; 168 | try writer.writeAll("end"); 169 | } 170 | }; 171 | }; 172 | 173 | pub const Edge = struct { 174 | parent: *std.Build.Step, 175 | parent_id: usize, 176 | include_parent_description: bool, 177 | 178 | child: *std.Build.Step, 179 | child_id: usize, 180 | include_child_description: bool, 181 | 182 | graph_output_step: *Self, 183 | 184 | pub fn format( 185 | edge: Edge, 186 | comptime fmt: []const u8, 187 | options: std.fmt.FormatOptions, 188 | writer: Writer, 189 | ) !void { 190 | _ = options; 191 | _ = fmt; 192 | try writer.print("step_{}", .{ 193 | edge.parent_id, 194 | }); 195 | if (edge.include_parent_description) { 196 | try writer.print("[{}]", .{ 197 | AnnotatedBuiltinStep{ 198 | .step = edge.parent, 199 | .graph_output_step = edge.graph_output_step, 200 | }, 201 | }); 202 | } 203 | try writer.writeAll(" --> "); 204 | try writer.print("step_{}", .{ 205 | edge.child_id, 206 | }); 207 | if (edge.include_child_description) { 208 | try writer.print("[{}]", .{ 209 | AnnotatedBuiltinStep{ 210 | .step = edge.child, 211 | .graph_output_step = edge.graph_output_step, 212 | }, 213 | }); 214 | } 215 | } 216 | }; 217 | 218 | pub const Node = struct { 219 | item: *std.Build.Step, 220 | id: usize, 221 | include_description: bool, 222 | graph_output_step: *Self, 223 | 224 | pub fn format( 225 | node: Node, 226 | comptime fmt: []const u8, 227 | options: std.fmt.FormatOptions, 228 | writer: Writer, 229 | ) !void { 230 | _ = options; 231 | _ = fmt; 232 | try writer.print("step_{}", .{ 233 | node.id, 234 | }); 235 | if (node.include_description) { 236 | try writer.print("[{}]", .{ 237 | AnnotatedBuiltinStep{ 238 | .step = node.item, 239 | .graph_output_step = node.graph_output_step, 240 | }, 241 | }); 242 | } 243 | } 244 | }; 245 | 246 | pub const GraphOutputWriteFn = fn (step: *std.Build.Step, writer: Writer) Writer.Error!?GraphOutputWriteFnInstruction; 247 | 248 | fn make(type_erased_graph_output_step: *std.Build.Step) anyerror!void { 249 | const graph_output_step = @fieldParentPtr(Self, "step", type_erased_graph_output_step); 250 | try graph_output_step.writer.print("{}\n", .{Header{ .direction = .top_down }}); 251 | var subgraph_counter: usize = 0; 252 | 253 | var step_id_map = std.AutoHashMapUnmanaged(*std.Build.Step, usize){}; 254 | var running_step_id: usize = 0; 255 | defer step_id_map.deinit(graph_output_step.builder.allocator); 256 | 257 | var step_visited_map = std.AutoHashMapUnmanaged(*std.Build.Step, void){}; 258 | defer step_visited_map.deinit(graph_output_step.builder.allocator); 259 | 260 | for (graph_output_step.builder.top_level_steps.items) |top_level_step| { 261 | try graph_output_step.writer.print("\t{}\n", .{Subgraph.Start{ 262 | .name = top_level_step.description, 263 | .id = subgraph_counter, 264 | }}); 265 | 266 | var dependency_stack = std.ArrayListUnmanaged(*std.Build.Step){}; 267 | defer dependency_stack.deinit(graph_output_step.builder.allocator); 268 | 269 | var parent_map = std.AutoHashMapUnmanaged(*std.Build.Step, *std.Build.Step){}; 270 | defer parent_map.deinit(graph_output_step.builder.allocator); 271 | 272 | try dependency_stack.append(graph_output_step.builder.allocator, &top_level_step.step); 273 | 274 | while (dependency_stack.popOrNull()) |step| { 275 | var include_step_description: bool = false; 276 | if (step_id_map.get(step) == null) { 277 | try step_id_map.put(graph_output_step.builder.allocator, step, running_step_id); 278 | include_step_description = true; 279 | running_step_id += 1; 280 | } 281 | const step_id = step_id_map.get(step).?; 282 | 283 | if (step_visited_map.get(step) == null) { 284 | if (parent_map.get(step)) |parent_step| { 285 | try graph_output_step.writer.print("\t{}\n", .{Edge{ 286 | .parent = parent_step, 287 | .parent_id = step_id_map.get(parent_step).?, 288 | .include_parent_description = false, 289 | .child = step, 290 | .child_id = step_id, 291 | .include_child_description = include_step_description, 292 | .graph_output_step = graph_output_step, 293 | }}); 294 | } else { 295 | try graph_output_step.writer.print("\t{}\n", .{Node{ 296 | .item = step, 297 | .id = step_id, 298 | .include_description = include_step_description, 299 | .graph_output_step = graph_output_step, 300 | }}); 301 | } 302 | try step_visited_map.put(graph_output_step.builder.allocator, step, {}); 303 | } 304 | 305 | for (step.dependencies.items) |dependency_step| { 306 | if (!dependency_step.loop_flag) { 307 | try parent_map.put(graph_output_step.builder.allocator, dependency_step, step); 308 | try dependency_stack.append(graph_output_step.builder.allocator, dependency_step); 309 | } 310 | } 311 | } 312 | 313 | try graph_output_step.writer.print("\t{}\n", .{Subgraph.End{}}); 314 | 315 | subgraph_counter += 1; 316 | } 317 | } 318 | }; 319 | } 320 | 321 | const step_inspection_functions = struct { 322 | pub fn annotateTopLevelStep(step: *std.Build.Step, writer: anytype) !void { 323 | // TODO: This is a hack around the fact that `std.build.Builder.TopLevelStep` is a private decl. 324 | // Look into whether it could be made public upstream. 325 | const TopLevelStep = std.meta.FieldType(std.build.Builder, .install_tls); 326 | std.debug.assert(step.cast(TopLevelStep) != null); 327 | try writer.print("\"{s} (Top Level)\"", .{step.name}); 328 | } 329 | 330 | pub fn annotateCompileStep(step: *std.Build.Step, writer: anytype, options: struct { 331 | print_newlines: bool, 332 | print_in_between_quotes: bool, 333 | }) !void { 334 | const compile_step = @fieldParentPtr(std.Build.CompileStep, "step", step); 335 | if (options.print_in_between_quotes) { 336 | try writer.writeByte('"'); 337 | } 338 | 339 | try writer.print("{s} (Compile)", .{compile_step.name}); 340 | 341 | if (options.print_newlines) { 342 | try writer.writeAll("\\n"); 343 | } else { 344 | try writer.writeAll(", "); 345 | } 346 | 347 | try writer.print("kind: {s}", .{@tagName(compile_step.kind)}); 348 | 349 | if (options.print_newlines) { 350 | try writer.writeAll("\\n"); 351 | } else { 352 | try writer.writeAll(", "); 353 | } 354 | try writer.print("mode: {s}", .{@tagName(compile_step.optimize)}); 355 | 356 | if (compile_step.linkage) |linkage| { 357 | if (options.print_newlines) { 358 | try writer.writeAll("\\n"); 359 | } else { 360 | try writer.writeAll(", "); 361 | } 362 | try writer.print("linkage: {s}", .{@tagName(linkage)}); 363 | } 364 | 365 | if (compile_step.root_src) |root_src| { 366 | if (options.print_newlines) { 367 | try writer.writeAll("\\n"); 368 | } else { 369 | try writer.writeAll(", "); 370 | } 371 | try writer.print("root_src: '{}'", .{formatting.fmtFileSource(compile_step.builder, root_src)}); 372 | } 373 | 374 | if (compile_step.version) |version| { 375 | if (options.print_newlines) { 376 | try writer.writeAll("\\n"); 377 | } else { 378 | try writer.writeAll(", "); 379 | } 380 | try writer.print("version: {}", .{version}); 381 | } 382 | 383 | if (options.print_in_between_quotes) { 384 | try writer.writeByte('"'); 385 | } else { 386 | try writer.writeByte('}'); 387 | } 388 | } 389 | 390 | // TODO(haze): annotate envmap 391 | pub fn annotateRunStep(step: *std.Build.Step, writer: anytype) !void { 392 | const run_step = @fieldParentPtr(std.Build.RunStep, "step", step); 393 | 394 | try writer.writeAll("\"Run\\nargv: ["); 395 | for (run_step.argv.items, 0..) |arg, index| { 396 | try writer.print("{}", .{formatting.RunStepArg{ .arg = arg, .builder = run_step.builder }}); 397 | if (index != run_step.argv.items.len - 1) { 398 | try writer.writeAll(", "); 399 | } 400 | } 401 | try writer.writeAll("]"); 402 | 403 | if (run_step.cwd) |cwd| { 404 | try writer.print("\\ncwd: '{s}'", .{cwd}); 405 | } 406 | 407 | if (run_step.expected_term) |exit_code| { 408 | try writer.print("\\nexpecting exit code: {}", .{exit_code}); 409 | } 410 | 411 | try writer.writeAll("\""); 412 | } 413 | 414 | pub fn annotateInstallArtifactStep(step: *std.Build.Step, writer: anytype) !void { 415 | const install_artifact_step = @fieldParentPtr(std.Build.InstallArtifactStep, "step", step); 416 | const builder = install_artifact_step.builder; 417 | 418 | try writer.print( 419 | "\"{s} (Install Artifact)\\ndestination: '{}'\"", 420 | .{ install_artifact_step.step.name, formatting.fmtInstallDir(builder, install_artifact_step.dest_dir) }, 421 | ); 422 | 423 | if (install_artifact_step.pdb_dir) |pdb_directory| { 424 | try writer.print("\\nPDB directory: '{}'", .{formatting.fmtInstallDir(builder, pdb_directory)}); 425 | } 426 | 427 | if (install_artifact_step.pdb_dir) |header_directory| { 428 | try writer.print("\\nHeader directory: '{}'", .{formatting.fmtInstallDir(builder, header_directory)}); 429 | } 430 | } 431 | }; 432 | 433 | const formatting = struct { 434 | pub const Artifact = struct { 435 | compile_step: *std.Build.CompileStep, 436 | 437 | pub fn format( 438 | artifact: Artifact, 439 | comptime fmt: []const u8, 440 | options: std.fmt.FormatOptions, 441 | writer: anytype, 442 | ) !void { 443 | _ = fmt; 444 | _ = options; 445 | try step_inspection_functions.annotateCompileStep(&artifact.compile_step.step, writer, .{ 446 | .print_newlines = false, 447 | .print_in_between_quotes = false, 448 | }); 449 | } 450 | }; 451 | 452 | pub const FormattedFileSource = struct { 453 | builder: *std.Build, 454 | file_source: std.Build.FileSource, 455 | 456 | pub fn format( 457 | formatter: FormattedFileSource, 458 | comptime fmt: []const u8, 459 | options: std.fmt.FormatOptions, 460 | writer: anytype, 461 | ) !void { 462 | _ = fmt; 463 | _ = options; 464 | const path = formatter.file_source.getPath(formatter.builder); 465 | const relative_path = formatter.builder.build_root.join(formatter.builder.allocator, &.{path}) catch unreachable; 466 | defer formatter.builder.allocator.free(relative_path); // there's a chance this could get freed, with it (presumably) being the latest allocation. 467 | try writer.writeAll(relative_path); 468 | } 469 | }; 470 | pub fn fmtFileSource(builder: *std.Build, file_source: std.Build.FileSource) FormattedFileSource { 471 | return .{ 472 | .builder = builder, 473 | .file_source = file_source, 474 | }; 475 | } 476 | 477 | pub const FormattedInstallDir = struct { 478 | builder: *std.Build, 479 | install_dir: std.Build.InstallDir, 480 | 481 | pub fn format( 482 | formatter: FormattedInstallDir, 483 | comptime fmt: []const u8, 484 | options: std.fmt.FormatOptions, 485 | writer: anytype, 486 | ) !void { 487 | _ = fmt; 488 | _ = options; 489 | 490 | const builder = formatter.builder; 491 | const install_path = builder.getInstallPath(formatter.install_dir, "."); 492 | 493 | const dst_rel_path = builder.build_root.join(builder.allocator, &.{install_path}) catch unreachable; 494 | defer builder.allocator.free(dst_rel_path); // there's a chance this could get freed, with it (presumably) being the latest allocation. 495 | 496 | try writer.writeAll(dst_rel_path); 497 | } 498 | }; 499 | pub fn fmtInstallDir(builder: *std.Build, install_dir: std.Build.InstallDir) FormattedInstallDir { 500 | return .{ 501 | .builder = builder, 502 | .install_dir = install_dir, 503 | }; 504 | } 505 | 506 | pub const RunStepArg = struct { 507 | arg: std.Build.RunStep.Arg, 508 | builder: *std.Build, 509 | 510 | pub fn format( 511 | run_step_arg: RunStepArg, 512 | comptime fmt: []const u8, 513 | options: std.fmt.FormatOptions, 514 | writer: anytype, 515 | ) !void { 516 | _ = options; 517 | _ = fmt; 518 | switch (run_step_arg.arg) { 519 | .bytes => |bytes| try writer.print(""{s}"", .{bytes}), 520 | .file_source => |file_source| try writer.print("{}", .{formatting.FormattedFileSource{ .file_source = file_source, .builder = run_step_arg.builder }}), 521 | .artifact => |artifact| try writer.print("{}", .{formatting.Artifact{ .compile_step = artifact }}), 522 | .output => |out| try writer.print("{s}", .{out.basename}), 523 | } 524 | } 525 | }; 526 | }; 527 | --------------------------------------------------------------------------------