cURL Command Builder — Rust 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 Rust implementation — the same logic the interactive tool runs, in a shareable, citable form.
//! curl-builder — structured input → copy-paste curl command + reverse parser.
//! Rust port (canonical TS: `src/lib/curl-builder.ts`; Go twin:
//! `cli/curl-builder`). Standard library only (no crates): composes a
//! copy-paste curl command from structured input and parses an existing
//! command back into the structure (round-trip). Values are POSIX
//! single-quoted (`'` → `'\''`) — safe for POSIX shells. Fixed flag order:
//! method (-X) → headers (-H, insertion order) → auth (-u) → data (-d) →
//! booleans (-I -k -L --compressed) → the URL last. Never panics — errors
//! travel in the result's `error` (None on success).
#[derive(Debug, Default, Clone)]
pub struct Header {
pub key: String,
pub value: String,
}
#[derive(Debug, Default, Clone)]
pub struct Auth {
pub user: String,
pub password: String,
}
#[derive(Debug, Default, Clone)]
pub struct CurlRequest {
pub url: String,
pub method: Option<String>, // None = GET
pub headers: Vec<Header>, // insertion order kept
pub data: Option<String>, // None or "" → omitted
pub auth: Option<Auth>, // None = absent
pub head_only: bool,
pub insecure: bool,
pub follow_redirects: bool,
pub compressed: bool,
}
#[derive(Debug, Default)]
pub struct CurlBuildResult {
pub command: String,
pub error: Option<String>,
}
#[derive(Debug, Default)]
pub struct ParsedCurl {
pub request: CurlRequest,
pub unknown_flags: Vec<String>,
}
#[derive(Debug, Default)]
pub struct CurlParseResult {
pub parsed: Option<ParsedCurl>,
pub error: Option<String>,
}
const METHODS: [&str; 7] = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"];
fn is_header_key(k: &str) -> bool {
!k.is_empty() && k.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'-')
}
/// POSIX single-quote a value: ' → '\'' (close, escaped quote, reopen).
pub fn shell_quote(value: &str) -> String {
format!("'{}'", value.replace('\'', "'\\''"))
}
/// Build the curl command. URL required; method/header names validated.
pub fn build_curl_command(req: &CurlRequest) -> CurlBuildResult {
let url = req.url.trim();
if url.is_empty() {
return CurlBuildResult { error: Some("A URL is required".into()), ..Default::default() };
}
let ok_scheme = url.starts_with("http://")
|| url.starts_with("https://")
|| url.starts_with('/')
|| url.starts_with('$');
if !ok_scheme {
return CurlBuildResult {
error: Some("URL must start with http://, https://, / or $ (a variable)".into()),
..Default::default()
};
}
let raw_method = req.method.as_deref().unwrap_or("GET");
let method = raw_method.to_uppercase();
if !METHODS.contains(&method.as_str()) {
return CurlBuildResult {
error: Some(format!("unsupported method {raw_method} (use {})", METHODS.join(", "))),
..Default::default()
};
}
for h in &req.headers {
if !is_header_key(&h.key) {
return CurlBuildResult {
error: Some(format!("invalid header name \"{}\" (letters, digits and hyphens only)", h.key)),
..Default::default()
};
}
}
let mut parts: Vec<String> = vec!["curl".into()];
if method != "GET" {
parts.push(format!("-X {method}"));
}
for h in &req.headers {
parts.push(format!("-H {}", shell_quote(&format!("{}: {}", h.key, h.value))));
}
if let Some(a) = &req.auth {
parts.push(format!("-u {}", shell_quote(&format!("{}:{}", a.user, a.password))));
}
if let Some(d) = &req.data {
if !d.is_empty() {
parts.push(format!("-d {}", shell_quote(d)));
}
}
if req.head_only {
parts.push("-I".into());
}
if req.insecure {
parts.push("-k".into());
}
if req.follow_redirects {
parts.push("-L".into());
}
if req.compressed {
parts.push("--compressed".into());
}
parts.push(shell_quote(url));
CurlBuildResult { command: parts.join(" "), error: None }
}
/// Shell word-split respecting single and double quotes.
fn split_words(line: &str) -> Vec<String> {
let mut words = Vec::new();
let mut cur = String::new();
let mut quote: Option<char> = None;
let mut has = false;
for ch in line.chars() {
if let Some(q) = quote {
if ch == q {
quote = None;
} else {
cur.push(ch);
}
} else if ch == '\'' || ch == '"' {
quote = Some(ch);
has = true;
} else if ch == ' ' || ch == '\t' {
if !cur.is_empty() || has {
words.push(std::mem::take(&mut cur));
}
has = false;
} else {
cur.push(ch);
has = true;
}
}
if has {
words.push(cur); // any accumulated characters imply has
}
words
}
/// Parse a curl command line back into a request (best effort, ordered).
pub fn parse_curl_command(line: &str) -> CurlParseResult {
let trimmed = line.trim();
if trimmed.is_empty() {
return CurlParseResult { error: Some("A command is required".into()), ..Default::default() };
}
// TS replace(/\\\n/g, ' '): a backslash-newline becomes one space.
let words = split_words(&trimmed.replace("\\\n", " "));
if words.first().map(String::as_str) != Some("curl") {
return CurlParseResult { error: Some("command must start with curl".into()), ..Default::default() };
}
let mut req = CurlRequest::default();
let mut unknown_flags = Vec::new();
let mut i = 1;
while i < words.len() {
let w = words[i].as_str();
if w == "-X" || w == "--request" {
i += 1;
if i < words.len() {
req.method = Some(words[i].clone());
}
} else if w == "-H" || w == "--header" {
i += 1;
if i < words.len() {
let raw = &words[i];
if let Some(at) = raw.find(':') {
if at > 0 {
req.headers.push(Header {
key: raw[..at].trim().to_string(),
value: raw[at + 1..].trim().to_string(),
});
}
}
}
} else if w == "-u" || w == "--user" {
i += 1;
if i < words.len() {
let raw = &words[i];
req.auth = Some(match raw.find(':') {
Some(at) => Auth { user: raw[..at].to_string(), password: raw[at + 1..].to_string() },
None => Auth { user: raw.clone(), password: String::new() },
});
}
} else if w == "-d" || w == "--data" {
i += 1;
if i < words.len() {
req.data = Some(words[i].clone());
}
} else if w == "-I" || w == "--head" {
req.head_only = true;
} else if w == "-k" || w == "--insecure" {
req.insecure = true;
} else if w == "-L" || w == "--location" {
req.follow_redirects = true;
} else if w == "--compressed" {
req.compressed = true;
} else if w.starts_with('-') {
unknown_flags.push(words[i].clone());
} else {
req.url = words[i].clone();
}
i += 1;
}
if req.url.is_empty() {
return CurlParseResult { error: Some("no URL found in command".into()), ..Default::default() };
}
CurlParseResult { parsed: Some(ParsedCurl { request: req, unknown_flags }), error: None }
}
// Example:
// shell_quote("it's") → "'it'\\''s'"
// build_curl_command(&CurlRequest { url: "https://api.example.com".into(),
// method: Some("post".into()), headers: vec![Header { key: "X-Tag".into(), value: "it's".into() }],
// data: Some("k=v".into()), ..Default::default() }).command
// → "curl -X POST -H 'X-Tag: it'\\''s' -d 'k=v' 'https://api.example.com'"
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 →