//! Non-interactive SSH command handlers. //! //! When a user runs `ssh cli.makenot.work `, the exec_request handler //! dispatches to this module. All commands write output to a byte buffer and //! return it for the SSH channel. use std::fmt::Write as _; use crate::api::{MnwApiClient, UserInfo}; use crate::format; use crate::staging; /// Sanitize an API error for display to SSH clients. /// /// Strips raw response bodies (HTML error pages, stack traces) that may leak /// from anyhow error chains. Keeps the high-level context + HTTP status code /// but drops everything after ` — ` (the body separator our API client uses). pub(crate) fn sanitize_api_error(e: &anyhow::Error) -> String { let msg = e.to_string(); // Our API client formats errors as "context: HTTP 500 — ". // Keep the part before the body separator. if let Some(idx) = msg.find(" \u{2014} ") { return msg[..idx].to_string(); } // For connection/timeout errors, return a generic message. if msg.contains("connect") || msg.contains("timed out") || msg.contains("dns") { return "Service temporarily unavailable".to_string(); } // Fallback: return the first line only (avoid multi-line leaks). msg.lines().next().unwrap_or("Unknown error").to_string() } /// Execute a non-interactive command and return the output bytes. pub(crate) async fn execute(command_line: &str, user: &UserInfo, api: &MnwApiClient) -> Vec { let parts: Vec<&str> = command_line.split_whitespace().collect(); if parts.is_empty() { return help_text(); } let json = parts.contains(&"--json"); let parts: Vec<&str> = parts.into_iter().filter(|p| *p != "--json").collect(); match parts[0] { "project" => match parts.get(1).copied() { Some("create") => { let title = extract_flag(&parts, &["--title", "-t"]).unwrap_or_default(); let ptype = extract_flag(&parts, &["--type"]).unwrap_or_else(|| "digital".to_string()); let desc = extract_flag(&parts, &["--description", "--desc", "-d"]); cmd_project_create(user, api, &title, &ptype, desc.as_deref()).await } _ => b"Usage: project create --title \"Name\" [--type audio|digital|video|mixed|subscription] [--description \"...\"]\r\n".to_vec(), }, "upload" => { b"Pipe uploads use stdin. Example:\r\n cat file.wav | ssh cli.makenot.work upload --filename track.wav --project my-project\r\n".to_vec() } "projects" => cmd_projects(user, api, json).await, "analytics" => { let range = parts .iter() .find_map(|p| p.strip_prefix("--range=")) .unwrap_or("30d"); cmd_analytics(user, api, range, json).await } "transactions" => cmd_transactions(user, api, json).await, "export" if parts.get(1) == Some(&"sales") => cmd_export_sales(user, api).await, "promo" => match parts.get(1).copied() { Some("list") => cmd_promo_list(user, api, json).await, Some("create") => { let code = parts.get(2).unwrap_or(&""); let pct = parts.get(3).unwrap_or(&"0"); cmd_promo_create(user, api, code, pct).await } _ => b"Usage: promo list | promo create CODE DISCOUNT_PCT\r\n".to_vec(), }, "blog" => match parts.get(1).copied() { Some("list") => { let slug = parts.get(2).unwrap_or(&""); cmd_blog_list(user, api, slug, json).await } _ => b"Usage: blog list \r\n".to_vec(), }, "broadcast" => { let subject = extract_flag(&parts, &["--subject", "-s"]).unwrap_or_default(); let body = extract_flag(&parts, &["--body", "-b"]).unwrap_or_default(); cmd_broadcast(user, api, &subject, &body).await } "collections" => cmd_collections(user, api, json).await, "domain" => match parts.get(1).copied() { Some("add") => { let domain = parts.get(2).unwrap_or(&""); cmd_domain_add(user, api, domain).await } Some("verify") => cmd_domain_verify(user, api).await, Some("remove") => cmd_domain_remove(user, api).await, _ => cmd_domain_show(user, api).await, }, "repo" => match parts.get(1).copied() { Some("list") => cmd_repo_list(user, api, json).await, Some("info") => cmd_repo_info(user, api, parts.get(2).unwrap_or(&""), json).await, Some("set-visibility") => { cmd_repo_set_visibility( user, api, parts.get(2).unwrap_or(&""), parts.get(3).unwrap_or(&""), ) .await } // The description is the rest of the line, so it is rejoined rather // than read from one slot: a description is prose and almost always // has a space in it. Some("set-description") => { let desc = parts.get(3..).map(|r| r.join(" ")).unwrap_or_default(); cmd_repo_set_description( user, api, parts.get(2).unwrap_or(&""), unquote(&desc), ) .await } // --confirm is required and deliberately not inferable. This is the // only verb here that destroys anything. Some("delete") => { if parts.contains(&"--confirm") { cmd_repo_delete(user, api, parts.get(2).unwrap_or(&"")).await } else { b"repo delete requires --confirm\r\nUsage: repo delete --confirm\r\n" .to_vec() } } _ => b"Usage: repo list | info NAME | set-visibility NAME public|unlisted|private | set-description NAME TEXT | delete NAME --confirm\r\n".to_vec(), }, "key" => match parts.get(1).copied() { Some("list") => cmd_key_list(user, api, json).await, Some("rm") => cmd_key_remove(user, api, parts.get(2).unwrap_or(&"")).await, _ => b"Usage: key list | key rm FINGERPRINT\r\n".to_vec(), }, "help" | "--help" | "-h" => help_text(), other => format!("Unknown command: {other}\r\nRun without arguments for usage help.\r\n") .into_bytes(), } } async fn cmd_project_create( user: &UserInfo, api: &MnwApiClient, title: &str, project_type: &str, description: Option<&str>, ) -> Vec { if title.is_empty() { return b"Usage: project create --title \"Name\" [--type audio|digital|video|mixed|subscription] [--description \"...\"]\r\n".to_vec(); } if !user.can_create_projects { return b"Error: your account cannot create projects. Upgrade your tier at makenot.work/pricing\r\n".to_vec(); } match api .create_project(&user.user_id, title, project_type, description) .await { Ok(p) => format!( "Created project: {} (slug: {}, type: {})\r\n", p.title, p.slug, p.project_type ) .into_bytes(), Err(e) => format!("Error: {}\r\n", sanitize_api_error(&e)).into_bytes(), } } async fn cmd_projects(user: &UserInfo, api: &MnwApiClient, json: bool) -> Vec { match api.get_projects(&user.user_id).await { Ok(projects) => { if json { return serde_json::to_vec_pretty(&projects).unwrap_or_default(); } if projects.is_empty() { return b"No projects.\r\n".to_vec(); } let mut out = format!( "{:<30} {:<12} {:<8} {:<6} {:<15}\r\n", "Title", "Type", "Status", "Items", "Revenue" ); out.push_str(&"-".repeat(75)); out.push_str("\r\n"); for p in &projects { let status = if p.is_public { "public" } else { "draft" }; let revenue = p.revenue().display_compact(user.settlement_currency); write!( out, "{:<30} {:<12} {:<8} {:<6} {:<15}\r\n", truncate(&p.title, 29), p.project_type, status, p.item_count, revenue, ) .unwrap(); } out.into_bytes() } Err(e) => format!("Error: {}\r\n", sanitize_api_error(&e)).into_bytes(), } } async fn cmd_analytics(user: &UserInfo, api: &MnwApiClient, range: &str, json: bool) -> Vec { match api.get_analytics(&user.user_id, range).await { Ok(data) => { if json { return serde_json::to_vec_pretty(&data).unwrap_or_default(); } let mut out = String::new(); write!(out, "Analytics ({range})\r\n\r\n").unwrap(); let rev = format::format_cents(data.current_revenue_cents, user.settlement_currency); let prev_rev = format::format_cents(data.previous_revenue_cents, user.settlement_currency); write!(out, "Revenue: {rev} (prev: {prev_rev})\r\n").unwrap(); write!( out, "Sales: {} (prev: {})\r\n", data.current_sales, data.previous_sales ) .unwrap(); write!( out, "Followers: {} (prev: {})\r\n", data.current_followers, data.previous_followers ) .unwrap(); if !data.top_projects.is_empty() { out.push_str("\r\nTop Projects:\r\n"); for p in &data.top_projects { write!( out, " {:<30} {}\r\n", truncate(&p.title, 29), p.revenue().display(user.settlement_currency) ) .unwrap(); } } out.into_bytes() } Err(e) => format!("Error: {}\r\n", sanitize_api_error(&e)).into_bytes(), } } async fn cmd_transactions(user: &UserInfo, api: &MnwApiClient, json: bool) -> Vec { match api.get_transactions(&user.user_id).await { Ok(txs) => { if json { return serde_json::to_vec_pretty(&txs).unwrap_or_default(); } if txs.is_empty() { return b"No transactions.\r\n".to_vec(); } let mut out = format!( "{:<30} {:<10} {:<12} {:<12}\r\n", "Item", "Amount", "Status", "Date" ); out.push_str(&"-".repeat(66)); out.push_str("\r\n"); for tx in &txs { let title = tx.item_title.as_deref().unwrap_or("--"); let amount = format::format_cents(i64::from(tx.amount_cents), user.settlement_currency); let date = tx.created_at.get(..10).unwrap_or(&tx.created_at); write!( out, "{:<30} {:<10} {:<12} {:<12}\r\n", truncate(title, 29), amount, tx.status, date, ) .unwrap(); } out.into_bytes() } Err(e) => format!("Error: {}\r\n", sanitize_api_error(&e)).into_bytes(), } } async fn cmd_export_sales(user: &UserInfo, api: &MnwApiClient) -> Vec { match api.export_sales_csv(&user.user_id).await { Ok(result) => result.csv.into_bytes(), Err(e) => format!("Error: {}\r\n", sanitize_api_error(&e)).into_bytes(), } } async fn cmd_promo_list(user: &UserInfo, api: &MnwApiClient, json: bool) -> Vec { match api.list_promo_codes(&user.user_id).await { Ok(codes) => { if json { return serde_json::to_vec_pretty(&codes).unwrap_or_default(); } if codes.is_empty() { return b"No promo codes.\r\n".to_vec(); } let mut out = format!( "{:<20} {:<16} {:<20} {:<10}\r\n", "Code", "Discount", "Scope", "Uses" ); out.push_str(&"-".repeat(68)); out.push_str("\r\n"); for c in &codes { let discount = match (c.discount_type.as_deref(), c.discount_value) { (Some("percentage"), Some(v)) => format!("{v}% off"), (Some("fixed"), Some(v)) => format!( "{} off", format::format_cents(i64::from(v), user.settlement_currency) ), _ => "Free".to_string(), }; let scope = c .item_title .as_deref() .or(c.project_title.as_deref()) .unwrap_or("All items"); let uses = match c.max_uses { Some(max) => format!("{}/{}", c.use_count, max), None => c.use_count.to_string(), }; write!( out, "{:<20} {:<16} {:<20} {:<10}\r\n", truncate(&c.code, 19), discount, truncate(scope, 19), uses, ) .unwrap(); } out.into_bytes() } Err(e) => format!("Error: {}\r\n", sanitize_api_error(&e)).into_bytes(), } } async fn cmd_promo_create(user: &UserInfo, api: &MnwApiClient, code: &str, pct: &str) -> Vec { if code.is_empty() { return b"Usage: promo create CODE DISCOUNT_PCT\r\n".to_vec(); } let discount: i32 = pct.parse().unwrap_or(0); match api .create_promo_code(&user.user_id, code, "percentage", discount, None, None) .await { Ok(_) => format!("Created promo code: {code} ({discount}% off)\r\n").into_bytes(), Err(e) => format!("Error: {}\r\n", sanitize_api_error(&e)).into_bytes(), } } async fn cmd_blog_list(user: &UserInfo, api: &MnwApiClient, slug: &str, json: bool) -> Vec { if slug.is_empty() { return b"Usage: blog list \r\n".to_vec(); } // Find the project by slug let projects = match api.get_projects(&user.user_id).await { Ok(p) => p, Err(e) => return format!("Error: {}\r\n", sanitize_api_error(&e)).into_bytes(), }; let Some(project) = projects.iter().find(|p| p.slug == slug) else { return format!("Project not found: {slug}\r\n").into_bytes(); }; match api.list_blog_posts(&user.user_id, &project.id).await { Ok(posts) => { if json { return serde_json::to_vec_pretty(&posts).unwrap_or_default(); } if posts.is_empty() { return b"No blog posts.\r\n".to_vec(); } let mut out = format!( "{:<30} {:<20} {:<10} {:<12}\r\n", "Title", "Slug", "Status", "Created" ); out.push_str(&"-".repeat(74)); out.push_str("\r\n"); for p in &posts { let status = if p.is_published { "published" } else { "draft" }; let date = p.created_at.get(..10).unwrap_or(&p.created_at); write!( out, "{:<30} {:<20} {:<10} {:<12}\r\n", truncate(&p.title, 29), truncate(&p.slug, 19), status, date, ) .unwrap(); } out.into_bytes() } Err(e) => format!("Error: {}\r\n", sanitize_api_error(&e)).into_bytes(), } } async fn cmd_broadcast(user: &UserInfo, api: &MnwApiClient, subject: &str, body: &str) -> Vec { if subject.is_empty() || body.is_empty() { return b"Usage: broadcast --subject \"Subject line\" --body \"Body text\"\r\n\ \x20 Aliases: -s, -b\r\n\ \x20 Sends an email to all your followers (1/24h limit).\r\n" .to_vec(); } match api.send_broadcast(&user.user_id, subject, body).await { Ok(result) => format!( "Broadcast sent to {} followers.\r\n", result.recipient_count ) .into_bytes(), Err(e) => format!("Error: {}\r\n", sanitize_api_error(&e)).into_bytes(), } } async fn cmd_collections(user: &UserInfo, api: &MnwApiClient, json: bool) -> Vec { match api.list_collections(&user.user_id).await { Ok(collections) => { if json { return serde_json::to_vec_pretty(&collections).unwrap_or_default(); } if collections.is_empty() { return b"No collections.\r\n".to_vec(); } let mut out = format!( "{:<25} {:<25} {:<8} {:<6}\r\n", "Title", "Slug", "Status", "Items" ); out.push_str(&"-".repeat(66)); out.push_str("\r\n"); for c in &collections { let status = if c.is_public { "public" } else { "draft" }; write!( out, "{:<25} {:<25} {:<8} {:<6}\r\n", truncate(&c.title, 24), truncate(&c.slug, 24), status, c.item_count, ) .unwrap(); } out.into_bytes() } Err(e) => format!("Error: {}\r\n", sanitize_api_error(&e)).into_bytes(), } } async fn cmd_domain_show(user: &UserInfo, api: &MnwApiClient) -> Vec { match api.get_domain(&user.user_id).await { Ok(Some(d)) => { let status = if d.verified { "verified" } else { "pending" }; let mut out = format!("Domain: {} ({})\r\n", d.domain, status); if !d.verified && let Some(ref instr) = d.instructions { write!(out, "{instr}\r\n").unwrap(); } out.into_bytes() } Ok(None) => b"No custom domain configured.\r\nUsage: domain add \r\n".to_vec(), Err(e) => format!("Error: {}\r\n", sanitize_api_error(&e)).into_bytes(), } } async fn cmd_domain_add(user: &UserInfo, api: &MnwApiClient, domain: &str) -> Vec { if domain.is_empty() { return b"Usage: domain add \r\n".to_vec(); } match api.add_domain(&user.user_id, domain).await { Ok(d) => { let mut out = format!("Domain added: {}\r\n", d.domain); if let Some(ref instr) = d.instructions { write!(out, "{instr}\r\n").unwrap(); } out.push_str("Run `domain verify` after adding the DNS record.\r\n"); out.into_bytes() } Err(e) => format!("Error: {}\r\n", sanitize_api_error(&e)).into_bytes(), } } async fn cmd_domain_verify(user: &UserInfo, api: &MnwApiClient) -> Vec { match api.verify_domain(&user.user_id).await { Ok(result) => format!("{}\r\n", result.message).into_bytes(), Err(e) => format!("Error: {}\r\n", sanitize_api_error(&e)).into_bytes(), } } async fn cmd_domain_remove(user: &UserInfo, api: &MnwApiClient) -> Vec { match api.remove_domain(&user.user_id).await { Ok(()) => b"Domain removed.\r\n".to_vec(), Err(e) => format!("Error: {}\r\n", sanitize_api_error(&e)).into_bytes(), } } /// Execute a pipe-mode file upload (called from handler after stdin EOF). pub(crate) async fn execute_pipe_upload( api: &MnwApiClient, upload: crate::ssh::handler::PipeUpload, ) -> anyhow::Result { let user = &upload.user; if upload.data.is_empty() { anyhow::bail!("no data received on stdin"); } let ext = upload .filename .rsplit('.') .next() .unwrap_or("") .to_lowercase(); let classification = staging::classify_extension(&ext) .ok_or_else(|| anyhow::anyhow!( "unsupported file type: .{ext}\r\nSupported: mp3, wav, flac, ogg, m4a, aac, zip, dmg, exe, appimage, deb, clap, vst3" ))?; // Find project by slug let projects = api.get_projects(&user.user_id).await?; let project = projects .iter() .find(|p| p.slug == upload.project_slug) .ok_or_else(|| anyhow::anyhow!("project not found: {}", upload.project_slug))?; // Create item let item = api .create_item( &user.user_id, &project.id, &upload.title, classification.item_type, upload.price_cents, ) .await?; // Presign upload let presign = api .presign_upload( &user.user_id, &item.item_id, classification.file_type, &upload.filename, classification.content_type, ) .await?; // Upload data directly to S3 let resp = crate::tls::builder() .build()? .put(&presign.upload_url) .header("content-type", classification.content_type) .body(upload.data) .send() .await?; if !resp.status().is_success() { anyhow::bail!("S3 upload failed: HTTP {}", resp.status()); } // Confirm api.confirm_upload( &user.user_id, &item.item_id, classification.file_type, &presign.s3_key, ) .await?; // Publish api.publish_item(&user.user_id, &item.item_id).await?; Ok(format!( "Uploaded and published: {} ({}, {})\r\n", upload.title, staging::format_bytes(resp.content_length().unwrap_or(0)), classification.item_type, )) } // ── Git repositories and SSH keys ── // // These verbs existed in the server's git_ssh.rs, reachable only through the // sshd `command=` path that the live SSH front door does not use. They are // here now because this is the door people actually knock on. async fn cmd_repo_list(user: &UserInfo, api: &MnwApiClient, json: bool) -> Vec { match api.repo_list(&user.user_id).await { Ok(repos) => { if json { return serde_json::to_vec_pretty(&repos).unwrap_or_default(); } if repos.is_empty() { return b"No repositories.\r\n".to_vec(); } let mut out = format!("{:<30} {:<10} {}\r\n", "Name", "Visibility", "Description"); out.push_str(&"-".repeat(70)); out.push_str("\r\n"); for r in &repos { let desc = if r.description.is_empty() { "-" } else { truncate(&r.description, 28) }; write!( out, "{:<30} {:<10} {}\r\n", truncate(&r.name, 29), r.visibility, desc ) .unwrap(); } write!(out, "\r\n{} repository(ies).\r\n", repos.len()).unwrap(); out.into_bytes() } Err(e) => format!("Error: {}\r\n", sanitize_api_error(&e)).into_bytes(), } } async fn cmd_repo_info(user: &UserInfo, api: &MnwApiClient, name: &str, json: bool) -> Vec { if name.is_empty() { return b"Usage: repo info \r\n".to_vec(); } match api.repo_info(&user.user_id, name).await { Ok(r) => { if json { return serde_json::to_vec_pretty(&r).unwrap_or_default(); } let desc = if r.description.is_empty() { "-" } else { &r.description }; format!( "Name: {}\r\nVisibility: {}\r\nDescription: {}\r\nCreated: {}\r\nIssues: {} open, {} closed\r\n", r.name, r.visibility, desc, r.created_at, r.open_issues, r.closed_issues, ) .into_bytes() } Err(e) => format!("Error: {}\r\n", sanitize_api_error(&e)).into_bytes(), } } async fn cmd_repo_set_visibility( user: &UserInfo, api: &MnwApiClient, name: &str, visibility: &str, ) -> Vec { if name.is_empty() || visibility.is_empty() { return b"Usage: repo set-visibility \r\n".to_vec(); } if !matches!(visibility, "public" | "unlisted" | "private") { return b"Visibility must be public, unlisted, or private.\r\n".to_vec(); } match api .repo_set_visibility(&user.user_id, name, visibility) .await { Ok(()) => format!("Set visibility of '{name}' to '{visibility}'.\r\n").into_bytes(), Err(e) => format!("Error: {}\r\n", sanitize_api_error(&e)).into_bytes(), } } async fn cmd_repo_set_description( user: &UserInfo, api: &MnwApiClient, name: &str, description: &str, ) -> Vec { if name.is_empty() { return b"Usage: repo set-description \r\n".to_vec(); } match api .repo_set_description(&user.user_id, name, description) .await { Ok(()) => format!("Updated description of '{name}'.\r\n").into_bytes(), Err(e) => format!("Error: {}\r\n", sanitize_api_error(&e)).into_bytes(), } } async fn cmd_repo_delete(user: &UserInfo, api: &MnwApiClient, name: &str) -> Vec { if name.is_empty() { return b"Usage: repo delete --confirm\r\n".to_vec(); } match api.repo_delete(&user.user_id, name).await { Ok(()) => format!("Deleted repository '{name}'.\r\n").into_bytes(), Err(e) => format!("Error: {}\r\n", sanitize_api_error(&e)).into_bytes(), } } async fn cmd_key_list(user: &UserInfo, api: &MnwApiClient, json: bool) -> Vec { match api.key_list(&user.user_id).await { Ok(keys) => { if json { return serde_json::to_vec_pretty(&keys).unwrap_or_default(); } if keys.is_empty() { return b"No SSH keys.\r\n".to_vec(); } let mut out = format!("{:<50} {:<20} {}\r\n", "Fingerprint", "Label", "Added"); out.push_str(&"-".repeat(80)); out.push_str("\r\n"); for k in &keys { let label = if k.label.is_empty() { "-" } else { truncate(&k.label, 20) }; // The shared endpoint returns RFC3339; the table wants a date. let added = k.created_at.get(..10).unwrap_or(&k.created_at); write!(out, "{:<50} {:<20} {}\r\n", k.fingerprint, label, added).unwrap(); } write!(out, "\r\n{} key(s).\r\n", keys.len()).unwrap(); out.into_bytes() } Err(e) => format!("Error: {}\r\n", sanitize_api_error(&e)).into_bytes(), } } async fn cmd_key_remove(user: &UserInfo, api: &MnwApiClient, fingerprint: &str) -> Vec { if fingerprint.is_empty() { return b"Usage: key rm \r\n".to_vec(); } match api.key_remove(&user.user_id, fingerprint).await { Ok(()) => format!("Removed SSH key '{fingerprint}'.\r\n").into_bytes(), Err(e) => format!("Error: {}\r\n", sanitize_api_error(&e)).into_bytes(), } } pub(crate) fn help_text() -> Vec { b"Usage: ssh cli.makenot.work \r\n\ \r\n\ Commands:\r\n\ \x20 projects List your projects\r\n\ \x20 project create [opts] Create a new project\r\n\ \x20 analytics [--range=N] Revenue stats (7d/30d/90d/all)\r\n\ \x20 transactions Recent transactions\r\n\ \x20 export sales Export sales as CSV\r\n\ \x20 promo list List promo codes\r\n\ \x20 promo create CODE PCT Create a promo code\r\n\ \x20 blog list SLUG List blog posts for project\r\n\ \x20 broadcast -s SUBJ -b BODY Email followers (1/24h limit)\r\n\ \x20 collections List your collections\r\n\ \x20 domain Show custom domain\r\n\ \x20 domain add DOMAIN Add a custom domain\r\n\ \x20 domain verify Verify DNS record\r\n\ \x20 domain remove Remove custom domain\r\n\ \x20 upload [args] Pipe upload (see below)\r\n\ \x20 repo list List your git repositories\r\n\ \x20 repo info NAME Show one repository\r\n\ \x20 repo set-visibility NAME public|unlisted|private\r\n\ \x20 repo set-description NAME TEXT\r\n\ \x20 repo delete NAME --confirm Delete a repository\r\n\ \x20 key list List your SSH keys\r\n\ \x20 key rm FINGERPRINT Remove an SSH key\r\n\ \r\n\ Add --json to any command for machine-readable output.\r\n\ \r\n\ Pipe uploads:\r\n\ \x20 cat file.wav | ssh cli.makenot.work upload --filename track.wav --project my-slug\r\n\ \x20 Options: --filename/-f NAME --project/-p SLUG [--title/-t TITLE] [--price CENTS]\r\n\ \r\n\ File uploads (SFTP):\r\n\ \x20 scp file.wav cli.makenot.work:upload/\r\n\ \x20 Then publish via the interactive TUI (ssh cli.makenot.work)\r\n\ \r\n\ Git hosting:\r\n\ \x20 git remote add mnw cli.makenot.work:username/repo-name\r\n\ \x20 git push mnw main\r\n" .to_vec() } /// Extract a flag value from command parts. Supports both `--flag value` and `-f value`. /// Handles quoted values that were split by whitespace by rejoining until the closing quote. fn extract_flag(parts: &[&str], flags: &[&str]) -> Option { for (i, part) in parts.iter().enumerate() { if flags.contains(part) && let Some(&next) = parts.get(i + 1) { // If the value starts with a quote, collect until closing quote if next.starts_with('"') || next.starts_with('\'') { let quote = next.as_bytes()[0] as char; let stripped = &next[1..]; if stripped.ends_with(quote) { return Some(stripped[..stripped.len() - 1].to_string()); } let mut collected = stripped.to_string(); for &subsequent in &parts[i + 2..] { collected.push(' '); if subsequent.ends_with(quote) { collected.push_str(&subsequent[..subsequent.len() - 1]); return Some(collected); } collected.push_str(subsequent); } return Some(collected); } return Some(next.to_string()); } } None } /// Strip one layer of matching surrounding quotes. /// /// The command line is split on whitespace, so a quoted argument arrives as /// several parts and is rejoined by the caller, which puts the quote characters /// back into the middle of the value: `set-description r "A cool project"` /// would otherwise store the description with the quotes attached. The old /// sshd-side parser tokenized with quote awareness and this is what replaces /// that, at the one place where an argument is prose rather than an identifier. fn unquote(s: &str) -> &str { let bytes = s.as_bytes(); if bytes.len() >= 2 && (bytes[0] == b'"' || bytes[0] == b'\'') && bytes[bytes.len() - 1] == bytes[0] { &s[1..s.len() - 1] } else { s } } fn truncate(s: &str, max_len: usize) -> &str { if s.len() <= max_len { s } else { &s[..s.floor_char_boundary(max_len)] } } #[cfg(test)] mod tests { use super::*; #[test] fn unquote_strips_matching_double_quotes() { assert_eq!(unquote("\"A cool project\""), "A cool project"); } #[test] fn unquote_strips_matching_single_quotes() { assert_eq!(unquote("'A cool project'"), "A cool project"); } #[test] fn unquote_leaves_unquoted_text_alone() { assert_eq!(unquote("A cool project"), "A cool project"); } #[test] fn unquote_leaves_mismatched_quotes_alone() { // A lone quote is part of the description, not a delimiter. assert_eq!(unquote("\"unterminated"), "\"unterminated"); assert_eq!(unquote("it's"), "it's"); } #[test] fn unquote_handles_the_empty_quoted_string() { assert_eq!(unquote("\"\""), ""); } #[test] fn truncate_short_string() { assert_eq!(truncate("hello", 10), "hello"); } #[test] fn truncate_exact_length() { assert_eq!(truncate("hello", 5), "hello"); } #[test] fn truncate_long_string() { assert_eq!(truncate("hello world", 5), "hello"); } #[test] fn truncate_multibyte_utf8() { // "café" is 5 bytes (é = 2 bytes), truncating at 4 should not panic let result = truncate("café", 4); assert_eq!(result, "caf"); } #[test] fn truncate_emoji() { // Each emoji is 4 bytes let result = truncate("🎵🎶🎸", 5); assert_eq!(result, "🎵"); } #[test] fn extract_flag_simple() { let parts = vec!["broadcast", "--subject", "Hello", "--body", "World"]; assert_eq!( extract_flag(&parts, &["--subject", "-s"]), Some("Hello".to_string()) ); assert_eq!( extract_flag(&parts, &["--body", "-b"]), Some("World".to_string()) ); } #[test] fn extract_flag_short() { let parts = vec!["broadcast", "-s", "Hi", "-b", "There"]; assert_eq!( extract_flag(&parts, &["--subject", "-s"]), Some("Hi".to_string()) ); } #[test] fn extract_flag_quoted_multiword() { let parts = vec![ "broadcast", "--subject", "\"Hello", "everyone\"", "--body", "\"text\"", ]; assert_eq!( extract_flag(&parts, &["--subject", "-s"]), Some("Hello everyone".to_string()) ); assert_eq!( extract_flag(&parts, &["--body", "-b"]), Some("text".to_string()) ); } #[test] fn extract_flag_missing() { let parts = vec!["broadcast", "--subject", "Hi"]; assert_eq!(extract_flag(&parts, &["--body", "-b"]), None); } }