|
| 1 | +use anyhow::Result; |
| 2 | +use clap::{Parser, Subcommand}; |
| 3 | + |
| 4 | +use aws_config::{BehaviorVersion, Region}; |
| 5 | +use aws_sdk_s3::Client; |
| 6 | + |
| 7 | +#[derive(Debug, Parser)] |
| 8 | +#[command(version, about, long_about = None)] |
| 9 | +struct Opts { |
| 10 | + /// The AWS Region. |
| 11 | + #[arg(short, long)] |
| 12 | + region: String, |
| 13 | + /// The name of the bucket. |
| 14 | + #[arg(short, long)] |
| 15 | + bucket: String, |
| 16 | + |
| 17 | + #[command(subcommand)] |
| 18 | + command: Option<Command>, |
| 19 | +} |
| 20 | + |
| 21 | +#[derive(Subcommand, Debug)] |
| 22 | +enum Command { |
| 23 | + List, |
| 24 | + Get { |
| 25 | + key: String, |
| 26 | + #[arg(short, long)] |
| 27 | + out: Option<String>, |
| 28 | + }, |
| 29 | +} |
| 30 | + |
| 31 | +#[wstd::main] |
| 32 | +async fn main() -> Result<()> { |
| 33 | + let opts = Opts::parse(); |
| 34 | + let config = aws_config::defaults(BehaviorVersion::latest()) |
| 35 | + .region(Region::new(opts.region.clone())) |
| 36 | + .sleep_impl(wstd_aws::sleep_impl()) |
| 37 | + .http_client(wstd_aws::http_client()) |
| 38 | + .load() |
| 39 | + .await; |
| 40 | + |
| 41 | + let client = Client::new(&config); |
| 42 | + |
| 43 | + match opts.command.as_ref().unwrap_or(&Command::List) { |
| 44 | + Command::List => list(&opts, &client).await, |
| 45 | + Command::Get { key, out } => { |
| 46 | + let contents = get(&opts, &client, &key).await?; |
| 47 | + let output: &str = if let Some(out) = out { |
| 48 | + out.as_str() |
| 49 | + } else { |
| 50 | + key.as_str() |
| 51 | + }; |
| 52 | + std::fs::write(output, contents)?; |
| 53 | + Ok(()) |
| 54 | + } |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +async fn list(opts: &Opts, client: &Client) -> Result<()> { |
| 59 | + let mut listing = client |
| 60 | + .list_objects_v2() |
| 61 | + .bucket(opts.bucket.clone()) |
| 62 | + .into_paginator() |
| 63 | + .send(); |
| 64 | + |
| 65 | + println!("key\tetag\tlast_modified\tstorage_class"); |
| 66 | + while let Some(res) = listing.next().await { |
| 67 | + let object = res?; |
| 68 | + for item in object.contents() { |
| 69 | + println!( |
| 70 | + "{}\t{}\t{}\t{}", |
| 71 | + item.key().unwrap_or_default(), |
| 72 | + item.e_tag().unwrap_or_default(), |
| 73 | + item.last_modified() |
| 74 | + .map(|lm| format!("{lm}")) |
| 75 | + .unwrap_or_default(), |
| 76 | + item.storage_class() |
| 77 | + .map(|sc| format!("{sc}")) |
| 78 | + .unwrap_or_default(), |
| 79 | + ); |
| 80 | + } |
| 81 | + } |
| 82 | + Ok(()) |
| 83 | +} |
| 84 | + |
| 85 | +async fn get(opts: &Opts, client: &Client, key: &str) -> Result<Vec<u8>> { |
| 86 | + let object = client |
| 87 | + .get_object() |
| 88 | + .bucket(opts.bucket.clone()) |
| 89 | + .key(key) |
| 90 | + .send() |
| 91 | + .await?; |
| 92 | + let data = object.body.collect().await?; |
| 93 | + Ok(data.to_vec()) |
| 94 | +} |
0 commit comments