rustfs-cli 0.1.12

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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
//! ilm rule command - Manage bucket lifecycle rules
//!
//! Add, edit, list, remove, export, and import lifecycle rules on a bucket.

use clap::{Args, Subcommand};
use comfy_table::{ContentArrangement, Table};
use rc_core::{
    AliasManager, LifecycleConfiguration, LifecycleExpiration, LifecycleRule, LifecycleRuleStatus,
    LifecycleTransition, NoncurrentVersionExpiration, NoncurrentVersionTransition,
    ObjectStore as _,
};
use rc_s3::S3Client;
use serde::Serialize;

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

#[derive(Subcommand, Debug)]
pub enum RuleCommands {
    /// Add a new lifecycle rule to a bucket
    Add(AddRuleArgs),

    /// Edit an existing lifecycle rule
    Edit(EditRuleArgs),

    /// List lifecycle rules on a bucket
    List(BucketArg),

    /// Remove lifecycle rules from a bucket
    Remove(RemoveRuleArgs),

    /// Export lifecycle rules as JSON
    Export(BucketArg),

    /// Import lifecycle rules from a JSON file
    Import(ImportRuleArgs),
}

#[derive(Args, Debug)]
pub struct BucketArg {
    /// Path to the bucket (alias/bucket)
    pub path: String,

    /// Force operation even if capability detection fails
    #[arg(long)]
    pub force: bool,
}

#[derive(Args, Debug)]
pub struct AddRuleArgs {
    /// Path to the bucket (alias/bucket)
    pub path: String,

    /// Expiration days for current versions
    #[arg(long)]
    pub expiry_days: Option<i32>,

    /// Expiration date for current versions (ISO 8601)
    #[arg(long)]
    pub expiry_date: Option<String>,

    /// Transition days for current versions
    #[arg(long)]
    pub transition_days: Option<i32>,

    /// Transition date for current versions (ISO 8601)
    #[arg(long)]
    pub transition_date: Option<String>,

    /// Target storage class for transition
    #[arg(long)]
    pub storage_class: Option<String>,

    /// Expiration days for noncurrent versions
    #[arg(long)]
    pub noncurrent_expiry_days: Option<i32>,

    /// Transition days for noncurrent versions
    #[arg(long)]
    pub noncurrent_transition_days: Option<i32>,

    /// Storage class for noncurrent version transition
    #[arg(long)]
    pub noncurrent_transition_storage_class: Option<String>,

    /// Key prefix filter
    #[arg(long)]
    pub prefix: Option<String>,

    /// Remove expired delete markers
    #[arg(long)]
    pub expired_object_delete_marker: bool,

    /// Maximum number of noncurrent versions to retain
    #[arg(long)]
    pub newer_noncurrent_versions: Option<i32>,

    /// Create the rule in disabled state
    #[arg(long)]
    pub disable: bool,

    /// Force operation even if capability detection fails
    #[arg(long)]
    pub force: bool,
}

#[derive(Args, Debug)]
pub struct EditRuleArgs {
    /// Path to the bucket (alias/bucket)
    pub path: String,

    /// ID of the rule to edit
    #[arg(long)]
    pub id: String,

    /// Expiration days for current versions
    #[arg(long)]
    pub expiry_days: Option<i32>,

    /// Expiration date for current versions (ISO 8601)
    #[arg(long)]
    pub expiry_date: Option<String>,

    /// Transition days for current versions
    #[arg(long)]
    pub transition_days: Option<i32>,

    /// Transition date for current versions (ISO 8601)
    #[arg(long)]
    pub transition_date: Option<String>,

    /// Target storage class for transition
    #[arg(long)]
    pub storage_class: Option<String>,

    /// Expiration days for noncurrent versions
    #[arg(long)]
    pub noncurrent_expiry_days: Option<i32>,

    /// Transition days for noncurrent versions
    #[arg(long)]
    pub noncurrent_transition_days: Option<i32>,

    /// Storage class for noncurrent version transition
    #[arg(long)]
    pub noncurrent_transition_storage_class: Option<String>,

    /// Key prefix filter
    #[arg(long)]
    pub prefix: Option<String>,

    /// Remove expired delete markers
    #[arg(long)]
    pub expired_object_delete_marker: Option<bool>,

    /// Maximum number of noncurrent versions to retain
    #[arg(long)]
    pub newer_noncurrent_versions: Option<i32>,

    /// Set the rule to disabled state
    #[arg(long)]
    pub disable: Option<bool>,

    /// Force operation even if capability detection fails
    #[arg(long)]
    pub force: bool,
}

#[derive(Args, Debug)]
pub struct RemoveRuleArgs {
    /// Path to the bucket (alias/bucket)
    pub path: String,

    /// ID of the rule to remove
    #[arg(long)]
    pub id: Option<String>,

    /// Remove all lifecycle rules
    #[arg(long)]
    pub all: bool,

    /// Force operation even if capability detection fails
    #[arg(long)]
    pub force: bool,
}

#[derive(Args, Debug)]
pub struct ImportRuleArgs {
    /// Path to the bucket (alias/bucket)
    pub path: String,

    /// Path to the JSON file containing lifecycle rules
    pub file: String,

    /// Force operation even if capability detection fails
    #[arg(long)]
    pub force: bool,
}

#[derive(Debug, Serialize)]
struct RuleListOutput {
    bucket: String,
    rules: Vec<LifecycleRule>,
}

#[derive(Debug, Serialize)]
struct RuleOperationOutput {
    bucket: String,
    rule_id: String,
    action: String,
}

/// Execute a rule subcommand
pub async fn execute(cmd: RuleCommands, output_config: OutputConfig) -> ExitCode {
    match cmd {
        RuleCommands::Add(args) => execute_add(args, output_config).await,
        RuleCommands::Edit(args) => execute_edit(args, output_config).await,
        RuleCommands::List(args) => execute_list(args, output_config).await,
        RuleCommands::Remove(args) => execute_remove(args, output_config).await,
        RuleCommands::Export(args) => execute_export(args, output_config).await,
        RuleCommands::Import(args) => execute_import(args, output_config).await,
    }
}

async fn execute_add(args: AddRuleArgs, output_config: OutputConfig) -> ExitCode {
    let formatter = Formatter::new(output_config);

    let (alias_name, bucket) = match parse_bucket_path(&args.path) {
        Ok(parts) => parts,
        Err(error) => {
            formatter.error(&error);
            return ExitCode::UsageError;
        }
    };

    let client = match setup_client(&alias_name, &bucket, args.force, &formatter).await {
        Ok(client) => client,
        Err(code) => return code,
    };

    // Get existing rules
    let mut rules = match client.get_bucket_lifecycle(&bucket).await {
        Ok(rules) => rules,
        Err(error) => {
            formatter.error(&format!("Failed to get lifecycle rules: {error}"));
            return ExitCode::GeneralError;
        }
    };

    // Generate rule ID
    let rule_id = generate_rule_id();

    let status = if args.disable {
        LifecycleRuleStatus::Disabled
    } else {
        LifecycleRuleStatus::Enabled
    };

    // Build expiration
    let expiration = if args.expiry_days.is_some() || args.expiry_date.is_some() {
        Some(LifecycleExpiration {
            days: args.expiry_days,
            date: args.expiry_date,
        })
    } else {
        None
    };

    // Build transition
    let transition = match (
        &args.transition_days,
        &args.transition_date,
        &args.storage_class,
    ) {
        (Some(_), _, Some(sc)) | (_, Some(_), Some(sc)) => Some(LifecycleTransition {
            days: args.transition_days,
            date: args.transition_date.clone(),
            storage_class: sc.clone(),
        }),
        (Some(_), _, None) | (_, Some(_), None) => {
            formatter.error(
                "--storage-class is required when using --transition-days or --transition-date",
            );
            return ExitCode::UsageError;
        }
        _ => None,
    };

    // Build noncurrent version expiration
    let noncurrent_version_expiration =
        args.noncurrent_expiry_days
            .map(|days| NoncurrentVersionExpiration {
                noncurrent_days: days,
                newer_noncurrent_versions: args.newer_noncurrent_versions,
            });

    // Build noncurrent version transition
    let noncurrent_version_transition = match (
        args.noncurrent_transition_days,
        &args.noncurrent_transition_storage_class,
    ) {
        (Some(days), Some(sc)) => Some(NoncurrentVersionTransition {
            noncurrent_days: days,
            storage_class: sc.clone(),
        }),
        (Some(_), None) => {
            formatter.error("--noncurrent-transition-storage-class is required when using --noncurrent-transition-days");
            return ExitCode::UsageError;
        }
        _ => None,
    };

    let expired_object_delete_marker = if args.expired_object_delete_marker {
        Some(true)
    } else {
        None
    };

    let new_rule = LifecycleRule {
        id: rule_id.clone(),
        status,
        prefix: args.prefix,
        tags: None,
        expiration,
        transition,
        noncurrent_version_expiration,
        noncurrent_version_transition,
        abort_incomplete_multipart_upload_days: None,
        expired_object_delete_marker,
    };

    rules.push(new_rule);

    match client.set_bucket_lifecycle(&bucket, rules).await {
        Ok(()) => {
            if formatter.is_json() {
                formatter.json(&RuleOperationOutput {
                    bucket,
                    rule_id,
                    action: "added".to_string(),
                });
            } else {
                formatter.success(&format!("Lifecycle rule '{rule_id}' added successfully."));
            }
            ExitCode::Success
        }
        Err(error) => {
            formatter.error(&format!("Failed to set lifecycle rules: {error}"));
            ExitCode::GeneralError
        }
    }
}

async fn execute_edit(args: EditRuleArgs, output_config: OutputConfig) -> ExitCode {
    let formatter = Formatter::new(output_config);

    let (alias_name, bucket) = match parse_bucket_path(&args.path) {
        Ok(parts) => parts,
        Err(error) => {
            formatter.error(&error);
            return ExitCode::UsageError;
        }
    };

    let client = match setup_client(&alias_name, &bucket, args.force, &formatter).await {
        Ok(client) => client,
        Err(code) => return code,
    };

    let mut rules = match client.get_bucket_lifecycle(&bucket).await {
        Ok(rules) => rules,
        Err(error) => {
            formatter.error(&format!("Failed to get lifecycle rules: {error}"));
            return ExitCode::GeneralError;
        }
    };

    let rule = match rules.iter_mut().find(|r| r.id == args.id) {
        Some(rule) => rule,
        None => {
            formatter.error(&format!("Rule '{}' not found", args.id));
            return ExitCode::NotFound;
        }
    };

    // Update status if requested
    if let Some(disable) = args.disable {
        rule.status = if disable {
            LifecycleRuleStatus::Disabled
        } else {
            LifecycleRuleStatus::Enabled
        };
    }

    // Update prefix if provided
    if args.prefix.is_some() {
        rule.prefix = args.prefix;
    }

    // Update expiration if provided
    if args.expiry_days.is_some() || args.expiry_date.is_some() {
        rule.expiration = Some(LifecycleExpiration {
            days: args
                .expiry_days
                .or_else(|| rule.expiration.as_ref().and_then(|e| e.days)),
            date: args
                .expiry_date
                .or_else(|| rule.expiration.as_ref().and_then(|e| e.date.clone())),
        });
    }

    // Update transition if provided
    if args.transition_days.is_some()
        || args.transition_date.is_some()
        || args.storage_class.is_some()
    {
        let current_sc = rule
            .transition
            .as_ref()
            .map(|t| t.storage_class.clone())
            .unwrap_or_default();
        let sc = args.storage_class.unwrap_or(current_sc);
        if sc.is_empty() {
            formatter.error("--storage-class is required for transition");
            return ExitCode::UsageError;
        }
        rule.transition = Some(LifecycleTransition {
            days: args
                .transition_days
                .or_else(|| rule.transition.as_ref().and_then(|t| t.days)),
            date: args
                .transition_date
                .or_else(|| rule.transition.as_ref().and_then(|t| t.date.clone())),
            storage_class: sc,
        });
    }

    // Update noncurrent version expiration if provided
    if args.noncurrent_expiry_days.is_some() || args.newer_noncurrent_versions.is_some() {
        let current = rule.noncurrent_version_expiration.as_ref();
        rule.noncurrent_version_expiration = Some(NoncurrentVersionExpiration {
            noncurrent_days: args
                .noncurrent_expiry_days
                .unwrap_or_else(|| current.map(|c| c.noncurrent_days).unwrap_or(0)),
            newer_noncurrent_versions: args
                .newer_noncurrent_versions
                .or_else(|| current.and_then(|c| c.newer_noncurrent_versions)),
        });
    }

    // Update noncurrent version transition if provided
    if args.noncurrent_transition_days.is_some()
        || args.noncurrent_transition_storage_class.is_some()
    {
        let current = rule.noncurrent_version_transition.as_ref();
        let sc = args
            .noncurrent_transition_storage_class
            .or_else(|| current.map(|c| c.storage_class.clone()))
            .unwrap_or_default();
        if sc.is_empty() {
            formatter.error(
                "--noncurrent-transition-storage-class is required for noncurrent transition",
            );
            return ExitCode::UsageError;
        }
        rule.noncurrent_version_transition = Some(NoncurrentVersionTransition {
            noncurrent_days: args
                .noncurrent_transition_days
                .unwrap_or_else(|| current.map(|c| c.noncurrent_days).unwrap_or(0)),
            storage_class: sc,
        });
    }

    // Update expired object delete marker if provided
    if let Some(val) = args.expired_object_delete_marker {
        rule.expired_object_delete_marker = Some(val);
    }

    match client.set_bucket_lifecycle(&bucket, rules).await {
        Ok(()) => {
            if formatter.is_json() {
                formatter.json(&RuleOperationOutput {
                    bucket,
                    rule_id: args.id,
                    action: "edited".to_string(),
                });
            } else {
                formatter.success("Lifecycle rule updated successfully.");
            }
            ExitCode::Success
        }
        Err(error) => {
            formatter.error(&format!("Failed to set lifecycle rules: {error}"));
            ExitCode::GeneralError
        }
    }
}

async fn execute_list(args: BucketArg, output_config: OutputConfig) -> ExitCode {
    let formatter = Formatter::new(output_config);

    let (alias_name, bucket) = match parse_bucket_path(&args.path) {
        Ok(parts) => parts,
        Err(error) => {
            formatter.error(&error);
            return ExitCode::UsageError;
        }
    };

    let client = match setup_client(&alias_name, &bucket, args.force, &formatter).await {
        Ok(client) => client,
        Err(code) => return code,
    };

    let rules = client
        .get_bucket_lifecycle(&bucket)
        .await
        .unwrap_or_default();

    if formatter.is_json() {
        formatter.json(&RuleListOutput { bucket, rules });
        return ExitCode::Success;
    }

    if rules.is_empty() {
        formatter.println("No lifecycle rules found.");
        return ExitCode::Success;
    }

    let mut table = Table::new();
    table.set_content_arrangement(ContentArrangement::Dynamic);
    table.set_header(vec![
        "ID",
        "Status",
        "Prefix",
        "Expiry",
        "Transition",
        "Storage Class",
    ]);

    for rule in &rules {
        let prefix = rule.prefix.as_deref().unwrap_or("-");
        let expiry = format_expiry(rule);
        let transition = format_transition(rule);
        let storage_class = rule
            .transition
            .as_ref()
            .map(|t| t.storage_class.as_str())
            .unwrap_or("-");

        table.add_row(vec![
            &rule.id,
            &rule.status.to_string(),
            prefix,
            &expiry,
            &transition,
            storage_class,
        ]);
    }

    formatter.println(&table.to_string());
    ExitCode::Success
}

async fn execute_remove(args: RemoveRuleArgs, output_config: OutputConfig) -> ExitCode {
    let formatter = Formatter::new(output_config);

    if args.id.is_none() && !args.all {
        formatter.error("Either --id or --all is required");
        return ExitCode::UsageError;
    }

    let (alias_name, bucket) = match parse_bucket_path(&args.path) {
        Ok(parts) => parts,
        Err(error) => {
            formatter.error(&error);
            return ExitCode::UsageError;
        }
    };

    let client = match setup_client(&alias_name, &bucket, args.force, &formatter).await {
        Ok(client) => client,
        Err(code) => return code,
    };

    if args.all {
        match client.delete_bucket_lifecycle(&bucket).await {
            Ok(()) => {
                if formatter.is_json() {
                    formatter.json(&RuleOperationOutput {
                        bucket,
                        rule_id: "*".to_string(),
                        action: "removed_all".to_string(),
                    });
                } else {
                    formatter.success("All lifecycle rules removed.");
                }
                return ExitCode::Success;
            }
            Err(error) => {
                formatter.error(&format!(
                    "Failed to delete lifecycle configuration: {error}"
                ));
                return ExitCode::GeneralError;
            }
        }
    }

    // Remove by ID
    let rule_id = args.id.as_deref().unwrap_or("");
    let mut rules = match client.get_bucket_lifecycle(&bucket).await {
        Ok(rules) => rules,
        Err(error) => {
            formatter.error(&format!("Failed to get lifecycle rules: {error}"));
            return ExitCode::GeneralError;
        }
    };

    let before = rules.len();
    rules.retain(|r| r.id != rule_id);
    if rules.len() == before {
        formatter.error(&format!("Rule '{rule_id}' not found"));
        return ExitCode::NotFound;
    }

    let result = if rules.is_empty() {
        client.delete_bucket_lifecycle(&bucket).await
    } else {
        client.set_bucket_lifecycle(&bucket, rules).await
    };

    match result {
        Ok(()) => {
            if formatter.is_json() {
                formatter.json(&RuleOperationOutput {
                    bucket,
                    rule_id: rule_id.to_string(),
                    action: "removed".to_string(),
                });
            } else {
                formatter.success(&format!("Lifecycle rule '{rule_id}' removed."));
            }
            ExitCode::Success
        }
        Err(error) => {
            formatter.error(&format!("Failed to update lifecycle rules: {error}"));
            ExitCode::GeneralError
        }
    }
}

async fn execute_export(args: BucketArg, output_config: OutputConfig) -> ExitCode {
    let formatter = Formatter::new(output_config);

    let (alias_name, bucket) = match parse_bucket_path(&args.path) {
        Ok(parts) => parts,
        Err(error) => {
            formatter.error(&error);
            return ExitCode::UsageError;
        }
    };

    let client = match setup_client(&alias_name, &bucket, args.force, &formatter).await {
        Ok(client) => client,
        Err(code) => return code,
    };

    let rules = client
        .get_bucket_lifecycle(&bucket)
        .await
        .unwrap_or_default();

    let config = LifecycleConfiguration { rules };
    formatter.json(&config);
    ExitCode::Success
}

async fn execute_import(args: ImportRuleArgs, output_config: OutputConfig) -> ExitCode {
    let formatter = Formatter::new(output_config);

    let (alias_name, bucket) = match parse_bucket_path(&args.path) {
        Ok(parts) => parts,
        Err(error) => {
            formatter.error(&error);
            return ExitCode::UsageError;
        }
    };

    let file_contents = match std::fs::read_to_string(&args.file) {
        Ok(contents) => contents,
        Err(error) => {
            formatter.error(&format!("Failed to read file '{}': {error}", args.file));
            return ExitCode::GeneralError;
        }
    };

    let config: LifecycleConfiguration = match serde_json::from_str(&file_contents) {
        Ok(config) => config,
        Err(error) => {
            formatter.error(&format!("Failed to parse lifecycle configuration: {error}"));
            return ExitCode::UsageError;
        }
    };

    let client = match setup_client(&alias_name, &bucket, args.force, &formatter).await {
        Ok(client) => client,
        Err(code) => return code,
    };

    let rule_count = config.rules.len();
    match client.set_bucket_lifecycle(&bucket, config.rules).await {
        Ok(()) => {
            if formatter.is_json() {
                formatter.json(&serde_json::json!({
                    "bucket": bucket,
                    "rulesImported": rule_count,
                    "action": "imported",
                }));
            } else {
                formatter.success(&format!(
                    "Imported {rule_count} lifecycle rule(s) to bucket '{bucket}'."
                ));
            }
            ExitCode::Success
        }
        Err(error) => {
            formatter.error(&format!("Failed to set lifecycle rules: {error}"));
            ExitCode::GeneralError
        }
    }
}

// ==================== Helpers ====================

async fn setup_client(
    alias_name: &str,
    bucket: &str,
    force: bool,
    formatter: &Formatter,
) -> Result<S3Client, ExitCode> {
    let alias_manager = match AliasManager::new() {
        Ok(manager) => manager,
        Err(error) => {
            formatter.error(&format!("Failed to load aliases: {error}"));
            return Err(ExitCode::GeneralError);
        }
    };

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

    let client = match S3Client::new(alias).await {
        Ok(client) => client,
        Err(error) => {
            formatter.error(&format!("Failed to create S3 client: {error}"));
            return Err(ExitCode::NetworkError);
        }
    };

    let caps = match client.capabilities().await {
        Ok(caps) => caps,
        Err(error) => {
            if force {
                rc_core::Capabilities::default()
            } else {
                formatter.error(&format!("Failed to detect capabilities: {error}"));
                return Err(ExitCode::NetworkError);
            }
        }
    };

    if !force && !caps.lifecycle {
        formatter.error("Backend does not support lifecycle. Use --force to attempt anyway.");
        return Err(ExitCode::UnsupportedFeature);
    }

    match client.bucket_exists(bucket).await {
        Ok(true) => {}
        Ok(false) => {
            formatter.error(&format!("Bucket '{bucket}' does not exist"));
            return Err(ExitCode::NotFound);
        }
        Err(error) => {
            formatter.error(&format!("Failed to check bucket: {error}"));
            return Err(ExitCode::NetworkError);
        }
    }

    Ok(client)
}

fn parse_bucket_path(path: &str) -> Result<(String, String), String> {
    if path.is_empty() {
        return Err("Path cannot be empty".to_string());
    }

    let parts: Vec<&str> = path.split('/').collect();
    if parts.len() < 2 || parts[0].is_empty() || parts[1].is_empty() {
        return Err("Bucket path must be in format alias/bucket".to_string());
    }

    if parts.iter().skip(2).any(|part| !part.is_empty()) {
        return Err("Bucket path must not include an object key".to_string());
    }

    Ok((parts[0].to_string(), parts[1].to_string()))
}

fn generate_rule_id() -> String {
    use std::time::{SystemTime, UNIX_EPOCH};

    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos();
    // Use lower 32 bits of nanosecond timestamp as a simple unique suffix
    let suffix = format!("{:08x}", (nanos & 0xFFFF_FFFF) as u32);
    format!("rule-{suffix}")
}

fn format_expiry(rule: &LifecycleRule) -> String {
    if let Some(exp) = &rule.expiration {
        if let Some(days) = exp.days {
            return format!("{days} day(s)");
        }
        if let Some(date) = &exp.date {
            return date.clone();
        }
    }
    "-".to_string()
}

fn format_transition(rule: &LifecycleRule) -> String {
    if let Some(tr) = &rule.transition {
        if let Some(days) = tr.days {
            return format!("{days} day(s)");
        }
        if let Some(date) = &tr.date {
            return date.clone();
        }
    }
    "-".to_string()
}

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

    #[test]
    fn test_parse_bucket_path_success() {
        let (alias, bucket) = parse_bucket_path("local/my-bucket").expect("should parse");
        assert_eq!(alias, "local");
        assert_eq!(bucket, "my-bucket");

        let (alias, bucket) = parse_bucket_path("local/my-bucket/").expect("should parse");
        assert_eq!(alias, "local");
        assert_eq!(bucket, "my-bucket");
    }

    #[test]
    fn test_parse_bucket_path_error() {
        assert!(parse_bucket_path("").is_err());
        assert!(parse_bucket_path("local").is_err());
        assert!(parse_bucket_path("/bucket").is_err());
        assert!(parse_bucket_path("local/my-bucket/key.txt").is_err());
        assert!(parse_bucket_path("local/my-bucket/path/to/key.txt").is_err());
    }

    #[test]
    fn test_generate_rule_id_format() {
        let id = generate_rule_id();
        assert!(id.starts_with("rule-"));
        assert_eq!(id.len(), 13); // "rule-" (5) + 8 hex chars
    }

    #[test]
    fn test_format_expiry_days() {
        let rule = LifecycleRule {
            id: "test".to_string(),
            status: LifecycleRuleStatus::Enabled,
            prefix: None,
            tags: None,
            expiration: Some(LifecycleExpiration {
                days: Some(30),
                date: None,
            }),
            transition: None,
            noncurrent_version_expiration: None,
            noncurrent_version_transition: None,
            abort_incomplete_multipart_upload_days: None,
            expired_object_delete_marker: None,
        };
        assert_eq!(format_expiry(&rule), "30 day(s)");
    }

    #[test]
    fn test_format_transition_none() {
        let rule = LifecycleRule {
            id: "test".to_string(),
            status: LifecycleRuleStatus::Enabled,
            prefix: None,
            tags: None,
            expiration: None,
            transition: None,
            noncurrent_version_expiration: None,
            noncurrent_version_transition: None,
            abort_incomplete_multipart_upload_days: None,
            expired_object_delete_marker: None,
        };
        assert_eq!(format_transition(&rule), "-");
    }

    #[tokio::test]
    async fn test_execute_add_invalid_path_returns_usage_error() {
        let args = AddRuleArgs {
            path: "invalid-path".to_string(),
            expiry_days: Some(30),
            expiry_date: None,
            transition_days: None,
            transition_date: None,
            storage_class: None,
            noncurrent_expiry_days: None,
            noncurrent_transition_days: None,
            noncurrent_transition_storage_class: None,
            prefix: None,
            expired_object_delete_marker: false,
            newer_noncurrent_versions: None,
            disable: false,
            force: false,
        };

        let code = execute_add(args, OutputConfig::default()).await;
        assert_eq!(code, ExitCode::UsageError);
    }

    #[tokio::test]
    async fn test_execute_remove_no_id_or_all_returns_usage_error() {
        let args = RemoveRuleArgs {
            path: "local/my-bucket".to_string(),
            id: None,
            all: false,
            force: false,
        };

        let code = execute_remove(args, OutputConfig::default()).await;
        assert_eq!(code, ExitCode::UsageError);
    }
}