rustfs-cli 0.1.13

A Rust S3 CLI client for S3-compatible object storage
Documentation
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
//! diff command - Compare objects between two locations
//!
//! Shows differences between two S3 paths or between local and remote.

use clap::Args;
use rc_core::{AliasManager, ListOptions, ObjectStore as _, ParsedPath, RemotePath, parse_path};
use rc_s3::S3Client;
use serde::Serialize;
use std::collections::HashMap;
use std::path::Path;

use crate::exit_code::ExitCode;
use crate::output::{Formatter, OutputConfig};

/// Compare objects between two locations
#[derive(Args, Debug)]
pub struct DiffArgs {
    /// First path (alias/bucket/prefix or local path)
    pub first: String,

    /// Second path (alias/bucket/prefix or local path)
    pub second: String,

    /// Recursive comparison
    #[arg(short, long)]
    pub recursive: bool,

    /// Show only differences (default: show all)
    #[arg(long)]
    pub diff_only: bool,
}

#[derive(Debug, Serialize, Clone)]
pub struct DiffEntry {
    pub key: String,
    pub status: DiffStatus,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub first_size: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub second_size: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub first_modified: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub second_modified: Option<String>,
}

#[derive(Debug, Serialize, Clone, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum DiffStatus {
    Same,
    Different,
    OnlyFirst,
    OnlySecond,
}

#[derive(Debug, Serialize)]
struct DiffOutput {
    first: String,
    second: String,
    entries: Vec<DiffEntry>,
    summary: DiffSummary,
}

#[derive(Debug, Serialize)]
struct DiffSummary {
    same: usize,
    different: usize,
    only_first: usize,
    only_second: usize,
    total: usize,
}

#[derive(Debug, Clone)]
struct FileInfo {
    size: Option<i64>,
    modified: Option<String>,
    etag: Option<String>,
}

/// Execute the diff command
pub async fn execute(args: DiffArgs, output_config: OutputConfig) -> ExitCode {
    let formatter = Formatter::new(output_config);

    // Parse both paths
    let first_parsed = parse_path(&args.first);
    let second_parsed = parse_path(&args.second);

    // Both must be remote for now (local support can be added later)
    let (first_path, second_path) = match (&first_parsed, &second_parsed) {
        (Ok(ParsedPath::Remote(f)), Ok(ParsedPath::Remote(s))) => (f.clone(), s.clone()),
        (Ok(ParsedPath::Local(_)), _) | (_, Ok(ParsedPath::Local(_))) => {
            formatter.error("Local paths are not yet supported in diff command");
            return ExitCode::UsageError;
        }
        (Err(e), _) => {
            formatter.error(&format!("Invalid first path: {e}"));
            return ExitCode::UsageError;
        }
        (_, Err(e)) => {
            formatter.error(&format!("Invalid second path: {e}"));
            return ExitCode::UsageError;
        }
    };

    // Load aliases
    let alias_manager = match AliasManager::new() {
        Ok(am) => am,
        Err(e) => {
            formatter.error(&format!("Failed to load aliases: {e}"));
            return ExitCode::GeneralError;
        }
    };

    // Create clients for both paths
    let first_alias = match alias_manager.get(&first_path.alias) {
        Ok(a) => a,
        Err(_) => {
            formatter.error(&format!("Alias '{}' not found", first_path.alias));
            return ExitCode::NotFound;
        }
    };

    let second_alias = match alias_manager.get(&second_path.alias) {
        Ok(a) => a,
        Err(_) => {
            formatter.error(&format!("Alias '{}' not found", second_path.alias));
            return ExitCode::NotFound;
        }
    };

    let first_client = match S3Client::new(first_alias).await {
        Ok(c) => c,
        Err(e) => {
            formatter.error(&format!("Failed to create client for first path: {e}"));
            return ExitCode::NetworkError;
        }
    };

    let second_client = match S3Client::new(second_alias).await {
        Ok(c) => c,
        Err(e) => {
            formatter.error(&format!("Failed to create client for second path: {e}"));
            return ExitCode::NetworkError;
        }
    };

    // List objects from both paths
    let first_objects = match list_objects_map(&first_client, &first_path, args.recursive).await {
        Ok(o) => o,
        Err(e) => {
            formatter.error(&format!("Failed to list first path: {e}"));
            return ExitCode::NetworkError;
        }
    };

    let second_objects = match list_objects_map(&second_client, &second_path, args.recursive).await
    {
        Ok(o) => o,
        Err(e) => {
            formatter.error(&format!("Failed to list second path: {e}"));
            return ExitCode::NetworkError;
        }
    };

    // Compare objects
    let entries = compare_objects(&first_objects, &second_objects, args.diff_only);

    // Calculate summary
    let mut summary = DiffSummary {
        same: 0,
        different: 0,
        only_first: 0,
        only_second: 0,
        total: entries.len(),
    };

    for entry in &entries {
        match entry.status {
            DiffStatus::Same => summary.same += 1,
            DiffStatus::Different => summary.different += 1,
            DiffStatus::OnlyFirst => summary.only_first += 1,
            DiffStatus::OnlySecond => summary.only_second += 1,
        }
    }

    // Determine exit code before moving summary
    let has_differences =
        summary.different > 0 || summary.only_first > 0 || summary.only_second > 0;

    if formatter.is_json() {
        let output = DiffOutput {
            first: args.first.clone(),
            second: args.second.clone(),
            entries,
            summary,
        };
        formatter.json(&output);
    } else {
        // Print diff entries
        for entry in &entries {
            let status_char = match entry.status {
                DiffStatus::Same => "=",
                DiffStatus::Different => "≠",
                DiffStatus::OnlyFirst => "<",
                DiffStatus::OnlySecond => ">",
            };

            let size_info = match entry.status {
                DiffStatus::Same => entry.first_size.map(format_size).unwrap_or_default(),
                DiffStatus::Different => {
                    let first = entry.first_size.map(format_size).unwrap_or_default();
                    let second = entry.second_size.map(format_size).unwrap_or_default();
                    format!("{first} → {second}")
                }
                DiffStatus::OnlyFirst => entry.first_size.map(format_size).unwrap_or_default(),
                DiffStatus::OnlySecond => entry.second_size.map(format_size).unwrap_or_default(),
            };

            formatter.println(&format!("{status_char} {:<50} {size_info}", entry.key));
        }

        // Print summary
        formatter.println("");
        formatter.println(&format!(
            "Summary: {} same, {} different, {} only in first, {} only in second",
            summary.same, summary.different, summary.only_first, summary.only_second
        ));
    }

    // Return appropriate exit code
    if has_differences {
        ExitCode::GeneralError // Indicates differences found
    } else {
        ExitCode::Success
    }
}

async fn list_objects_map(
    client: &S3Client,
    path: &RemotePath,
    recursive: bool,
) -> Result<HashMap<String, FileInfo>, rc_core::Error> {
    let mut objects = HashMap::new();
    let mut continuation_token: Option<String> = None;
    let base_prefix = &path.key;

    loop {
        let options = ListOptions {
            recursive,
            max_keys: Some(1000),
            continuation_token: continuation_token.clone(),
            ..Default::default()
        };

        let result = client.list_objects(path, options).await?;

        for item in result.items {
            if item.is_dir {
                continue;
            }

            // Get relative key (remove base prefix)
            let relative_key = item.key.strip_prefix(base_prefix).unwrap_or(&item.key);
            let relative_key = relative_key.trim_start_matches('/').to_string();

            if relative_key.is_empty() {
                // Single object case
                let filename = Path::new(&item.key)
                    .file_name()
                    .map(|s| s.to_string_lossy().to_string())
                    .unwrap_or(item.key.clone());
                objects.insert(
                    filename,
                    FileInfo {
                        size: item.size_bytes,
                        modified: item.last_modified.map(|t| t.to_string()),
                        etag: item.etag,
                    },
                );
            } else {
                objects.insert(
                    relative_key,
                    FileInfo {
                        size: item.size_bytes,
                        modified: item.last_modified.map(|t| t.to_string()),
                        etag: item.etag,
                    },
                );
            }
        }

        if result.truncated {
            continuation_token = result.continuation_token;
        } else {
            break;
        }
    }

    Ok(objects)
}

fn compare_objects(
    first: &HashMap<String, FileInfo>,
    second: &HashMap<String, FileInfo>,
    diff_only: bool,
) -> Vec<DiffEntry> {
    let mut entries = Vec::new();

    // Check objects in first
    for (key, first_info) in first {
        if let Some(second_info) = second.get(key) {
            // Object exists in both
            let is_same = first_info.size == second_info.size
                && (first_info.etag == second_info.etag || first_info.etag.is_none());

            let status = if is_same {
                DiffStatus::Same
            } else {
                DiffStatus::Different
            };

            if !diff_only || status != DiffStatus::Same {
                entries.push(DiffEntry {
                    key: key.clone(),
                    status,
                    first_size: first_info.size,
                    second_size: second_info.size,
                    first_modified: first_info.modified.clone(),
                    second_modified: second_info.modified.clone(),
                });
            }
        } else {
            // Only in first
            entries.push(DiffEntry {
                key: key.clone(),
                status: DiffStatus::OnlyFirst,
                first_size: first_info.size,
                second_size: None,
                first_modified: first_info.modified.clone(),
                second_modified: None,
            });
        }
    }

    // Check objects only in second
    for (key, second_info) in second {
        if !first.contains_key(key) {
            entries.push(DiffEntry {
                key: key.clone(),
                status: DiffStatus::OnlySecond,
                first_size: None,
                second_size: second_info.size,
                first_modified: None,
                second_modified: second_info.modified.clone(),
            });
        }
    }

    // Sort by key
    entries.sort_by(|a, b| a.key.cmp(&b.key));
    entries
}

fn format_size(size: i64) -> String {
    humansize::format_size(size as u64, humansize::BINARY)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_compare_objects_same() {
        let mut first = HashMap::new();
        first.insert(
            "file.txt".to_string(),
            FileInfo {
                size: Some(100),
                modified: None,
                etag: Some("abc123".to_string()),
            },
        );

        let mut second = HashMap::new();
        second.insert(
            "file.txt".to_string(),
            FileInfo {
                size: Some(100),
                modified: None,
                etag: Some("abc123".to_string()),
            },
        );

        let entries = compare_objects(&first, &second, false);
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].status, DiffStatus::Same);
    }

    #[test]
    fn test_compare_objects_different() {
        let mut first = HashMap::new();
        first.insert(
            "file.txt".to_string(),
            FileInfo {
                size: Some(100),
                modified: None,
                etag: Some("abc123".to_string()),
            },
        );

        let mut second = HashMap::new();
        second.insert(
            "file.txt".to_string(),
            FileInfo {
                size: Some(200),
                modified: None,
                etag: Some("def456".to_string()),
            },
        );

        let entries = compare_objects(&first, &second, false);
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].status, DiffStatus::Different);
    }

    #[test]
    fn test_compare_objects_only_first() {
        let mut first = HashMap::new();
        first.insert(
            "file.txt".to_string(),
            FileInfo {
                size: Some(100),
                modified: None,
                etag: None,
            },
        );

        let second = HashMap::new();

        let entries = compare_objects(&first, &second, false);
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].status, DiffStatus::OnlyFirst);
    }

    #[test]
    fn test_compare_objects_only_second() {
        let first = HashMap::new();

        let mut second = HashMap::new();
        second.insert(
            "file.txt".to_string(),
            FileInfo {
                size: Some(100),
                modified: None,
                etag: None,
            },
        );

        let entries = compare_objects(&first, &second, false);
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].status, DiffStatus::OnlySecond);
    }
}