//! `attach-issue ` and `attach-comment //! ` — upload a file as an attachment. Prints the browser //! download URL. use std::path::{Path, PathBuf}; use anyhow::{Context, Result, bail}; use clap::Args as ClapArgs; use forgejo_api::structs::{ Attachment, IssueCreateIssueAttachmentQuery, IssueCreateIssueCommentAttachmentQuery, }; use crate::client::{Client, index}; #[derive(ClapArgs)] pub struct IssueArgs { /// Issue number. number: u64, /// File path to upload. file: PathBuf, } #[derive(ClapArgs)] pub struct CommentArgs { /// Comment id. id: u64, /// File path to upload. file: PathBuf, } /// # Errors /// /// Returns an error if the input file doesn't exist or can't be /// read. Propagates any transport error from the Forgejo REST call /// (network unreachable, 4xx/5xx response, token missing/invalid) /// and any I/O error from writing the browser download URL to stdout. pub fn run_issue(client: &Client, args: IssueArgs) -> Result<()> { if !args.file.is_file() { bail!( "hive-forge attach-issue: file not found: {}", args.file.display() ); } let (owner, name) = client.owner_repo()?; let bytes = read_file(&args.file)?; let query = IssueCreateIssueAttachmentQuery { name: file_name(&args.file), updated_at: None, }; let resp = client .api() .issue_create_issue_attachment(owner, name, index(args.number)?, &bytes, query) .send()?; println!("{}", require_url(&resp)?); Ok(()) } /// # Errors /// /// Returns an error if the input file doesn't exist or can't be /// read. Propagates any transport error from the Forgejo REST call /// (network unreachable, 4xx/5xx response, token missing/invalid) /// and any I/O error from writing the browser download URL to stdout. pub fn run_comment(client: &Client, args: CommentArgs) -> Result<()> { if !args.file.is_file() { bail!( "hive-forge attach-comment: file not found: {}", args.file.display() ); } let (owner, name) = client.owner_repo()?; let bytes = read_file(&args.file)?; let query = IssueCreateIssueCommentAttachmentQuery { name: file_name(&args.file), updated_at: None, }; let resp = client .api() .issue_create_issue_comment_attachment(owner, name, index(args.id)?, &bytes, query) .send()?; println!("{}", require_url(&resp)?); Ok(()) } fn read_file(path: &Path) -> Result> { std::fs::read(path).with_context(|| format!("read {}", path.display())) } /// The upload's attachment name — the file's basename, matching what /// the old multipart form (which sent the file with its real name) /// made the server record. fn file_name(path: &Path) -> Option { path.file_name().map(|n| n.to_string_lossy().into_owned()) } /// The uploaded attachment's browser download URL, hard-erroring if the /// forge answered 2xx with none. A caller piping the printed URL (e.g. /// `url=$(hive-forge attach-issue …)`) used to get an empty string and no /// signal when this was `None` — the upload had happened, but nothing said /// so, and nothing said it hadn't. fn require_url(v: &Attachment) -> Result { v.browser_download_url.clone().ok_or_else(|| { anyhow::anyhow!( "hive-forge attach: upload succeeded but the forge returned no download URL \ (attachment {})", attachment_ident(v) ) }) } /// Best-effort identifier for an attachment error message — id if present, /// else name, else a placeholder so the message never comes out empty. fn attachment_ident(v: &Attachment) -> String { match (v.id, v.name.as_deref()) { (Some(id), Some(n)) => format!("id={id} name={n}"), (Some(id), None) => format!("id={id}"), (None, Some(n)) => format!("name={n}"), (None, None) => "".to_owned(), } } #[cfg(test)] mod tests { use super::require_url; use forgejo_api::structs::Attachment; fn attachment(url: Option<&str>) -> Attachment { Attachment { browser_download_url: url.map(|u| u.parse().unwrap()), created_at: None, download_count: None, id: Some(7), name: Some("out.log".to_owned()), size: None, r#type: None, uuid: None, } } #[test] fn control_present_url_is_returned() { let a = attachment(Some("https://forge.example/a/1")); assert_eq!( require_url(&a).unwrap().as_str(), "https://forge.example/a/1" ); } #[test] fn missing_url_errors_naming_the_attachment() { // A 2xx response with no browser_download_url used to print nothing // and exit 0 — a caller doing `url=$(hive-forge attach-issue …)` // got an empty string with no signal anything went wrong. let a = attachment(None); let err = require_url(&a).unwrap_err(); let msg = err.to_string(); assert!(msg.contains("id=7"), "missing attachment id: {msg}"); assert!(msg.contains("out.log"), "missing attachment name: {msg}"); } }