Skip to content

Commit

Permalink
fix: add std import when needed
Browse files Browse the repository at this point in the history
  • Loading branch information
nilslice committed Aug 22, 2024
1 parent a843985 commit c843319
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
18 changes: 17 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import ejs from "ejs";
import { getContext, helpers, Property } from "@dylibso/xtp-bindgen";
import { getContext, helpers, Property, XtpSchema } from "@dylibso/xtp-bindgen";

function toZigType(property: Property, pkg?: string): string {
if (property.$ref) return (pkg ? `${pkg}.` : "") + property.$ref.name;
Expand Down Expand Up @@ -39,6 +39,21 @@ function pointerToZigType(property: Property) {
return `*${typ}`;
}

function addStdImport(schema: XtpSchema) {
// in the generated `main.zig` this would include a reference to
// std.json.ArrayHashMap and std.json.Value, so we import "std".
const exportHasJsonObject = schema.exports.some((f) => {
return (f.input?.contentType === "application/json" &&
f.input.type === "object") ||
(f.output?.contentType === "application/json" &&
f.output.type === "object");
});

return exportHasJsonObject /* || others here */
? 'const std = @import("std");'
: null;
}

function makeStructName(s: string) {
const cap = s.charAt(0).toUpperCase();
if (s.charAt(0) === cap) {
Expand All @@ -57,6 +72,7 @@ export function render() {
toZigType,
pointerToZigType,
makeStructName,
addStdImport,
};

const output = ejs.render(tmpl, ctx);
Expand Down
1 change: 1 addition & 0 deletions template/src/main.zig.ejs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
<%- addStdImport(schema) %>
const schema = @import("schema.zig");
<%- schema.imports && schema.imports.length > 0 ? "const Host = schema.Host;" : null %>

Expand Down

0 comments on commit c843319

Please sign in to comment.