cURL Command Builder — Ruby 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 Ruby implementation — the same logic the interactive tool runs, in a shareable, citable form.
# frozen_string_literal: true
# curl-builder — structured input → copy-paste curl command + reverse parser.
# Ruby port (canonical TS: src/lib/curl-builder.ts; Go twin: cli/curl-builder).
# 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. Request hashes use snake_case keys (head_only,
# follow_redirects, ...; missing key = unset). Never raises — errors travel
# in the result hash (:error nil on success).
module CurlBuilder
module_function
METHODS = %w[GET POST PUT PATCH DELETE HEAD OPTIONS].freeze
# POSIX single-quote a value: ' → '\'' (close, escaped quote, reopen).
def shell_quote(value)
"'#{value.gsub("'") { "'\\''" }}'" # block form: the replacement is literal
end
# Build the curl command. URL required; method/header names validated.
def build_curl_command(req)
url = req[:url].to_s.strip
return { command: '', error: 'A URL is required' } if url.empty?
unless url.match?(/\A(?:https?:\/\/|\/|\$)/)
return { command: '', error: 'URL must start with http://, https://, / or $ (a variable)' }
end
method = req[:method]
method = method.nil? ? 'GET' : method.to_s.upcase
unless METHODS.include?(method)
return { command: '', error: "unsupported method #{req[:method]} (use #{METHODS.join(', ')})" }
end
headers = req[:headers] || []
headers.each do |h|
next if h[:key].match?(/\A[A-Za-z0-9-]+\z/)
return { command: '', error: "invalid header name \"#{h[:key]}\" (letters, digits and hyphens only)" }
end
parts = ['curl']
parts << "-X #{method}" unless method == 'GET'
headers.each { |h| parts << "-H #{shell_quote("#{h[:key]}: #{h[:value]}")}" }
if (auth = req[:auth])
parts << "-u #{shell_quote("#{auth[:user]}:#{auth[:password]}")}"
end
data = req[:data]
parts << "-d #{shell_quote(data)}" unless data.nil? || data.empty?
parts << '-I' if req[:head_only]
parts << '-k' if req[:insecure]
parts << '-L' if req[:follow_redirects]
parts << '--compressed' if req[:compressed]
parts << shell_quote(url)
{ command: parts.join(' '), error: nil }
end
# Shell word-split respecting single and double quotes.
def split_words(line)
words = []
cur = +''
quote = nil
has = false
line.each_char do |ch|
if quote
if ch == quote
quote = nil
else
cur << ch
end
elsif ch == "'" || ch == '"'
quote = ch
has = true
elsif ch == ' ' || ch == "\t"
words << cur if !cur.empty? || has
cur = +''
has = false
else
cur << ch
has = true
end
end
words << cur if has # any accumulated characters imply has
words
end
# Parse a curl command line back into a request (best effort, ordered).
def parse_curl_command(line)
trimmed = line.strip
return { parsed: nil, error: 'A command is required' } if trimmed.empty?
words = split_words(trimmed.gsub(/\\\n/, ' '))
return { parsed: nil, error: 'command must start with curl' } if words[0] != 'curl'
req = { url: '', headers: [] }
unknown_flags = []
i = 1
while i < words.length
w = words[i]
case w
when '-X', '--request'
i += 1
req[:method] = words[i] if i < words.length
when '-H', '--header'
i += 1
if i < words.length
raw = words[i]
at = raw.index(':')
req[:headers] << { key: raw[0...at].strip, value: raw[(at + 1)..].strip } if at && at.positive?
end
when '-u', '--user'
i += 1
if i < words.length
raw = words[i]
at = raw.index(':')
req[:auth] = at ? { user: raw[0...at], password: raw[(at + 1)..] } : { user: raw, password: '' }
end
when '-d', '--data'
i += 1
req[:data] = words[i] if i < words.length
when '-I', '--head' then req[:head_only] = true
when '-k', '--insecure' then req[:insecure] = true
when '-L', '--location' then req[:follow_redirects] = true
when '--compressed' then req[:compressed] = true
else
if w.start_with?('-')
unknown_flags << w
else
req[:url] = w
end
end
i += 1
end
return { parsed: nil, error: 'no URL found in command' } if req[:url].empty?
{ parsed: { request: req, unknown_flags: unknown_flags }, error: nil }
end
end
# Example:
# CurlBuilder.shell_quote("it's") => "'it'\\''s'"
# CurlBuilder.build_curl_command(url: 'https://api.example.com', method: 'post',
# headers: [{ key: 'X-Tag', value: "it's" }], data: 'k=v')[:command]
# => "curl -X POST -H 'X-Tag: it'\\''s' -d 'k=v' 'https://api.example.com'"
# CurlBuilder.parse_curl_command("curl -sL --compressed 'https://x.dev'")
# => { parsed: { request: { url: 'https://x.dev', headers: [], compressed: true }, unknown_flags: ['-sL'] }, error: nil }
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 →