Skip to content

cURL Command Builder — Kotlin 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 Kotlin implementation — the same logic the interactive tool runs, in a shareable, citable form.

// curl-builder — structured input → copy-paste curl command + reverse parser.
// Kotlin port (canonical TS: src/lib/curl-builder.ts; Go twin:
// cli/curl-builder). Standard library only. Composes a copy-paste curl
// command from structured input; also parses an existing command back into
// the structure (round-trip). Values are single-quoted with embedded quotes
// escaped (' → '\'') — safe for POSIX shells. The flag order is fixed and
// deterministic: method (-X) → headers (-H, insertion order) → auth (-u) →
// data (-d) → boolean flags (-I -k -L --compressed) → the URL last. Absent
// optional fields are null; null data is treated like "" (omitted). Never
// throws — errors travel in the result's nullable error (null on success).

data class CurlHeader(val key: String, val value: String)
data class CurlAuth(val user: String, val password: String)

data class CurlRequest(
    var url: String = "",
    var method: String? = null,                                // null = GET
    var headers: MutableList<CurlHeader> = mutableListOf(),    // insertion order kept
    var data: String? = null,                                  // null or "" → omitted
    var auth: CurlAuth? = null,                                // null = absent
    var headOnly: Boolean = false,
    var insecure: Boolean = false,
    var followRedirects: Boolean = false,
    var compressed: Boolean = false,
)

data class CurlBuildResult(val command: String, val error: String?)
data class ParsedCurl(val request: CurlRequest, val unknownFlags: List<String>)
data class CurlParseResult(val parsed: ParsedCurl?, val error: String?)

private val METHODS = listOf("GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS")

/** POSIX single-quote a value: ' → '\'' (close, escaped quote, reopen). */
fun shellQuote(value: String): String = "'" + value.replace("'", "'\\''") + "'"

private fun isHeaderKey(k: String): Boolean =
    k.isNotEmpty() && k.all { it in 'A'..'Z' || it in 'a'..'z' || it in '0'..'9' || it == '-' }

/** Build the curl command. URL required; method/header names validated. */
fun buildCurlCommand(req: CurlRequest): CurlBuildResult {
    val url = req.url.trim()
    if (url.isEmpty()) return CurlBuildResult("", "A URL is required")
    val okScheme = url.startsWith("http://") || url.startsWith("https://") ||
        url.startsWith("/") || url.startsWith("$")
    if (!okScheme) return CurlBuildResult("", "URL must start with http://, https://, / or $ (a variable)")
    val rawMethod = req.method ?: "GET"
    val method = rawMethod.uppercase()
    if (method !in METHODS)
        return CurlBuildResult("", "unsupported method ${req.method} (use ${METHODS.joinToString(", ")})")
    for (h in req.headers) {
        if (!isHeaderKey(h.key))
            return CurlBuildResult("", "invalid header name \"${h.key}\" (letters, digits and hyphens only)")
    }
    val parts = mutableListOf("curl")
    if (method != "GET") parts += "-X $method"
    for (h in req.headers) parts += "-H " + shellQuote("${h.key}: ${h.value}")
    req.auth?.let { parts += "-u " + shellQuote("${it.user}:${it.password}") }
    val data = req.data
    if (data != null && data.isNotEmpty()) parts += "-d " + shellQuote(data)
    if (req.headOnly) parts += "-I"
    if (req.insecure) parts += "-k"
    if (req.followRedirects) parts += "-L"
    if (req.compressed) parts += "--compressed"
    parts += shellQuote(url)
    return CurlBuildResult(parts.joinToString(" "), null)
}

/** Shell word-split respecting single and double quotes. */
fun splitWords(line: String): List<String> {
    val words = mutableListOf<String>()
    var cur = ""
    var quote: Char? = null
    var has = false
    for (ch in line) {
        if (quote != null) {
            if (ch == quote) quote = null else cur += ch
        } else if (ch == '\'' || ch == '"') {
            quote = ch
            has = true
        } else if (ch == ' ' || ch == '\t') {
            if (cur.isNotEmpty() || has) words += cur
            cur = ""
            has = false
        } else {
            cur += ch
            has = true
        }
    }
    if (has) words += cur // any accumulated characters imply has
    return words
}

/** Parse a curl command line back into a request (best effort, ordered). */
fun parseCurlCommand(line: String): CurlParseResult {
    val trimmed = line.trim()
    if (trimmed.isEmpty()) return CurlParseResult(null, "A command is required")
    val words = splitWords(trimmed.replace("\\\n", " "))
    if (words.firstOrNull() != "curl") return CurlParseResult(null, "command must start with curl")
    val req = CurlRequest()
    val unknown = mutableListOf<String>()
    var i = 1
    while (i < words.size) {
        val w = words[i]
        when (w) {
            "-X", "--request" -> { i++; if (i < words.size) req.method = words[i] }
            "-H", "--header" -> {
                i++
                if (i < words.size) {
                    val raw = words[i]
                    val at = raw.indexOf(':')
                    if (at > 0) req.headers += CurlHeader(raw.substring(0, at).trim(), raw.substring(at + 1).trim())
                }
            }
            "-u", "--user" -> {
                i++
                if (i < words.size) {
                    val raw = words[i]
                    val at = raw.indexOf(':')
                    req.auth = if (at < 0) CurlAuth(raw, "") else CurlAuth(raw.substring(0, at), raw.substring(at + 1))
                }
            }
            "-d", "--data" -> { i++; if (i < words.size) req.data = words[i] }
            "-I", "--head" -> req.headOnly = true
            "-k", "--insecure" -> req.insecure = true
            "-L", "--location" -> req.followRedirects = true
            "--compressed" -> req.compressed = true
            else -> if (w.startsWith("-")) unknown += w else req.url = w
        }
        i++
    }
    if (req.url.isEmpty()) return CurlParseResult(null, "no URL found in command")
    return CurlParseResult(ParsedCurl(req, unknown), null)
}

// Example:
// shellQuote("it's") → "'it'\\''s'"
// buildCurlCommand(CurlRequest(url = "https://api.example.com", method = "post",
//     headers = mutableListOf(CurlHeader("X-Tag", "it's")), data = "k=v")).command
// → "curl -X POST -H 'X-Tag: it'\\''s' -d 'k=v' 'https://api.example.com'"
// parseCurlCommand("curl -sL --compressed 'https://x.dev'")
// → ParsedCurl(request = CurlRequest(url = "https://x.dev", compressed = true), unknownFlags = ["-sL"])

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 →