LINE1 10 20 30 40 50 60 70 80 90 1001use std::{fs, io::Read, path::PathBuf};23use anyhow::{Context, bail};4use base64::{Engine as _, engine::general_purpose::STANDARD};5use clap::Subcommand;6use serde_json::{Value, json};78#[cfg(test)]9use crate::api::ApiBody;10use crate::api::{ApiMethod, ApiRequest, ApiResponse, TwigApi};1112const MAX_CONTENT_BYTES: usize = 1024 * 1024;13const MAX_BINARY_BYTES: u64 = 512 * 1024 * 1024;1415#[derive(Subcommand, Debug)]16pub enum NamespaceCommand {17 18 List,19 20 Create { name: String },21 22 Show { namespace: String },23 24 Rename { namespace: String, new_name: String },25 26 Delete { namespace: String },27}2829#[derive(Subcommand, Debug)]30pub enum RepositoryCommand {31 32 List {33 namespace: String,34 #[arg(short, long)]35 query: Option<String>,36 },37 38 Create {39 namespace: String,40 name: String,41 #[arg(long, default_value = "main")]42 default_branch: String,43 },44 45 Show {46 namespace: String,47 repository: String,48 },49 50 Rename {51 namespace: String,52 repository: String,53 new_name: String,54 },55 56 Move {57 namespace: String,58 repository: String,59 target_namespace: String,60 },61 62 Delete {63 namespace: String,64 repository: String,65 },66 67 Branches {68 namespace: String,69 repository: String,70 },71 72 Commits {73 namespace: String,74 repository: String,75 #[arg(long = "ref")]76 reference: String,77 #[arg(long)]78 limit: Option<u32>,79 },80 81 Tree {82 namespace: String,83 repository: String,84 #[arg(long = "ref")]85 reference: String,86 #[arg(long, default_value = "")]87 path: String,88 },89}9091#[derive(Subcommand, Debug)]92pub enum ContentCommand {93 94 Get {95 namespace: String,96 repository: String,97 #[arg(long = "ref")]98 reference: String,99 path: String,100 #[arg(long)]101 output: Option<PathBuf>,102 },103 104 Put {105 namespace: String,106 repository: String,107 #[arg(long = "ref")]108 reference: String,109 path: String,110 #[arg(long, conflicts_with = "file")]111 text: Option<String>,112 #[arg(long, conflicts_with = "text")]113 file: Option<PathBuf>,114 #[arg(long)]115 message: String,116 #[arg(long, value_name = "COMMIT_ID")]117 expected_head: String,118 },119 120 Delete {121 namespace: String,122 repository: String,123 #[arg(long = "ref")]124 reference: String,125 path: String,126 #[arg(long)]127 message: String,128 #[arg(long, value_name = "COMMIT_ID")]129 expected_head: String,130 },131 132 Rename {133 namespace: String,134 repository: String,135 #[arg(long = "ref")]136 reference: String,137 from: String,138 to: String,139 #[arg(long)]140 message: String,141 #[arg(long, value_name = "COMMIT_ID")]142 expected_head: String,143 },144}145146#[derive(Subcommand, Debug)]147pub enum BinaryCommand {148 149 List {150 namespace: String,151 repository: String,152 },153 154 Get {155 namespace: String,156 repository: String,157 version: String,158 filename: String,159 #[arg(long)]160 output: PathBuf,161 },162 163 Put {164 namespace: String,165 repository: String,166 version: String,167 filename: String,168 #[arg(long)]169 file: PathBuf,170 },171}172173#[derive(Subcommand, Debug)]174pub enum MemberCommand {175 176 List { namespace: String },177}178179#[derive(Subcommand, Debug)]180pub enum InvitationCommand {181 182 List { namespace: String },183 184 Create {185 namespace: String,186 email: String,187 #[arg(value_parser = ["owner", "contributor"])]188 role: String,189 #[arg(value_parser = ["1d", "7d", "30d", "never"])]190 expires: String,191 },192 193 Resend { namespace: String, id: String },194}195196pub enum ApiCommand {197 Me,198 Version,199 Namespace(NamespaceCommand),200 Repository(RepositoryCommand),201 Content(ContentCommand),202 Binary(BinaryCommand),203 Member(MemberCommand),204 Invitation(InvitationCommand),205}206207enum OutputMode {208 Json,209 ContentFile(PathBuf),210 BinaryFile(PathBuf),211}212213pub async fn run_command(api: &impl TwigApi, command: ApiCommand) -> anyhow::Result<()> {214 let output_mode = output_mode(&command);215 let request = request_for(&command)?;216 let response = api.execute(request).await?.ensure_success()?;217 match output_mode {218 OutputMode::Json => print_json(&response),219 OutputMode::ContentFile(path) => {220 let document = response.json_value()?;221 let encoding = document222 .get("encoding")223 .and_then(Value::as_str)224 .context("Twig content response is missing its encoding")?;225 if encoding != "base64" {226 bail!("Twig content response used an unsupported encoding: {encoding}");227 }228 let content = document229 .get("content")230 .and_then(Value::as_str)231 .context("Twig content response is missing Base64 content")?;232 let bytes = STANDARD233 .decode(content)234 .context("Twig returned invalid Base64 file content")?;235 fs::write(&path, &bytes)236 .with_context(|| format!("Could not write content to {}", path.display()))?;237 println!("Wrote {} bytes to {}", bytes.len(), path.display());238 Ok(())239 }240 OutputMode::BinaryFile(path) => {241 fs::write(&path, &response.body)242 .with_context(|| format!("Could not write binary to {}", path.display()))?;243 println!(244 "Downloaded {} bytes to {}",245 response.body.len(),246 path.display()247 );248 Ok(())249 }250 }251}252253pub fn request_for(command: &ApiCommand) -> anyhow::Result<ApiRequest> {254 match command {255 ApiCommand::Me => Ok(ApiRequest::new(ApiMethod::Get, vec!["me".into()])),256 ApiCommand::Version => {257 Ok(ApiRequest::new(ApiMethod::Get, vec!["version".into()]).root_api())258 }259 ApiCommand::Namespace(command) => Ok(namespace_request(command)),260 ApiCommand::Repository(command) => Ok(repository_request(command)),261 ApiCommand::Content(command) => content_request(command),262 ApiCommand::Binary(command) => binary_request(command),263 ApiCommand::Member(MemberCommand::List { namespace }) => Ok(ApiRequest::new(264 ApiMethod::Get,265 ["namespaces", namespace, "members"]266 .into_iter()267 .map(str::to_owned)268 .collect(),269 )),270 ApiCommand::Invitation(command) => Ok(invitation_request(command)),271 }272}273274fn namespace_request(command: &NamespaceCommand) -> ApiRequest {275 match command {276 NamespaceCommand::List => ApiRequest::new(ApiMethod::Get, vec!["namespaces".into()]),277 NamespaceCommand::Create { name } => {278 ApiRequest::new(ApiMethod::Post, vec!["namespaces".into()]).json(json!({"name": name}))279 }280 NamespaceCommand::Show { namespace } => {281 ApiRequest::new(ApiMethod::Get, vec!["namespaces".into(), namespace.clone()])282 }283 NamespaceCommand::Rename {284 namespace,285 new_name,286 } => ApiRequest::new(287 ApiMethod::Patch,288 vec!["namespaces".into(), namespace.clone()],289 )290 .json(json!({"name": new_name})),291 NamespaceCommand::Delete { namespace } => ApiRequest::new(292 ApiMethod::Delete,293 vec!["namespaces".into(), namespace.clone()],294 ),295 }296}297298fn repository_request(command: &RepositoryCommand) -> ApiRequest {299 match command {300 RepositoryCommand::List { namespace, query } => {301 let request = ApiRequest::new(302 ApiMethod::Get,303 vec![304 "namespaces".into(),305 namespace.clone(),306 "repositories".into(),307 ],308 );309 match query {310 Some(query) => request.query("q", query),311 None => request,312 }313 }314 RepositoryCommand::Create {315 namespace,316 name,317 default_branch,318 } => ApiRequest::new(319 ApiMethod::Post,320 vec![321 "namespaces".into(),322 namespace.clone(),323 "repositories".into(),324 ],325 )326 .json(json!({"name": name, "default_branch": default_branch})),327 RepositoryCommand::Show {328 namespace,329 repository,330 } => ApiRequest::new(ApiMethod::Get, repository_path(namespace, repository)),331 RepositoryCommand::Branches {332 namespace,333 repository,334 } => ApiRequest::new(335 ApiMethod::Get,336 repository_subpath(namespace, repository, &["branches"]),337 ),338 RepositoryCommand::Commits {339 namespace,340 repository,341 reference,342 limit,343 } => {344 let request = ApiRequest::new(345 ApiMethod::Get,346 repository_subpath(namespace, repository, &["commits"]),347 )348 .query("ref", reference);349 match limit {350 Some(limit) => request.query("limit", limit.to_string()),351 None => request,352 }353 }354 RepositoryCommand::Tree {355 namespace,356 repository,357 reference,358 path,359 } => ApiRequest::new(360 ApiMethod::Get,361 repository_subpath(namespace, repository, &["tree"]),362 )363 .query("ref", reference)364 .query("path", path),365 RepositoryCommand::Rename {366 namespace,367 repository,368 new_name,369 } => ApiRequest::new(ApiMethod::Patch, repository_path(namespace, repository))370 .json(json!({"name": new_name})),371 RepositoryCommand::Move {372 namespace,373 repository,374 target_namespace,375 } => ApiRequest::new(ApiMethod::Patch, repository_path(namespace, repository))376 .json(json!({"target_namespace": target_namespace})),377 RepositoryCommand::Delete {378 namespace,379 repository,380 } => ApiRequest::new(ApiMethod::Delete, repository_path(namespace, repository)),381 }382}383384fn repository_path(namespace: &str, repository: &str) -> Vec<String> {385 vec![386 "namespaces".into(),387 namespace.into(),388 "repositories".into(),389 repository.into(),390 ]391}392393fn repository_subpath(namespace: &str, repository: &str, suffix: &[&str]) -> Vec<String> {394 let mut path = repository_path(namespace, repository);395 path.extend(suffix.iter().map(|segment| (*segment).to_owned()));396 path397}398399fn content_request(command: &ContentCommand) -> anyhow::Result<ApiRequest> {400 match command {401 ContentCommand::Get {402 namespace,403 repository,404 reference,405 path,406 ..407 } => Ok(ApiRequest::new(408 ApiMethod::Get,409 repository_path(namespace, repository)410 .into_iter()411 .chain(["contents".to_owned()])412 .collect(),413 )414 .query("ref", reference)415 .query("path", path)),416 ContentCommand::Put {417 namespace,418 repository,419 reference,420 path,421 text,422 file,423 message,424 expected_head,425 } => {426 let (content, encoding) = match (text, file) {427 (Some(text), None) => {428 let bytes = text.as_bytes();429 ensure_content_size(bytes.len())?;430 (text.clone(), "utf8")431 }432 (None, Some(file)) => {433 let bytes = read_limited_file(file, MAX_CONTENT_BYTES as u64, "content")?;434 (STANDARD.encode(bytes), "base64")435 }436 _ => bail!("provide exactly one of --text or --file"),437 };438 Ok(ApiRequest::new(439 ApiMethod::Put,440 repository_path(namespace, repository)441 .into_iter()442 .chain(["contents".to_owned()])443 .collect(),444 )445 .query("ref", reference)446 .query("path", path)447 .json(json!({448 "content": content,449 "encoding": encoding,450 "message": message,451 "expected_head": expected_head,452 })))453 }454 ContentCommand::Delete {455 namespace,456 repository,457 reference,458 path,459 message,460 expected_head,461 } => Ok(ApiRequest::new(462 ApiMethod::Delete,463 repository_path(namespace, repository)464 .into_iter()465 .chain(["contents".to_owned()])466 .collect(),467 )468 .query("ref", reference)469 .query("path", path)470 .json(json!({"message": message, "expected_head": expected_head}))),471 ContentCommand::Rename {472 namespace,473 repository,474 reference,475 from,476 to,477 message,478 expected_head,479 } => Ok(ApiRequest::new(480 ApiMethod::Post,481 repository_path(namespace, repository)482 .into_iter()483 .chain(["contents".to_owned(), "rename".to_owned()])484 .collect(),485 )486 .json(json!({487 "ref": reference,488 "from": from,489 "to": to,490 "message": message,491 "expected_head": expected_head,492 }))),493 }494}495496fn binary_request(command: &BinaryCommand) -> anyhow::Result<ApiRequest> {497 match command {498 BinaryCommand::List {499 namespace,500 repository,501 } => Ok(ApiRequest::new(502 ApiMethod::Get,503 repository_path(namespace, repository)504 .into_iter()505 .chain(["binaries".to_owned()])506 .collect(),507 )),508 BinaryCommand::Get {509 namespace,510 repository,511 version,512 filename,513 ..514 } => Ok(ApiRequest::new(515 ApiMethod::Get,516 repository_path(namespace, repository)517 .into_iter()518 .chain(["binaries".to_owned(), version.clone(), filename.clone()])519 .collect(),520 )),521 BinaryCommand::Put {522 namespace,523 repository,524 version,525 filename,526 file,527 } => {528 let body = read_limited_file(file, MAX_BINARY_BYTES, "binary release")?;529 Ok(ApiRequest::new(530 ApiMethod::Put,531 repository_path(namespace, repository)532 .into_iter()533 .chain(["binaries".to_owned(), version.clone(), filename.clone()])534 .collect(),535 )536 .binary(body))537 }538 }539}540541fn invitation_request(command: &InvitationCommand) -> ApiRequest {542 match command {543 InvitationCommand::List { namespace } => ApiRequest::new(544 ApiMethod::Get,545 vec!["namespaces".into(), namespace.clone(), "invitations".into()],546 ),547 InvitationCommand::Create {548 namespace,549 email,550 role,551 expires,552 } => ApiRequest::new(553 ApiMethod::Post,554 vec!["namespaces".into(), namespace.clone(), "invitations".into()],555 )556 .json(json!({"email": email, "role": role, "expires": expires})),557 InvitationCommand::Resend { namespace, id } => ApiRequest::new(558 ApiMethod::Post,559 vec![560 "namespaces".into(),561 namespace.clone(),562 "invitations".into(),563 id.clone(),564 "resend".into(),565 ],566 ),567 }568}569570fn output_mode(command: &ApiCommand) -> OutputMode {571 match command {572 ApiCommand::Content(ContentCommand::Get {573 output: Some(path), ..574 }) => OutputMode::ContentFile(path.clone()),575 ApiCommand::Binary(BinaryCommand::Get { output, .. }) => {576 OutputMode::BinaryFile(output.clone())577 }578 _ => OutputMode::Json,579 }580}581582fn read_limited_file(path: &PathBuf, max_bytes: u64, kind: &str) -> anyhow::Result<Vec<u8>> {583 let mut file = fs::File::open(path)584 .with_context(|| format!("Could not open {kind} file {}", path.display()))?;585 let metadata = file586 .metadata()587 .with_context(|| format!("Could not inspect {kind} file {}", path.display()))?;588 if metadata.len() > max_bytes {589 bail!(590 "{kind} file is too large ({} bytes; maximum is {max_bytes})",591 metadata.len()592 );593 }594 let mut bytes = Vec::new();595 file.by_ref()596 .take(max_bytes.saturating_add(1))597 .read_to_end(&mut bytes)598 .with_context(|| format!("Could not read {kind} file {}", path.display()))?;599 if bytes.len() as u64 > max_bytes {600 bail!("{kind} file grew beyond the maximum size while it was being read");601 }602 Ok(bytes)603}604605fn ensure_content_size(size: usize) -> anyhow::Result<()> {606 if size > MAX_CONTENT_BYTES {607 bail!("content is too large ({size} bytes; maximum is {MAX_CONTENT_BYTES})");608 }609 Ok(())610}611612fn print_json(response: &ApiResponse) -> anyhow::Result<()> {613 if response.body.is_empty() {614 println!("{{}}");615 return Ok(());616 }617 let value = response.json_value()?;618 println!("{}", serde_json::to_string_pretty(&value)?);619 Ok(())620}621622#[cfg(test)]623mod tests {624 use std::time::{SystemTime, UNIX_EPOCH};625626 use super::*;627628 struct StaticApi(ApiResponse);629630 impl TwigApi for StaticApi {631 async fn execute(&self, _request: ApiRequest) -> anyhow::Result<ApiResponse> {632 Ok(self.0.clone())633 }634 }635636 fn strings(values: &[&str]) -> Vec<String> {637 values.iter().map(|value| (*value).to_owned()).collect()638 }639640 fn temporary_file() -> PathBuf {641 let timestamp = SystemTime::now()642 .duration_since(UNIX_EPOCH)643 .expect("clock after epoch")644 .as_nanos();645 std::env::temp_dir().join(format!("tree-api-test-{}-{timestamp}", std::process::id()))646 }647648 #[allow(clippy::needless_pass_by_value)]649 fn assert_route(command: ApiCommand, method: ApiMethod, path: &[&str]) {650 let request = request_for(&command).expect("valid command request");651 assert_eq!(request.method, method);652 assert_eq!(request.path_segments, strings(path));653 }654655 #[test]656 #[allow(clippy::too_many_lines)]657 fn request_builder_maps_every_documented_route() {658 let version = request_for(&ApiCommand::Version).unwrap();659 assert_eq!(version.method, ApiMethod::Get);660 assert_eq!(version.root, crate::api::ApiRoot::Root);661 assert_eq!(version.path_segments, strings(&["version"]));662 assert_route(ApiCommand::Me, ApiMethod::Get, &["me"]);663664 assert_route(665 ApiCommand::Namespace(NamespaceCommand::List),666 ApiMethod::Get,667 &["namespaces"],668 );669 assert_route(670 ApiCommand::Namespace(NamespaceCommand::Create {671 name: "acme".into(),672 }),673 ApiMethod::Post,674 &["namespaces"],675 );676 assert_route(677 ApiCommand::Namespace(NamespaceCommand::Show {678 namespace: "acme".into(),679 }),680 ApiMethod::Get,681 &["namespaces", "acme"],682 );683 assert_route(684 ApiCommand::Namespace(NamespaceCommand::Rename {685 namespace: "acme".into(),686 new_name: "new-acme".into(),687 }),688 ApiMethod::Patch,689 &["namespaces", "acme"],690 );691 assert_route(692 ApiCommand::Namespace(NamespaceCommand::Delete {693 namespace: "acme".into(),694 }),695 ApiMethod::Delete,696 &["namespaces", "acme"],697 );698699 assert_route(700 ApiCommand::Repository(RepositoryCommand::List {701 namespace: "acme".into(),702 query: None,703 }),704 ApiMethod::Get,705 &["namespaces", "acme", "repositories"],706 );707 assert_route(708 ApiCommand::Repository(RepositoryCommand::Create {709 namespace: "acme".into(),710 name: "tooling".into(),711 default_branch: "main".into(),712 }),713 ApiMethod::Post,714 &["namespaces", "acme", "repositories"],715 );716 assert_route(717 ApiCommand::Repository(RepositoryCommand::Show {718 namespace: "acme".into(),719 repository: "tooling".into(),720 }),721 ApiMethod::Get,722 &["namespaces", "acme", "repositories", "tooling"],723 );724 assert_route(725 ApiCommand::Repository(RepositoryCommand::Rename {726 namespace: "acme".into(),727 repository: "tooling".into(),728 new_name: "tools".into(),729 }),730 ApiMethod::Patch,731 &["namespaces", "acme", "repositories", "tooling"],732 );733 assert_route(734 ApiCommand::Repository(RepositoryCommand::Move {735 namespace: "acme".into(),736 repository: "tooling".into(),737 target_namespace: "other".into(),738 }),739 ApiMethod::Patch,740 &["namespaces", "acme", "repositories", "tooling"],741 );742 assert_route(743 ApiCommand::Repository(RepositoryCommand::Delete {744 namespace: "acme".into(),745 repository: "tooling".into(),746 }),747 ApiMethod::Delete,748 &["namespaces", "acme", "repositories", "tooling"],749 );750 assert_route(751 ApiCommand::Repository(RepositoryCommand::Branches {752 namespace: "acme".into(),753 repository: "tooling".into(),754 }),755 ApiMethod::Get,756 &["namespaces", "acme", "repositories", "tooling", "branches"],757 );758 assert_route(759 ApiCommand::Repository(RepositoryCommand::Commits {760 namespace: "acme".into(),761 repository: "tooling".into(),762 reference: "main".into(),763 limit: None,764 }),765 ApiMethod::Get,766 &["namespaces", "acme", "repositories", "tooling", "commits"],767 );768 assert_route(769 ApiCommand::Repository(RepositoryCommand::Tree {770 namespace: "acme".into(),771 repository: "tooling".into(),772 reference: "main".into(),773 path: String::new(),774 }),775 ApiMethod::Get,776 &["namespaces", "acme", "repositories", "tooling", "tree"],777 );778779 assert_route(780 ApiCommand::Content(ContentCommand::Get {781 namespace: "acme".into(),782 repository: "tooling".into(),783 reference: "main".into(),784 path: "README.md".into(),785 output: None,786 }),787 ApiMethod::Get,788 &["namespaces", "acme", "repositories", "tooling", "contents"],789 );790 assert_route(791 ApiCommand::Content(ContentCommand::Put {792 namespace: "acme".into(),793 repository: "tooling".into(),794 reference: "main".into(),795 path: "README.md".into(),796 text: Some("text".into()),797 file: None,798 message: "message".into(),799 expected_head: "head".into(),800 }),801 ApiMethod::Put,802 &["namespaces", "acme", "repositories", "tooling", "contents"],803 );804 assert_route(805 ApiCommand::Content(ContentCommand::Delete {806 namespace: "acme".into(),807 repository: "tooling".into(),808 reference: "main".into(),809 path: "README.md".into(),810 message: "message".into(),811 expected_head: "head".into(),812 }),813 ApiMethod::Delete,814 &["namespaces", "acme", "repositories", "tooling", "contents"],815 );816 assert_route(817 ApiCommand::Content(ContentCommand::Rename {818 namespace: "acme".into(),819 repository: "tooling".into(),820 reference: "main".into(),821 from: "old".into(),822 to: "new".into(),823 message: "message".into(),824 expected_head: "head".into(),825 }),826 ApiMethod::Post,827 &[828 "namespaces",829 "acme",830 "repositories",831 "tooling",832 "contents",833 "rename",834 ],835 );836 assert_route(837 ApiCommand::Binary(BinaryCommand::List {838 namespace: "acme".into(),839 repository: "tooling".into(),840 }),841 ApiMethod::Get,842 &["namespaces", "acme", "repositories", "tooling", "binaries"],843 );844 assert_route(845 ApiCommand::Binary(BinaryCommand::Get {846 namespace: "acme".into(),847 repository: "tooling".into(),848 version: "latest".into(),849 filename: "tool".into(),850 output: PathBuf::from("tool"),851 }),852 ApiMethod::Get,853 &[854 "namespaces",855 "acme",856 "repositories",857 "tooling",858 "binaries",859 "latest",860 "tool",861 ],862 );863 assert_route(864 ApiCommand::Member(MemberCommand::List {865 namespace: "acme".into(),866 }),867 ApiMethod::Get,868 &["namespaces", "acme", "members"],869 );870 assert_route(871 ApiCommand::Invitation(InvitationCommand::List {872 namespace: "acme".into(),873 }),874 ApiMethod::Get,875 &["namespaces", "acme", "invitations"],876 );877 assert_route(878 ApiCommand::Invitation(InvitationCommand::Create {879 namespace: "acme".into(),880 email: "person@example.com".into(),881 role: "owner".into(),882 expires: "never".into(),883 }),884 ApiMethod::Post,885 &["namespaces", "acme", "invitations"],886 );887 assert_route(888 ApiCommand::Invitation(InvitationCommand::Resend {889 namespace: "acme".into(),890 id: "42".into(),891 }),892 ApiMethod::Post,893 &["namespaces", "acme", "invitations", "42", "resend"],894 );895 }896897 #[test]898 fn namespace_and_repository_requests_match_documented_routes() {899 let request = request_for(&ApiCommand::Namespace(NamespaceCommand::Rename {900 namespace: "acme".into(),901 new_name: "acme-tools".into(),902 }))903 .unwrap();904 assert_eq!(request.method, ApiMethod::Patch);905 assert_eq!(request.path_segments, strings(&["namespaces", "acme"]));906 assert_eq!(request.body, ApiBody::Json(json!({"name":"acme-tools"})));907908 let request = request_for(&ApiCommand::Repository(RepositoryCommand::Move {909 namespace: "acme".into(),910 repository: "tooling".into(),911 target_namespace: "other".into(),912 }))913 .unwrap();914 assert_eq!(request.method, ApiMethod::Patch);915 assert_eq!(916 request.body,917 ApiBody::Json(json!({"target_namespace":"other"}))918 );919 }920921 #[test]922 fn content_mutations_include_expected_head_and_exact_branch() {923 let request = request_for(&ApiCommand::Content(ContentCommand::Delete {924 namespace: "acme".into(),925 repository: "tooling".into(),926 reference: "feature/docs".into(),927 path: "README.md".into(),928 message: "Remove old readme".into(),929 expected_head: "abc123".into(),930 }))931 .unwrap();932 assert_eq!(request.method, ApiMethod::Delete);933 assert!(934 request935 .query936 .contains(&("ref".into(), "feature/docs".into()))937 );938 assert!(request.query.contains(&("path".into(), "README.md".into())));939 assert_eq!(940 request.body,941 ApiBody::Json(json!({"message":"Remove old readme","expected_head":"abc123"}))942 );943944 let request = request_for(&ApiCommand::Content(ContentCommand::Rename {945 namespace: "acme".into(),946 repository: "tooling".into(),947 reference: "main".into(),948 from: "old.txt".into(),949 to: "new.txt".into(),950 message: "Rename".into(),951 expected_head: "def456".into(),952 }))953 .unwrap();954 assert_eq!(955 request.path_segments,956 strings(&[957 "namespaces",958 "acme",959 "repositories",960 "tooling",961 "contents",962 "rename"963 ])964 );965 assert_eq!(966 request.body,967 ApiBody::Json(json!({968 "ref":"main", "from":"old.txt", "to":"new.txt", "message":"Rename", "expected_head":"def456"969 }))970 );971 }972973 #[test]974 fn commits_use_exact_branch_and_optional_limit() {975 let request = request_for(&ApiCommand::Repository(RepositoryCommand::Commits {976 namespace: "acme".into(),977 repository: "tooling".into(),978 reference: "feature/docs".into(),979 limit: Some(12),980 }))981 .unwrap();982 assert_eq!(983 request.query,984 vec![985 ("ref".into(), "feature/docs".into()),986 ("limit".into(), "12".into())987 ]988 );989 }990991 #[test]992 fn invitation_requests_keep_expiry_and_resend_namespace_scoped() {993 let request = request_for(&ApiCommand::Invitation(InvitationCommand::Create {994 namespace: "acme".into(),995 email: "person@example.com".into(),996 role: "contributor".into(),997 expires: "7d".into(),998 }))999 .unwrap();1000 assert_eq!(1001 request.body,1002 ApiBody::Json(1003 json!({"email":"person@example.com","role":"contributor","expires":"7d"})1004 )1005 );1006 let resend = request_for(&ApiCommand::Invitation(InvitationCommand::Resend {1007 namespace: "acme".into(),1008 id: "42".into(),1009 }))1010 .unwrap();1011 assert_eq!(1012 resend.path_segments,1013 strings(&["namespaces", "acme", "invitations", "42", "resend"])1014 );1015 }10161017 #[test]1018 fn content_and_binary_files_preserve_bytes_and_use_distinct_encodings() {1019 let path = temporary_file();1020 fs::write(&path, [0, 255, 10]).expect("write temporary binary fixture");10211022 let content = request_for(&ApiCommand::Content(ContentCommand::Put {1023 namespace: "acme".into(),1024 repository: "tooling".into(),1025 reference: "main".into(),1026 path: "asset.bin".into(),1027 text: None,1028 file: Some(path.clone()),1029 message: "Add asset".into(),1030 expected_head: "head".into(),1031 }))1032 .expect("Base64 content request");1033 let ApiBody::Json(content_body) = content.body else {1034 panic!("content file should use JSON");1035 };1036 assert_eq!(content_body["encoding"], "base64");1037 assert_eq!(content_body["content"], "AP8K");10381039 let binary = request_for(&ApiCommand::Binary(BinaryCommand::Put {1040 namespace: "acme".into(),1041 repository: "tooling".into(),1042 version: "1.2.3".into(),1043 filename: "tool".into(),1044 file: path.clone(),1045 }))1046 .expect("raw binary request");1047 assert_eq!(binary.method, ApiMethod::Put);1048 assert_eq!(1049 binary.path_segments,1050 strings(&[1051 "namespaces",1052 "acme",1053 "repositories",1054 "tooling",1055 "binaries",1056 "1.2.3",1057 "tool",1058 ])1059 );1060 assert_eq!(binary.body, ApiBody::Binary(vec![0, 255, 10]));1061 fs::remove_file(path).expect("remove temporary fixture");1062 }10631064 #[test]1065 fn local_file_reader_enforces_size_ceiling() {1066 let path = temporary_file();1067 fs::write(&path, [1, 2, 3, 4]).expect("write temporary fixture");1068 assert!(read_limited_file(&path, 3, "test").is_err());1069 assert_eq!(read_limited_file(&path, 4, "test").unwrap(), [1, 2, 3, 4]);1070 fs::remove_file(path).expect("remove temporary fixture");1071 }10721073 #[tokio::test]1074 async fn content_and_binary_downloads_write_original_bytes() {1075 let content_path = temporary_file();1076 let content_api = StaticApi(ApiResponse {1077 status: 200,1078 content_type: Some("application/json".into()),1079 body: serde_json::to_vec(&json!({"encoding":"base64","content":"AP8K"})).unwrap(),1080 });1081 run_command(1082 &content_api,1083 ApiCommand::Content(ContentCommand::Get {1084 namespace: "acme".into(),1085 repository: "tooling".into(),1086 reference: "main".into(),1087 path: "asset.bin".into(),1088 output: Some(content_path.clone()),1089 }),1090 )1091 .await1092 .expect("content download");1093 assert_eq!(fs::read(&content_path).unwrap(), [0, 255, 10]);1094 fs::remove_file(content_path).expect("remove content output");10951096 let binary_path = temporary_file();1097 let binary_api = StaticApi(ApiResponse {1098 status: 200,1099 content_type: Some("application/octet-stream".into()),1100 body: vec![0, 255, 10],1101 });1102 run_command(1103 &binary_api,1104 ApiCommand::Binary(BinaryCommand::Get {1105 namespace: "acme".into(),1106 repository: "tooling".into(),1107 version: "latest".into(),1108 filename: "tool".into(),1109 output: binary_path.clone(),1110 }),1111 )1112 .await1113 .expect("binary download");1114 assert_eq!(fs::read(&binary_path).unwrap(), [0, 255, 10]);1115 fs::remove_file(binary_path).expect("remove binary output");1116 }11171118 #[test]1119 fn content_size_limit_is_one_mibibyte() {1120 assert!(ensure_content_size(MAX_CONTENT_BYTES).is_ok());1121 assert!(ensure_content_size(MAX_CONTENT_BYTES + 1).is_err());1122 }1123}