transfer_family_cli 0.3.0

TUI to browse and transfer files via AWS Transfer Family connector
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
//! TUI (terminal UI) for the Transfer Family Connector CLI.

use crate::config::Config;
use crate::error::Error;
use crate::listing::DirectoryListing;
use crate::types::RemotePath;
use ratatui::Frame;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Clear, List, ListItem, Paragraph, Wrap};
use std::path::PathBuf;
use std::str::FromStr;
use std::time::Instant;

/// Spinner frames (ASCII, 4 frames).
const SPINNER_FRAMES: &[char] = &['|', '/', '-', '\\'];
const SPINNER_MS_PER_FRAME: u128 = 80;

/// App state for the TUI.
#[non_exhaustive]
pub struct AppState {
    pub current_remote_path: RemotePath,
    pub listing: Option<DirectoryListing>,
    pub status_message: String,
    pub selected_index: usize,
    /// When loading, time at which the operation started (None = not loading).
    pub loading_started: Option<Instant>,
    pub download_dir: PathBuf,
    /// Command line buffer (e.g. "ls", "cd ..", "get file.txt", "put ./local.txt").
    pub cmd_buffer: String,
    /// When Some(path), show confirmation popup: "Delete path? (y/n)".
    pub pending_rm: Option<RemotePath>,
    /// When Some(pattern), filter listing by glob (e.g. "A*100*" for ls A*100*).
    pub listing_glob: Option<String>,
}

/// Matches `name` against glob `pattern`. Supports `*` (any sequence) and `?` (single char).
fn glob_match(pattern: &str, name: &str) -> bool {
    let p: Vec<char> = pattern.chars().collect();
    let n: Vec<char> = name.chars().collect();
    fn match_at(p: &[char], n: &[char]) -> bool {
        if p.is_empty() {
            return n.is_empty();
        }
        if p.first() == Some(&'*') {
            let rest = p.get(1..).unwrap_or_default();
            if rest.is_empty() {
                return true;
            }
            for i in 0..=n.len() {
                if match_at(rest, n.get(i..).unwrap_or_default()) {
                    return true;
                }
            }
            return false;
        }
        if n.is_empty() {
            return false;
        }
        if p.first() == Some(&'?') || p.first() == n.first() {
            return match_at(
                p.get(1..).unwrap_or_default(),
                n.get(1..).unwrap_or_default(),
            );
        }
        false
    }
    match_at(&p, &n)
}

impl AppState {
    #[must_use]
    pub fn new(config: &Config) -> Self {
        Self {
            current_remote_path: RemotePath::from("/"),
            listing: None,
            status_message: String::new(),
            selected_index: 0,
            loading_started: None,
            download_dir: config.download_dir.clone(),
            cmd_buffer: String::new(),
            pending_rm: None,
            listing_glob: None,
        }
    }

    /// Keeps `selected_index` within bounds of the current (filtered) listing.
    pub fn clamp_selected_index(&mut self) {
        let len = self.entries_for_display().len();
        if len > 0 {
            self.selected_index = self.selected_index.min(len - 1);
        } else {
            self.selected_index = 0;
        }
    }

    /// Returns (`display_line`, `is_dir`, path) for each entry, filtered by `listing_glob` when set.
    #[must_use]
    pub fn entries_for_display(&self) -> Vec<(String, bool, RemotePath)> {
        let mut entries = Vec::new();
        if let Some(ref listing) = self.listing {
            let filter = self.listing_glob.as_deref();
            for p in &listing.paths {
                let name = p.path.rsplit('/').next().unwrap_or(&p.path);
                if !name.is_empty() && filter.is_none_or(|g| glob_match(g, name)) {
                    let path = RemotePath::from(p.path.clone());
                    entries.push((format!("  {name}/"), true, path));
                }
            }
            for f in &listing.files {
                let name = f.file_path.rsplit('/').next().unwrap_or(&f.file_path);
                if !name.is_empty() && filter.is_none_or(|g| glob_match(g, name)) {
                    let path = RemotePath::from(f.file_path.clone());
                    let size = f
                        .size
                        .map(|s| format!("  {name} ({s} B)"))
                        .unwrap_or_else(|| format!("  {name}"));
                    entries.push((size, false, path));
                }
            }
        }
        entries
    }

    #[must_use]
    pub fn selected_file_path(&self) -> Option<RemotePath> {
        let entries = self.entries_for_display();
        let (_, is_dir, path) = entries.get(self.selected_index)?;
        if *is_dir { None } else { Some(path.clone()) }
    }

    #[must_use]
    pub fn selected_dir_path(&self) -> Option<RemotePath> {
        let entries = self.entries_for_display();
        let (_, is_dir, path) = entries.get(self.selected_index)?;
        if *is_dir { Some(path.clone()) } else { None }
    }

    /// Resolve "cd &lt;name&gt;" to full remote path from current listing. Name is the last segment (e.g. "foo" or "..").
    #[must_use]
    pub fn resolve_dir_name(&self, name: &str) -> Option<RemotePath> {
        if name == ".." {
            return None; // Caller handles cd ..
        }
        let listing = self.listing.as_ref()?;
        let name = name.trim_end_matches('/');
        for p in &listing.paths {
            let segment = p
                .path
                .trim_end_matches('/')
                .rsplit('/')
                .next()
                .unwrap_or(&p.path);
            if segment == name {
                return Some(RemotePath::from(p.path.clone()));
            }
        }
        None
    }

    /// Sets loading state for async operations (spinner, message).
    pub fn set_loading(&mut self, message: impl Into<String>) {
        self.loading_started = Some(Instant::now());
        self.status_message = message.into();
    }

    /// Clears loading state after async operation completes.
    pub const fn clear_loading(&mut self) {
        self.loading_started = None;
    }
}

/// Result of an async operation (listing, get, put, delete, move).
#[derive(Clone, Debug)]
pub enum AsyncResultAction {
    Listing(std::result::Result<DirectoryListing, Error>),
    Get(std::result::Result<(), Error>),
    Put(std::result::Result<(), Error>),
    Delete(std::result::Result<(), Error>),
    Move(std::result::Result<(), Error>),
}

impl AsyncResultAction {
    /// True if applying this result (and it succeeds) should trigger an automatic listing refresh.
    #[must_use]
    pub const fn should_refresh_listing_on_success(&self) -> bool {
        matches!(
            self,
            AsyncResultAction::Delete(Ok(())) | AsyncResultAction::Move(Ok(()))
        )
    }

    /// Applies the result to app state: clears loading and updates status/listing.
    pub fn apply(self, state: &mut AppState) {
        state.clear_loading();
        match self {
            AsyncResultAction::Listing(Ok(listing)) => {
                state.listing = Some(listing);
                state.status_message.clear();
                state.clamp_selected_index();
            }
            AsyncResultAction::Listing(Err(e)) => {
                state.status_message = format!("Listing failed: {}", e.display_for_user());
            }
            AsyncResultAction::Get(res) => {
                Self::apply_op_result(state, "Download complete.", res, "Get");
            }
            AsyncResultAction::Put(res) => {
                Self::apply_op_result(state, "Upload complete.", res, "Put");
            }
            AsyncResultAction::Delete(res) => {
                Self::apply_op_result(state, "Deleted.", res, "Delete");
            }
            AsyncResultAction::Move(res) => {
                Self::apply_op_result(state, "Moved.", res, "Move");
            }
        }
    }

    fn apply_op_result(
        state: &mut AppState,
        success_msg: &str,
        result: std::result::Result<(), Error>,
        op_name: &str,
    ) {
        match result {
            Ok(()) => state.status_message = success_msg.to_string(),
            Err(e) => {
                state.status_message = format!("{op_name} failed: {}", e.display_for_user());
            }
        }
    }
}

/// Behavioral category of a user action (for documentation, tests, logging).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ActionKind {
    /// Quit, `CursorUp`, `CursorDown` - no loading/status changes.
    Sync,
    /// `CdUp`, `CdIn`, `CdTo` - clear status on success.
    SyncClearStatus,
    /// Refresh, Get, `GetFile`, Put, Rm, `RmFile`, Mv, `MvTo` - trigger async work, set loading.
    AsyncTrigger,
    /// `AsyncResult` - clear loading, update state from result.
    AsyncResult,
    /// Status - clear loading, set message.
    StatusOverride,
}

/// User action from the TUI (parsed command or key) or from async task (result).
#[derive(Clone, Debug)]
pub enum UserAction {
    Quit,
    Refresh(Option<String>), // ls [glob]
    CdIn,                    // cd (into selected dir)
    CdUp,                    // cd ..
    CdTo(String),            // cd <dirname>
    CursorUp,
    CursorDown,
    Get,             // get (selected file)
    GetFile(String), // get <remote_path>
    Put(String),     // put <local_path>
    Rm,              // rm (selected file)
    RmFile(String),  // rm <remote_path>
    /// Confirm or cancel pending rm (y/n).
    ConfirmRm(bool),
    Mv(String, String), // mv <src> <dest>
    MvTo(String),       // mv <dest> (selected file)
    Status(String),
    /// Result of async operation (listing, get, put, delete, move).
    AsyncResult(AsyncResultAction),
}

fn parse_mv(rest: &str) -> std::result::Result<UserAction, String> {
    let r = rest.trim();
    if r.is_empty() {
        return Err("mv requires source and destination, e.g. mv file.txt newname.txt".to_string());
    }
    match r.find(char::is_whitespace) {
        None => Ok(UserAction::MvTo(r.to_string())),
        Some(i) => {
            let src = r[..i].trim().to_string();
            let dest = r[i + 1..].trim().to_string();
            if dest.is_empty() {
                Err("mv requires destination, e.g. mv file.txt newname.txt".to_string())
            } else {
                Ok(UserAction::Mv(src, dest))
            }
        }
    }
}

impl FromStr for UserAction {
    type Err = String;

    /// Parses a command line into a `UserAction`. Familiar syntax: ls, cd [dir|..], get [file], put `local_path`, quit.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let line = s.trim();
        let (cmd, rest) = match line.find(char::is_whitespace) {
            Some(i) => (line[..i].trim(), line[i + 1..].trim()),
            None => (line, ""),
        };
        let cmd = cmd.to_lowercase();
        match (cmd.as_str(), rest) {
            ("ls", "") => Ok(UserAction::Refresh(None)),
            ("ls", r) => Ok(UserAction::Refresh(Some(r.to_string()))),
            ("cd", "") => Ok(UserAction::CdIn),
            ("cd", "..") => Ok(UserAction::CdUp),
            ("cd", r) => Ok(UserAction::CdTo(r.to_string())),
            ("get", "") => Ok(UserAction::Get),
            ("get", r) => Ok(UserAction::GetFile(r.to_string())),
            ("put", "") => Err("put requires a local path, e.g. put ./file.txt".to_string()),
            ("put", r) => Ok(UserAction::Put(r.to_string())),
            ("rm", "") => Ok(UserAction::Rm),
            ("rm", r) => Ok(UserAction::RmFile(r.to_string())),
            ("mv", "") => {
                Err("mv requires source and destination, e.g. mv file.txt newname.txt".to_string())
            }
            ("mv", r) => parse_mv(r),
            ("quit", _) | ("q", _) => Ok(UserAction::Quit),
            _ => Err(format!(
                "unknown command: {cmd}. Use ls, cd, get, put, rm, mv, quit."
            )),
        }
    }
}

impl UserAction {
    /// Returns the behavioral category of this action.
    #[must_use]
    pub const fn kind(&self) -> ActionKind {
        match self {
            UserAction::Quit | UserAction::CursorUp | UserAction::CursorDown => ActionKind::Sync,
            UserAction::CdUp | UserAction::CdIn | UserAction::CdTo(_) => {
                ActionKind::SyncClearStatus
            }
            UserAction::Refresh(_)
            | UserAction::Get
            | UserAction::GetFile(_)
            | UserAction::Put(_)
            | UserAction::Rm
            | UserAction::RmFile(_)
            | UserAction::Mv(_, _)
            | UserAction::MvTo(_) => ActionKind::AsyncTrigger,
            UserAction::ConfirmRm(_) => ActionKind::SyncClearStatus,
            UserAction::AsyncResult(_) => ActionKind::AsyncResult,
            UserAction::Status(_) => ActionKind::StatusOverride,
        }
    }
}

/// Draws the TUI frame.
pub fn draw(frame: &mut Frame, state: &AppState, config: &Config) {
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Min(3),
            Constraint::Length(1),
            Constraint::Length(3), // borders + title + one row for input
        ])
        .split(frame.area());

    let entries = state.entries_for_display();
    let items: Vec<ListItem> = entries
        .iter()
        .enumerate()
        .map(|(i, (text, _, _))| {
            let style = if i == state.selected_index {
                Style::default().add_modifier(Modifier::REVERSED)
            } else {
                Style::default()
            };
            ListItem::new(Line::from(Span::styled(text.as_str(), style)))
        })
        .collect();

    let list = List::new(items).block(
        Block::default()
            .title(format!(
                " Remote: {} | Connector: {} ",
                state.current_remote_path, config.connector_id
            ))
            .borders(Borders::ALL),
    );

    let list_chunk = chunks.first().copied().unwrap_or_default();
    frame.render_widget(list, list_chunk);

    let status: String = if let Some(started) = state.loading_started {
        let spinner_char = {
            let idx = (started.elapsed().as_millis() / SPINNER_MS_PER_FRAME) as usize
                % SPINNER_FRAMES.len();
            SPINNER_FRAMES.get(idx).copied().unwrap_or('|')
        };
        let msg = if state.status_message.is_empty() {
            "Loading..."
        } else {
            state.status_message.as_str()
        };
        format!(" [{spinner_char}] {msg} ")
    } else if state.status_message.is_empty() {
        " ls  cd [dir|..]  get [file]  put <local>  rm [file]  mv [src] dest  quit ".to_string()
    } else {
        state.status_message.clone()
    };

    let status_para = Paragraph::new(status.as_str())
        .block(Block::default().borders(Borders::NONE))
        .wrap(Wrap { trim: true });
    let status_chunk = chunks.get(1).copied().unwrap_or_default();
    frame.render_widget(status_para, status_chunk);

    let cmd_line = format!("> {}_", state.cmd_buffer);
    let cmd_para = Paragraph::new(cmd_line.as_str())
        .block(Block::default().borders(Borders::ALL).title(" Command "))
        .wrap(Wrap { trim: true });
    let cmd_chunk = chunks.get(2).copied().unwrap_or_default();
    frame.render_widget(cmd_para, cmd_chunk);

    if let Some(ref path) = state.pending_rm {
        let area = frame.area();
        let popup_width = area.width.saturating_sub(4).clamp(20, 60);
        let popup_height = 5u16;
        let popup_rect = Rect {
            x: area.width.saturating_sub(popup_width) / 2,
            y: area.height.saturating_sub(popup_height) / 2,
            width: popup_width,
            height: popup_height,
        };
        frame.render_widget(Clear, popup_rect);
        let msg = format!("Delete {}? (y/n)", path);
        let block = Block::default().borders(Borders::ALL).title(" Delete ");
        let para = Paragraph::new(msg.as_str())
            .block(block)
            .wrap(Wrap { trim: true });
        frame.render_widget(para, popup_rect);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::listing::{DirectoryListing, ListedFile, ListedPath};
    #[test]
    fn glob_match_star_matches_any_sequence() {
        assert!(super::glob_match("A*100*", "ABC100200300"));
        assert!(super::glob_match("A*100*", "A100"));
        assert!(super::glob_match("*", "anything"));
        assert!(super::glob_match("*", ""));
        assert!(super::glob_match("*.txt", "file.txt"));
        assert!(super::glob_match("*.txt", ".txt"));
        assert!(!super::glob_match("A*100*", "ABC200300"));
        assert!(!super::glob_match("*.txt", "file.dat"));
    }

    #[test]
    fn glob_match_question_matches_single_char() {
        assert!(super::glob_match("?", "a"));
        assert!(super::glob_match("f?o", "foo"));
        assert!(super::glob_match("?.txt", "a.txt"));
        assert!(!super::glob_match("?", ""));
        assert!(!super::glob_match("?", "ab"));
        assert!(!super::glob_match("f?o", "fo"));
    }

    #[test]
    fn glob_match_empty_and_literal() {
        assert!(super::glob_match("", ""));
        assert!(!super::glob_match("", "x"));
        assert!(super::glob_match("abc", "abc"));
        assert!(!super::glob_match("abc", "ab"));
        assert!(!super::glob_match("abc", "abcd"));
    }

    #[test]
    fn ls_parses_without_glob() {
        let a: UserAction = "ls".parse().unwrap();
        assert!(matches!(a, UserAction::Refresh(None)));
    }

    #[test]
    fn ls_parses_with_glob() {
        let a: UserAction = "ls A*100*".parse().unwrap();
        assert!(matches!(&a, UserAction::Refresh(Some(p)) if p == "A*100*"));

        let b: UserAction = "ls *.txt".parse().unwrap();
        assert!(matches!(&b, UserAction::Refresh(Some(p)) if p == "*.txt"));
    }

    #[test]
    fn entries_for_display_filters_by_glob() {
        let config = crate::config::test_config();
        let mut state = AppState::new(&config);
        state.listing = Some(DirectoryListing {
            paths: vec![
                ListedPath {
                    path: "/foo".to_string(),
                },
                ListedPath {
                    path: "/ABC100dir".to_string(),
                },
            ],
            files: vec![
                ListedFile {
                    file_path: "/readme.txt".to_string(),
                    modified_timestamp: None,
                    size: Some(1024),
                },
                ListedFile {
                    file_path: "/ABC100200300".to_string(),
                    modified_timestamp: None,
                    size: None,
                },
                ListedFile {
                    file_path: "/other.dat".to_string(),
                    modified_timestamp: None,
                    size: None,
                },
            ],
            truncated: false,
        });

        let all = state.entries_for_display();
        assert_eq!(all.len(), 5);

        state.listing_glob = Some("A*100*".to_string());
        let filtered = state.entries_for_display();
        assert_eq!(filtered.len(), 2);
        let names: Vec<String> = filtered
            .iter()
            .map(|(s, _, _)| {
                s.trim()
                    .trim_end_matches('/')
                    .replace(" (", " ")
                    .split_whitespace()
                    .next()
                    .unwrap_or("")
                    .to_string()
            })
            .collect();
        assert!(names.contains(&"ABC100dir".to_string()));
        assert!(names.contains(&"ABC100200300".to_string()));
    }

    #[test]
    fn clamp_selected_index_after_filter() {
        let config = crate::config::test_config();
        let mut state = AppState::new(&config);
        state.listing = Some(DirectoryListing {
            paths: vec![],
            files: vec![
                ListedFile {
                    file_path: "/a".to_string(),
                    modified_timestamp: None,
                    size: None,
                },
                ListedFile {
                    file_path: "/b".to_string(),
                    modified_timestamp: None,
                    size: None,
                },
            ],
            truncated: false,
        });
        state.selected_index = 5;
        state.clamp_selected_index();
        assert_eq!(state.selected_index, 1);

        state.listing_glob = Some("c".to_string());
        state.selected_index = 1;
        state.clamp_selected_index();
        assert_eq!(state.selected_index, 0);
    }
}