Skip to content

cURL Command Builder — Zig source

Compose a copy-paste curl command from a form: method, headers, body, auth and flags — values POSIX-quoted safely. Paste an existing command to import it back. Runs locally with a shareable link.

This is the Zig implementation — the same logic the interactive tool runs, in a shareable, citable form.

// curl-builder — structured input → copy-paste curl command + reverse parser.
// Zig port (canonical TS: src/lib/curl-builder.ts; Go twin: cli/curl-builder).
// Language: Zig 0.17 — unmanaged std.ArrayList (the 0.15+ API). Pass an
// arena allocator: every byte the results reference lives in it; deinit the
// arena to free. Validation errors are values in the result's `err` field
// (null on success); the error union is only for OOM. Fixed flag order:
// method (-X) → headers (-H, insertion order) → auth (-u) → data (-d) →
// booleans (-I -k -L --compressed) → the URL last.
//
// Test: zig test zig.zig

const std = @import("std");

pub const Header = struct { key: []const u8, value: []const u8 };
pub const Auth = struct { user: []const u8, password: []const u8 };

pub const CurlRequest = struct {
    url: []const u8 = "",
    method: ?[]const u8 = null, // null = GET
    headers: []const Header = &.{},
    data: ?[]const u8 = null, // null or "" → omitted
    auth: ?Auth = null, // null = absent
    head_only: bool = false,
    insecure: bool = false,
    follow_redirects: bool = false,
    compressed: bool = false,
};

pub const CurlBuildResult = struct {
    command: []const u8 = "",
    /// null when the build succeeded (TS: error: null).
    err: ?[]const u8 = null,
};

pub const ParsedCurl = struct { request: CurlRequest, unknown_flags: []const []const u8 };

pub const CurlParseResult = struct {
    parsed: ?ParsedCurl = null,
    err: ?[]const u8 = null,
};

const METHODS = [_][]const u8{ "GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS" };

fn isMethod(m: []const u8) bool {
    for (METHODS) |x| if (std.mem.eql(u8, x, m)) return true;
    return false;
}

fn isHeaderKey(k: []const u8) bool {
    if (k.len == 0) return false;
    for (k) |c| {
        const ok = (c >= 'A' and c <= 'Z') or (c >= 'a' and c <= 'z') or
            (c >= '0' and c <= '9') or c == '-';
        if (!ok) return false;
    }
    return true;
}

fn trimWs(s: []const u8) []const u8 {
    return std.mem.trim(u8, s, " \t\n\r\x0b\x0c");
}

/// POSIX single-quote a value: ' → '\'' (close, escaped quote, reopen).
pub fn shellQuote(a: std.mem.Allocator, value: []const u8) ![]u8 {
    var q: usize = 0;
    for (value) |c| {
        if (c == '\'') q += 1;
    }
    const out = try a.alloc(u8, value.len + 2 + q * 3);
    var i: usize = 0;
    out[i] = '\'';
    i += 1;
    for (value) |c| {
        if (c == '\'') {
            @memcpy(out[i .. i + 4], "'\\''");
            i += 4;
        } else {
            out[i] = c;
            i += 1;
        }
    }
    out[i] = '\'';
    return out[0 .. i + 1];
}

/// Build the curl command. URL required; method/header names validated.
pub fn buildCurlCommand(a: std.mem.Allocator, req: CurlRequest) !CurlBuildResult {
    const url = trimWs(req.url);
    if (url.len == 0) return .{ .err = "A URL is required" };
    const ok_scheme = std.mem.startsWith(u8, url, "http://") or
        std.mem.startsWith(u8, url, "https://") or (url.len > 0 and (url[0] == '/' or url[0] == '$'));
    if (!ok_scheme) return .{ .err = "URL must start with http://, https://, / or $ (a variable)" };
    const raw_method = req.method orelse "GET";
    const method = try a.dupe(u8, raw_method);
    for (method) |*c| c.* = std.ascii.toUpper(c.*);
    if (!isMethod(method)) {
        return .{ .err = try std.fmt.allocPrint(
            a,
            "unsupported method {s} (use GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS)",
            .{raw_method},
        ) };
    }
    for (req.headers) |h| {
        if (!isHeaderKey(h.key)) {
            return .{ .err = try std.fmt.allocPrint(
                a,
                "invalid header name \"{s}\" (letters, digits and hyphens only)",
                .{h.key},
            ) };
        }
    }
    var parts: std.ArrayList([]const u8) = .empty;
    defer parts.deinit(a);
    try parts.append(a, "curl");
    if (!std.mem.eql(u8, method, "GET"))
        try parts.append(a, try std.fmt.allocPrint(a, "-X {s}", .{method}));
    for (req.headers) |h| {
        const q = try shellQuote(a, try std.fmt.allocPrint(a, "{s}: {s}", .{ h.key, h.value }));
        try parts.append(a, try std.fmt.allocPrint(a, "-H {s}", .{q}));
    }
    if (req.auth) |auth| {
        const q = try shellQuote(a, try std.fmt.allocPrint(a, "{s}:{s}", .{ auth.user, auth.password }));
        try parts.append(a, try std.fmt.allocPrint(a, "-u {s}", .{q}));
    }
    if (req.data != null and req.data.?.len > 0) {
        const q = try shellQuote(a, req.data.?);
        try parts.append(a, try std.fmt.allocPrint(a, "-d {s}", .{q}));
    }
    if (req.head_only) try parts.append(a, "-I");
    if (req.insecure) try parts.append(a, "-k");
    if (req.follow_redirects) try parts.append(a, "-L");
    if (req.compressed) try parts.append(a, "--compressed");
    try parts.append(a, try shellQuote(a, url));
    return .{ .command = try std.mem.join(a, " ", parts.items), .err = null };
}

/// Shell word-split respecting single and double quotes. Words are duped.
fn splitWords(a: std.mem.Allocator, line: []const u8) ![][]const u8 {
    var words: std.ArrayList([]const u8) = .empty;
    var cur: std.ArrayList(u8) = .empty;
    defer cur.deinit(a);
    var quote: u8 = 0;
    var has = false;
    for (line) |ch| {
        if (quote != 0) {
            if (ch == quote) quote = 0 else try cur.append(a, ch);
        } else if (ch == '\'' or ch == '"') {
            quote = ch;
            has = true;
        } else if (ch == ' ' or ch == '\t') {
            if (cur.items.len > 0 or has) try words.append(a, try a.dupe(u8, cur.items));
            cur.clearRetainingCapacity();
            has = false;
        } else {
            try cur.append(a, ch);
            has = true;
        }
    }
    if (has) try words.append(a, try a.dupe(u8, cur.items));
    return words.toOwnedSlice(a);
}

/// Parse a curl command line back into a request (best effort, ordered).
pub fn parseCurlCommand(a: std.mem.Allocator, line: []const u8) !CurlParseResult {
    const trimmed = trimWs(line);
    if (trimmed.len == 0) return .{ .err = "A command is required" };
    // TS replace(/\\\n/g, ' '): a backslash-newline becomes one space.
    const joined = try a.alloc(u8, trimmed.len);
    var jn: usize = 0;
    var k: usize = 0;
    while (k < trimmed.len) : (k += 1) {
        if (trimmed[k] == '\\' and k + 1 < trimmed.len and trimmed[k + 1] == '\n') {
            joined[jn] = ' ';
            jn += 1;
            k += 1;
        } else {
            joined[jn] = trimmed[k];
            jn += 1;
        }
    }
    const words = try splitWords(a, joined[0..jn]);
    if (words.len == 0 or !std.mem.eql(u8, words[0], "curl"))
        return .{ .err = "command must start with curl" };
    var req = CurlRequest{};
    var headers: std.ArrayList(Header) = .empty;
    var flags: std.ArrayList([]const u8) = .empty;
    var i: usize = 1;
    while (i < words.len) : (i += 1) {
        const w = words[i];
        if (std.mem.eql(u8, w, "-X") or std.mem.eql(u8, w, "--request")) {
            i += 1;
            if (i < words.len) req.method = try a.dupe(u8, words[i]);
        } else if (std.mem.eql(u8, w, "-H") or std.mem.eql(u8, w, "--header")) {
            i += 1;
            if (i < words.len) {
                const raw = words[i];
                if (std.mem.indexOfScalar(u8, raw, ':')) |at| {
                    if (at > 0) try headers.append(a, .{
                        .key = try a.dupe(u8, trimWs(raw[0..at])),
                        .value = try a.dupe(u8, trimWs(raw[at + 1 ..])),
                    });
                }
            }
        } else if (std.mem.eql(u8, w, "-u") or std.mem.eql(u8, w, "--user")) {
            i += 1;
            if (i < words.len) {
                const raw = words[i];
                if (std.mem.indexOfScalar(u8, raw, ':')) |at| {
                    req.auth = .{
                        .user = try a.dupe(u8, raw[0..at]),
                        .password = try a.dupe(u8, raw[at + 1 ..]),
                    };
                } else {
                    req.auth = .{ .user = try a.dupe(u8, raw), .password = try a.dupe(u8, "") };
                }
            }
        } else if (std.mem.eql(u8, w, "-d") or std.mem.eql(u8, w, "--data")) {
            i += 1;
            if (i < words.len) req.data = try a.dupe(u8, words[i]);
        } else if (std.mem.eql(u8, w, "-I") or std.mem.eql(u8, w, "--head")) {
            req.head_only = true;
        } else if (std.mem.eql(u8, w, "-k") or std.mem.eql(u8, w, "--insecure")) {
            req.insecure = true;
        } else if (std.mem.eql(u8, w, "-L") or std.mem.eql(u8, w, "--location")) {
            req.follow_redirects = true;
        } else if (std.mem.eql(u8, w, "--compressed")) {
            req.compressed = true;
        } else if (w.len > 0 and w[0] == '-') {
            try flags.append(a, try a.dupe(u8, w));
        } else {
            req.url = try a.dupe(u8, w);
        }
    }
    if (req.url.len == 0) return .{ .err = "no URL found in command" };
    req.headers = try headers.toOwnedSlice(a);
    return .{ .parsed = .{ .request = req, .unknown_flags = try flags.toOwnedSlice(a) }, .err = null };
}

test "build: quoting and fixed flag order" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();
    const res = try buildCurlCommand(a, .{
        .url = " https://api.example.com ",
        .method = "post",
        .headers = &[_]Header{.{ .key = "X-Tag", .value = "it's" }},
        .data = "k=v",
        .auth = .{ .user = "u", .password = "p'w" },
        .head_only = true,
        .insecure = true,
        .follow_redirects = true,
        .compressed = true,
    });
    try std.testing.expect(res.err == null);
    try std.testing.expectEqualStrings(
        "curl -X POST -H 'X-Tag: it'\\''s' -u 'u:p'\\''w' -d 'k=v' -I -k -L --compressed 'https://api.example.com'",
        res.command,
    );
}

test "parse: round-trip, unknown flags, errors" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();
    const back = try parseCurlCommand(a, "curl -sL -X POST -H 'Accept: a\\b' -u 'u' -d '{\"x\":1}' -k -L --compressed 'https://x.dev'");
    try std.testing.expect(back.err == null);
    const req = back.parsed.?.request;
    try std.testing.expectEqualStrings("POST", req.method.?);
    try std.testing.expectEqualStrings("a\\b", req.headers[0].value);
    try std.testing.expectEqualStrings("u", req.auth.?.user);
    try std.testing.expectEqualStrings("", req.auth.?.password);
    try std.testing.expect(req.insecure and req.follow_redirects and req.compressed);
    try std.testing.expectEqualStrings("-sL", back.parsed.?.unknown_flags[0]);
    const empty = try parseCurlCommand(a, "   ");
    try std.testing.expectEqualStrings("A command is required", empty.err.?);
    const nourl = try parseCurlCommand(a, "curl -X POST");
    try std.testing.expectEqualStrings("no URL found in command", nourl.err.?);
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →