1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
use rusoto_s3::{ Delete, DeleteObjectsRequest, GetObjectRequest, GetObjectTaggingRequest, Object, ObjectIdentifier, PutObjectAclRequest, PutObjectTaggingRequest, S3, S3Client, Tagging, }; use std::process::Command; use std::process::ExitStatus; use std::fs; use std::fs::File; use std::io::Write; use std::path::Path; use rusoto_core::Region; use failure::Error; use futures::stream::Stream; use futures::Future; use indicatif::{ProgressBar, ProgressStyle}; use error::*; pub fn fprint(bucket: &str, item: &Object) { println!( "s3://{}/{}", bucket, item.key.as_ref().unwrap_or(&"".to_string()) ); } pub fn advanced_print(bucket: &str, item: &Object) { println!( "{} {:?} {} {} s3://{}/{} {}", item.e_tag.as_ref().unwrap_or(&"NoEtag".to_string()), item.owner.as_ref().map(|x| x.display_name.as_ref()), item.size.as_ref().unwrap_or(&0), item.last_modified.as_ref().unwrap_or(&"NoTime".to_string()), bucket, item.key.as_ref().unwrap_or(&"".to_string()), item.storage_class .as_ref() .unwrap_or(&"NoStorage".to_string()), ); } #[derive(Debug, PartialEq, Clone)] pub struct ExecStatus { pub status: ExitStatus, pub runcommand: String, } pub fn exec(command: &str, key: &str) -> Result<ExecStatus, Error> { let scommand = command.replace("{}", key); let mut command_args = scommand.split(' '); let command_name = command_args.next().ok_or(FunctionError::CommandlineParse)?; let mut rcommand = Command::new(command_name); for arg in command_args { rcommand.arg(arg); } let output = rcommand.output()?; let output_str = String::from_utf8_lossy(&output.stdout).to_string(); print!("{}", &output_str); Ok(ExecStatus { status: output.status, runcommand: scommand.clone(), }) } pub fn s3_delete(client: &S3Client, bucket: &str, list: &[&Object]) -> Result<(), Error> { let key_list: Vec<_> = list .iter() .map(|x| ObjectIdentifier { key: x.key.as_ref().unwrap().to_string(), version_id: None, }) .collect(); let request = DeleteObjectsRequest { bucket: bucket.to_string(), delete: Delete { objects: key_list, quiet: None, }, mfa: None, request_payer: None, }; let result = client.delete_objects(request).sync()?; if let Some(deleted_list) = result.deleted { for object in deleted_list { println!( "deleted: s3://{}/{}", bucket, object.key.as_ref().unwrap_or(&"".to_string()) ); } } Ok(()) } pub fn s3_download( client: &S3Client, bucket: &str, list: &[&Object], target: &str, force: bool, ) -> Result<(), Error> { for object in list { let key = object.key.as_ref().unwrap(); let request = GetObjectRequest { bucket: bucket.to_owned(), key: key.to_owned(), ..Default::default() }; let size = (*object.size.as_ref().unwrap()) as u64; let file_path = Path::new(target).join(key); let dir_path = file_path.parent().ok_or(FunctionError::ParentPathParse)?; let mut count: u64 = 0; let pb = ProgressBar::new(size); pb.set_style(ProgressStyle::default_bar() .template("{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({eta})") .progress_chars("#>-")); println!( "downloading: s3://{}/{} => {}", bucket, &key, file_path.to_str().ok_or(FunctionError::FileNameParseError)? ); if file_path.exists() && !force { return Err(FunctionError::PresentFileError.into()); } let result = client.get_object(request).sync()?; let mut stream = result.body.ok_or(FunctionError::S3FetchBodyError)?; fs::create_dir_all(&dir_path)?; let mut output = File::create(&file_path)?; let _r = stream .for_each(|buf| { output.write_all(&buf)?; count += buf.len() as u64; pb.set_position(count); Ok(()) }) .wait(); } Ok(()) } pub fn s3_set_tags( client: &S3Client, bucket: &str, list: &[&Object], tags: &Tagging, ) -> Result<(), Error> { for object in list { let key = object.key.as_ref().unwrap(); let request = PutObjectTaggingRequest { bucket: bucket.to_owned(), key: key.to_owned(), tagging: tags.clone(), ..Default::default() }; client.put_object_tagging(request).sync()?; println!("tags are set for: s3://{}/{}", bucket, &key); } Ok(()) } pub fn s3_list_tags(client: &S3Client, bucket: &str, list: &[&Object]) -> Result<(), Error> { for object in list { let key = object.key.as_ref().unwrap(); let request = GetObjectTaggingRequest { bucket: bucket.to_owned(), key: key.to_owned(), ..Default::default() }; let tag_output = client.get_object_tagging(request).sync()?; let tags: String = tag_output .tag_set .into_iter() .map(|x| format!("{}:{}", x.key, x.value)) .collect::<Vec<String>>() .join(","); println!( "s3://{}/{} {}", bucket, object.key.as_ref().unwrap_or(&"".to_string()), tags, ); } Ok(()) } fn s3_public_url(key: &str, bucket: &str, region: &str) -> String { match region { "us-east-1" => format!("http://{}.s3.amazonaws.com/{}", bucket, key), _ => format!("http://{}.s3-{}.amazonaws.com/{}", bucket, region, key), } } pub fn s3_set_public( client: &S3Client, bucket: &str, list: &[&Object], region: &Region, ) -> Result<(), Error> { let region_str = region.name(); for object in list { let key = object.key.as_ref().unwrap(); let request = PutObjectAclRequest { bucket: bucket.to_owned(), key: key.to_owned(), acl: Some("public-read".to_string()), ..Default::default() }; client.put_object_acl(request).sync()?; let url = s3_public_url(key, bucket, region_str); println!("{} {}", &key, url); } Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn exec_true() { let exec_status = exec("true", "").unwrap(); assert!(exec_status.status.success(), "Exit code of true is 0"); } #[test] fn exec_false() { let exec_status = exec("false", ""); assert!( !exec_status.unwrap().status.success(), "Exit code of false is 1" ); } #[test] fn exec_echo_multiple() { let exec_status = exec("echo Hello world1", "").unwrap(); assert!(exec_status.status.success(), "Exit code of echo is 0"); assert_eq!( exec_status.runcommand, "echo Hello world1", "Output of echo is 'Hello world1'" ); } #[test] #[should_panic] fn exec_incorrect_command() { let exec_status = exec("jbrwuDxPy4ck", ""); assert!( !exec_status.unwrap().status.success(), "Exit code should not be success" ); } #[test] fn exec_echo_interpolation() { let exec_status = exec("echo Hello {}", "world2").unwrap(); assert!(exec_status.status.success(), "Exit code of echo is 0"); assert_eq!( exec_status.runcommand, "echo Hello world2", "String should interpolated and printed" ); } #[test] fn advanced_print_test() { let object = Object { e_tag: Some("9d48114aa7c18f9d68aa20086dbb7756".to_string()), key: Some("somepath/otherpath".to_string()), last_modified: Some("2017-07-19T19:04:17.000Z".to_string()), owner: None, size: Some(4997288), storage_class: Some("STANDARD".to_string()), }; advanced_print("bucket", &object); } }