component_debug/
copy.rs

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
// Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use fidl::endpoints::create_proxy;

use crate::io::{Directory, DirentKind, LocalDirectory, RemoteDirectory};
use crate::path::{
    add_source_filename_to_path_if_absent, open_parent_subdir_readable, LocalOrRemoteDirectoryPath,
};
use anyhow::{bail, Result};
use fidl::endpoints::ServerEnd;
use regex::Regex;
use std::path::PathBuf;
use thiserror::Error;
use {fidl_fuchsia_io as fio, fidl_fuchsia_sys2 as fsys};

#[derive(Error, Debug)]
pub enum CopyError {
    #[error("Destination can not have a wildcard.")]
    DestinationContainWildcard,

    #[error("At least two paths (local or remote) must be provided.")]
    NotEnoughPaths,

    #[error("File name was unexpectedly empty.")]
    EmptyFileName,

    #[error("Path does not contain a parent folder.")]
    NoParentFolder { path: String },

    #[error("No files found matching: {pattern}.")]
    NoWildCardMatches { pattern: String },

    #[error(
        "Could not find an instance with the moniker: {moniker}\n\
    Use `ffx component list` or `ffx component show` to find the correct moniker of your instance."
    )]
    InstanceNotFound { moniker: String },

    #[error("Encountered an unexpected error when attempting to open a directory with the provider moniker: {moniker}. {error:?}.")]
    UnexpectedErrorFromMoniker { moniker: String, error: fsys::OpenError },

    #[error("No file found at {file} in remote component directory.")]
    NamespaceFileNotFound { file: String },
}

/// Transfer files between a directories associated with a component to/from the local filesystem.
///
/// # Arguments
/// * `realm_query`: |RealmQueryProxy| to open the component directories.
/// * `paths`: The local and remote paths to copy. The last entry is the destination.
/// * `verbose`: Flag used to indicate whether or not to print output to console.
pub async fn copy_cmd<W: std::io::Write>(
    realm_query: &fsys::RealmQueryProxy,
    mut paths: Vec<String>,
    verbose: bool,
    mut writer: W,
) -> Result<()> {
    validate_paths(&paths)?;

    // paths is safe to unwrap as validate_paths ensures that it is non-empty.
    let destination_path = paths.pop().unwrap();

    for source_path in paths {
        let result: Result<()> = match (
            LocalOrRemoteDirectoryPath::parse(&source_path),
            LocalOrRemoteDirectoryPath::parse(&destination_path),
        ) {
            (
                LocalOrRemoteDirectoryPath::Remote(source),
                LocalOrRemoteDirectoryPath::Local(destination_path),
            ) => {
                let source_dir = RemoteDirectory::from_proxy(
                    open_component_dir_for_moniker(&realm_query, &source.moniker, &source.dir_type)
                        .await?,
                );
                let destination_dir = LocalDirectory::new();

                do_copy(
                    &source_dir,
                    &source.relative_path,
                    &destination_dir,
                    &destination_path,
                    verbose,
                    &mut writer,
                )
                .await
            }

            (
                LocalOrRemoteDirectoryPath::Local(source_path),
                LocalOrRemoteDirectoryPath::Remote(destination),
            ) => {
                let source_dir = LocalDirectory::new();
                let destination_dir = RemoteDirectory::from_proxy(
                    open_component_dir_for_moniker(
                        &realm_query,
                        &destination.moniker,
                        &destination.dir_type,
                    )
                    .await?,
                );

                do_copy(
                    &source_dir,
                    &source_path,
                    &destination_dir,
                    &destination.relative_path,
                    verbose,
                    &mut writer,
                )
                .await
            }

            (
                LocalOrRemoteDirectoryPath::Remote(source),
                LocalOrRemoteDirectoryPath::Remote(destination),
            ) => {
                let source_dir = RemoteDirectory::from_proxy(
                    open_component_dir_for_moniker(&realm_query, &source.moniker, &source.dir_type)
                        .await?,
                );

                let destination_dir = RemoteDirectory::from_proxy(
                    open_component_dir_for_moniker(
                        &realm_query,
                        &destination.moniker,
                        &destination.dir_type,
                    )
                    .await?,
                );

                do_copy(
                    &source_dir,
                    &source.relative_path,
                    &destination_dir,
                    &destination.relative_path,
                    verbose,
                    &mut writer,
                )
                .await
            }

            (
                LocalOrRemoteDirectoryPath::Local(source_path),
                LocalOrRemoteDirectoryPath::Local(destination_path),
            ) => {
                let source_dir = LocalDirectory::new();
                let destination_dir = LocalDirectory::new();
                do_copy(
                    &source_dir,
                    &source_path,
                    &destination_dir,
                    &destination_path,
                    verbose,
                    &mut writer,
                )
                .await
            }
        };

        match result {
            Ok(_) => continue,
            Err(e) => bail!("Copy from {} to {} failed: {}", &source_path, &destination_path, e),
        };
    }

    Ok(())
}

async fn do_copy<S: Directory, D: Directory, W: std::io::Write>(
    source_dir: &S,
    source_path: &PathBuf,
    destination_dir: &D,
    destination_path: &PathBuf,
    verbose: bool,
    writer: &mut W,
) -> Result<()> {
    let source_paths = maybe_expand_wildcards(source_path, source_dir).await?;
    for path in source_paths {
        if is_file(source_dir, &path).await? {
            let destination_path_path =
                add_source_filename_to_path_if_absent(destination_dir, &path, &destination_path)
                    .await?;

            let data = source_dir.read_file_bytes(path).await?;
            destination_dir.write_file(destination_path_path.clone(), &data).await?;

            if verbose {
                writeln!(
                    writer,
                    "Copied {} -> {}",
                    source_path.display(),
                    destination_path_path.display()
                )?;
            }
        } else {
            // TODO(https://fxbug.dev/42067334): add recursive copy support.
            writeln!(
                writer,
                "Directory \"{}\" ignored as recursive copying is unsupported. (See https://fxbug.dev/42067334)",
                path.display()
            )?;
        }
    }

    Ok(())
}

async fn is_file<D: Directory>(dir: &D, path: &PathBuf) -> Result<bool> {
    let parent_dir = open_parent_subdir_readable(path, dir)?;
    let source_file = path.file_name().map_or_else(
        || Err(CopyError::EmptyFileName),
        |file| Ok(file.to_string_lossy().to_string()),
    )?;

    let remote_type = parent_dir.entry_type(&source_file).await?;
    match remote_type {
        Some(kind) => match kind {
            DirentKind::File => Ok(true),
            _ => Ok(false),
        },
        None => Err(CopyError::NamespaceFileNotFound { file: source_file }.into()),
    }
}

/// If `path` contains a wildcard, returns the expanded list of files. Otherwise,
/// returns a list with a single entry.
///
/// # Arguments
///
/// * `path`: A path that may contain a wildcard.
/// * `dir`: Directory proxy to query to expand wildcards.
async fn maybe_expand_wildcards<D: Directory>(path: &PathBuf, dir: &D) -> Result<Vec<PathBuf>> {
    if !&path.to_string_lossy().contains("*") {
        return Ok(vec![path.clone()]);
    }
    let parent_dir = open_parent_subdir_readable(path, dir)?;

    let file_pattern = &path
        .file_name()
        .map_or_else(
            || Err(CopyError::EmptyFileName),
            |file| Ok(file.to_string_lossy().to_string()),
        )?
        .replace("*", ".*"); // Regex syntax requires a . before wildcard.

    let entries = get_dirents_matching_pattern(&parent_dir, file_pattern.clone()).await?;

    if entries.len() == 0 {
        return Err(CopyError::NoWildCardMatches { pattern: file_pattern.to_string() }.into());
    }

    let parent_dir_path = match path.parent() {
        Some(parent) => PathBuf::from(parent),
        None => {
            return Err(
                CopyError::NoParentFolder { path: path.to_string_lossy().to_string() }.into()
            )
        }
    };
    Ok(entries.iter().map(|file| parent_dir_path.join(file)).collect::<Vec<_>>())
}

/// Checks that the paths meet the following conditions:
///
/// * Destination path does not contain a wildcard.
/// * At least two path arguments are provided.
///
/// # Arguments
///
/// *`paths`: list of filepaths to be processed.
fn validate_paths(paths: &Vec<String>) -> Result<()> {
    if paths.len() < 2 {
        Err(CopyError::NotEnoughPaths.into())
    } else if paths.last().unwrap().contains("*") {
        Err(CopyError::DestinationContainWildcard.into())
    } else {
        Ok(())
    }
}

/// Retrieves the directory proxy for one of a component's associated directories.
/// # Arguments
/// * `realm_query`: |RealmQueryProxy| to retrieve a component instance.
/// * `moniker`: Absolute moniker of a component instance.
/// * `dir_type`: The type of directory (namespace, outgoing, ...)
async fn open_component_dir_for_moniker(
    realm_query: &fsys::RealmQueryProxy,
    moniker: &str,
    dir_type: &fsys::OpenDirType,
) -> Result<fio::DirectoryProxy> {
    let (dir, server_end) = create_proxy::<fio::DirectoryMarker>();
    let server_end = ServerEnd::new(server_end.into_channel());
    let flags = match dir_type {
        fsys::OpenDirType::PackageDir => fio::OpenFlags::RIGHT_READABLE,
        _ => fio::OpenFlags::RIGHT_READABLE | fio::OpenFlags::RIGHT_WRITABLE,
    };
    match realm_query
        .deprecated_open(&moniker, dir_type.clone(), flags, fio::ModeType::empty(), ".", server_end)
        .await?
    {
        Ok(()) => Ok(dir),
        Err(fsys::OpenError::InstanceNotFound) => {
            Err(CopyError::InstanceNotFound { moniker: moniker.to_string() }.into())
        }
        Err(e) => {
            Err(CopyError::UnexpectedErrorFromMoniker { moniker: moniker.to_string(), error: e }
                .into())
        }
    }
}

// Retrieves all entries within a remote directory containing a file pattern.
///
/// # Arguments
/// * `dir`: A directory.
/// * `file_pattern`: A file pattern to match.
async fn get_dirents_matching_pattern<D: Directory>(
    dir: &D,
    file_pattern: String,
) -> Result<Vec<String>> {
    let mut entries = dir.entry_names().await?;

    let file_pattern = Regex::new(format!(r"^{}$", file_pattern).as_str())?;

    entries.retain(|file_name| file_pattern.is_match(file_name.as_str()));

    Ok(entries)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_utils::{
        create_tmp_dir, generate_directory_paths, generate_file_paths, serve_realm_query, File,
        SeedPath,
    };
    use std::collections::HashMap;
    use std::fs::{read, write};
    use std::iter::zip;
    use test_case::test_case;

    const CHANNEL_SIZE_LIMIT: u64 = 64 * 1024;
    const LARGE_FILE_ARRAY: [u8; CHANNEL_SIZE_LIMIT as usize] = [b'a'; CHANNEL_SIZE_LIMIT as usize];
    const OVER_LIMIT_FILE_ARRAY: [u8; (CHANNEL_SIZE_LIMIT + 1) as usize] =
        [b'a'; (CHANNEL_SIZE_LIMIT + 1) as usize];

    // We can call from_utf8_unchecked as the file arrays only contain the character 'a' which is safe to unwrap.
    const LARGE_FILE_DATA: &str = unsafe { std::str::from_utf8_unchecked(&LARGE_FILE_ARRAY) };
    const OVER_LIMIT_FILE_DATA: &str =
        unsafe { std::str::from_utf8_unchecked(&OVER_LIMIT_FILE_ARRAY) };

    #[derive(Clone)]
    struct Input {
        source: &'static str,
        destination: &'static str,
    }

    #[derive(Clone)]
    struct Inputs {
        sources: Vec<&'static str>,
        destination: &'static str,
    }

    #[derive(Clone)]
    struct Expectation {
        path: &'static str,
        data: &'static str,
    }

    fn create_realm_query(
        foo_dir_type: fsys::OpenDirType,
        foo_files: Vec<SeedPath>,
        bar_dir_type: fsys::OpenDirType,
        bar_files: Vec<SeedPath>,
    ) -> (fsys::RealmQueryProxy, PathBuf, PathBuf) {
        let foo_ns_dir = create_tmp_dir(foo_files).unwrap();
        let bar_ns_dir = create_tmp_dir(bar_files).unwrap();
        let foo_path = foo_ns_dir.path().to_path_buf();
        let bar_path = bar_ns_dir.path().to_path_buf();
        let realm_query = serve_realm_query(
            vec![],
            HashMap::new(),
            HashMap::new(),
            HashMap::from([
                (("./foo/bar".to_string(), foo_dir_type), foo_ns_dir),
                (("./bar/foo".to_string(), bar_dir_type), bar_ns_dir),
            ]),
        );
        (realm_query, foo_path, bar_path)
    }

    fn create_realm_query_simple(
        foo_files: Vec<SeedPath>,
        bar_files: Vec<SeedPath>,
    ) -> (fsys::RealmQueryProxy, PathBuf, PathBuf) {
        create_realm_query(
            fsys::OpenDirType::NamespaceDir,
            foo_files,
            fsys::OpenDirType::NamespaceDir,
            bar_files,
        )
    }

    #[test_case(Input{source: "/foo/bar::out::/data/foo.txt", destination: "foo.txt"},
                generate_file_paths(vec![File{ name: "data/foo.txt", data: "Hello"}]),
                Expectation{path: "foo.txt", data: "Hello"}; "single_file")]
    #[fuchsia::test]
    async fn copy_from_outgoing_dir(
        input: Input,
        foo_files: Vec<SeedPath>,
        expectation: Expectation,
    ) {
        // Show that the copy command will respect an input that specifies
        // a directory other than the namespace.
        let local_dir = create_tmp_dir(vec![]).unwrap();
        let local_path = local_dir.path();

        let (realm_query, _, _) = create_realm_query(
            fsys::OpenDirType::OutgoingDir,
            foo_files,
            fsys::OpenDirType::OutgoingDir,
            vec![],
        );
        let destination_path = local_path.join(input.destination).display().to_string();

        copy_cmd(
            &realm_query,
            vec![input.source.to_string(), destination_path],
            /*verbose=*/ false,
            std::io::stdout(),
        )
        .await
        .unwrap();

        let expected_data = expectation.data.to_owned().into_bytes();
        let actual_data_path = local_path.join(expectation.path);
        let actual_data = read(actual_data_path).unwrap();
        assert_eq!(actual_data, expected_data);
    }

    #[test_case(Input{source: "/foo/bar::/data/foo.txt", destination: "foo.txt"},
                generate_file_paths(vec![File{ name: "data/foo.txt", data: "Hello"}]),
                Expectation{path: "foo.txt", data: "Hello"}; "single_file")]
    #[test_case(Input{source: "/foo/bar::/data/foo.txt", destination: "foo.txt"},
                generate_file_paths(vec![File{ name: "data/foo.txt", data: "Hello"}]),
                Expectation{path: "foo.txt", data: "Hello"}; "overwrite_file")]
    #[test_case(Input{source: "/foo/bar::/data/foo.txt", destination: "bar.txt"},
                generate_file_paths(vec![File{ name: "data/foo.txt", data: "Hello"}]),
                Expectation{path: "bar.txt", data: "Hello"}; "different_file_name")]
    #[test_case(Input{source: "/foo/bar::/data/foo.txt", destination: ""},
                generate_file_paths(vec![File{ name: "data/foo.txt", data: "Hello"}]),
                Expectation{path: "foo.txt", data: "Hello"}; "infer_path")]
    #[test_case(Input{source: "/foo/bar::/data/foo.txt", destination: "./"},
                generate_file_paths(vec![File{ name: "data/foo.txt", data: "Hello"}]),
                Expectation{path: "foo.txt", data: "Hello"}; "infer_path_slash")]
    #[test_case(Input{source: "/foo/bar::/data/foo.txt", destination: "foo.txt"},
                generate_file_paths(vec![File{ name: "data/foo.txt", data: "Hello"}, File{ name: "data/bar.txt", data: "World"}]),
                Expectation{path: "foo.txt", data: "Hello"}; "populated_directory")]
    #[test_case(Input{source: "/foo/bar::/data/foo.txt", destination: "foo.txt"},
                generate_file_paths(vec![File{ name: "data/foo.txt", data: LARGE_FILE_DATA}]),
                Expectation{path: "foo.txt", data: LARGE_FILE_DATA}; "large_file")]
    #[test_case(Input{source: "/foo/bar::/data/foo.txt", destination: "foo.txt"},
                generate_file_paths(vec![File{ name: "data/foo.txt", data: OVER_LIMIT_FILE_DATA}]),
                Expectation{path: "foo.txt", data: OVER_LIMIT_FILE_DATA}; "over_limit_file")]
    #[fuchsia::test]
    async fn copy_device_to_local(
        input: Input,
        foo_files: Vec<SeedPath>,
        expectation: Expectation,
    ) {
        let local_dir = create_tmp_dir(vec![]).unwrap();
        let local_path = local_dir.path();

        let (realm_query, _, _) = create_realm_query_simple(foo_files, vec![]);
        let destination_path = local_path.join(input.destination).display().to_string();

        eprintln!("Destination path: {:?}", destination_path);

        copy_cmd(
            &realm_query,
            vec![input.source.to_string(), destination_path],
            /*verbose=*/ false,
            std::io::stdout(),
        )
        .await
        .unwrap();

        let expected_data = expectation.data.to_owned().into_bytes();
        let actual_data_path = local_path.join(expectation.path);
        let actual_data = read(actual_data_path).unwrap();
        assert_eq!(actual_data, expected_data);
    }

    #[test_case(Input{source: "/foo/bar::/data/*", destination: "foo.txt"},
                generate_file_paths(vec![File{ name: "data/foo.txt", data: "Hello"}]),
                vec![Expectation{path: "foo.txt", data: "Hello"}]; "all_matches")]
    #[test_case(Input{source: "/foo/bar::/data/*", destination: "foo.txt"},
                generate_file_paths(vec![File{ name: "data/foo.txt", data: "Hello"}, File{ name: "foo.txt", data: "World"}]),
                vec![Expectation{path: "foo.txt", data: "Hello"}]; "all_matches_overwrite")]
    #[test_case(Input{source: "/foo/bar::/data/*", destination: "foo.txt"},
                generate_file_paths(vec![File{ name: "data/foo.txt", data: "Hello"}, File{ name: "data/nested/foo.txt", data: "World"}]),
                vec![Expectation{path: "foo.txt", data: "Hello"}]; "all_matches_nested")]
    #[test_case(Input{source: "/foo/bar::/data/*.txt", destination: "foo.txt"},
                generate_file_paths(vec![File{ name: "data/foo.txt", data: "Hello"}]),
                vec![Expectation{path: "foo.txt", data: "Hello"}]; "file_extension")]
    #[test_case(Input{source: "/foo/bar::/data/foo.*", destination: "foo.txt"},
                generate_file_paths(vec![File{ name: "data/foo.txt", data: "Hello"}]),
                vec![Expectation{path: "foo.txt", data: "Hello"}]; "file_extension_2")]
    #[test_case(Input{source: "/foo/bar::/data/fo*.txt", destination: "foo.txt"},
                generate_file_paths(vec![File{ name: "data/foo.txt", data: "Hello"}]),
                vec![Expectation{path: "foo.txt", data: "Hello"}]; "file_substring_match")]
    #[test_case(Input{source: "/foo/bar::/data/*", destination: "./"},
                generate_file_paths(vec![File{ name: "data/foo.txt", data: "Hello"}, File{ name: "data/bar.txt", data: "World"}]),
                vec![Expectation{path: "foo.txt", data: "Hello"}, Expectation{path: "bar.txt", data: "World"}]; "multi_file")]
    #[test_case(Input{source: "/foo/bar::/data/*fo*.txt", destination: "./"},
                generate_file_paths(vec![File{ name: "data/foo.txt", data: "Hello"}, File{ name: "data/foobar.txt", data: "World"}]),
                vec![Expectation{path: "foo.txt", data: "Hello"}, Expectation{path: "foobar.txt", data: "World"}]; "multi_wildcard")]
    #[test_case(Input{source: "/foo/bar::/data/*", destination: "./"},
                generate_file_paths(vec![File{ name: "data/foo.txt", data: "Hello"}, File{ name: "data/foobar.txt", data: "World"},
                     File{ name: "foo.txt", data: "World"}, File{ name: "foobar.txt", data: "Hello"}]),
                vec![Expectation{path: "foo.txt", data: "Hello"}, Expectation{path: "foobar.txt", data: "World"}]; "multi_file_overwrite")]
    #[fuchsia::test]
    async fn copy_device_to_local_wildcard(
        input: Input,
        foo_files: Vec<SeedPath>,
        expectation: Vec<Expectation>,
    ) {
        let local_dir = create_tmp_dir(vec![]).unwrap();
        let local_path = local_dir.path();

        let (realm_query, _, _) = create_realm_query_simple(foo_files, vec![]);
        let destination_path = local_path.join(input.destination);

        copy_cmd(
            &realm_query,
            vec![input.source.to_string(), destination_path.display().to_string()],
            /*verbose=*/ true,
            std::io::stdout(),
        )
        .await
        .unwrap();

        for expected in expectation {
            let expected_data = expected.data.to_owned().into_bytes();
            let actual_data_path = local_path.join(expected.path);

            eprintln!("reading file '{}'", actual_data_path.display());

            let actual_data = read(actual_data_path).unwrap();
            assert_eq!(actual_data, expected_data);
        }
    }

    #[test_case(Input{source: "/wrong_moniker/foo/bar::/data/foo.txt", destination: "foo.txt"},
                generate_file_paths(vec![File{ name: "data/foo.txt", data: "Hello"}]); "bad_moniker")]
    #[test_case(Input{source: "/foo/bar::/data/bar.txt", destination: "foo.txt"},
                generate_file_paths(vec![File{ name: "data/foo.txt", data: "Hello"}]); "bad_file")]
    #[test_case(Input{source: "/foo/bar::/data/foo.txt", destination: "bar/foo.txt"},
                generate_file_paths(vec![File{ name: "data/foo.txt", data: "Hello"}]); "bad_directory")]
    #[fuchsia::test]
    async fn copy_device_to_local_fails(input: Input, foo_files: Vec<SeedPath>) {
        let local_dir = create_tmp_dir(vec![]).unwrap();
        let local_path = local_dir.path();

        let (realm_query, _, _) = create_realm_query_simple(foo_files, vec![]);
        let destination_path = local_path.join(input.destination).display().to_string();
        let result = copy_cmd(
            &realm_query,
            vec![input.source.to_string(), destination_path],
            /*verbose=*/ true,
            std::io::stdout(),
        )
        .await;

        assert!(result.is_err());
    }

    #[test_case(Input{source: "foo.txt", destination: "/foo/bar::/data/foo.txt"},
                generate_directory_paths(vec!["data"]),
                Expectation{path: "data/foo.txt", data: "Hello"}; "single_file")]
    #[test_case(Input{source: "foo.txt", destination: "/foo/bar::/data/bar.txt"},
                generate_directory_paths(vec!["data"]),
                Expectation{path: "data/bar.txt", data: "Hello"}; "different_file_name")]
    #[test_case(Input{source: "foo.txt", destination: "/foo/bar::/data/foo.txt"},
                generate_file_paths(vec![File{ name: "data/foo.txt", data: "World"}]),
                Expectation{path: "data/foo.txt", data: "Hello"}; "overwrite_file")]
    #[test_case(Input{source: "foo.txt", destination: "/foo/bar::/data"},
                generate_file_paths(vec![File{ name: "data/foo.txt", data: "Hello"}]),
                Expectation{path: "data/foo.txt", data: "Hello"}; "infer_path")]
    #[test_case(Input{source: "foo.txt", destination: "/foo/bar::/data/"},
                generate_file_paths(vec![File{ name: "data/foo.txt", data: "Hello"}]),
                Expectation{path: "data/foo.txt", data: "Hello"}; "infer_slash_path")]
    #[test_case(Input{source: "foo.txt", destination: "/foo/bar::/data/nested/foo.txt"},
                generate_directory_paths(vec!["data", "data/nested"]),
                Expectation{path: "data/nested/foo.txt", data: "Hello"}; "nested_path")]
    #[test_case(Input{source: "foo.txt", destination: "/foo/bar::/data/nested"},
                generate_directory_paths(vec!["data", "data/nested"]),
                Expectation{path: "data/nested/foo.txt", data: "Hello"}; "infer_nested_path")]
    #[test_case(Input{source: "foo.txt", destination: "/foo/bar::/data/"},
                generate_directory_paths(vec!["data"]),
                Expectation{path: "data/foo.txt", data: LARGE_FILE_DATA}; "large_file")]
    #[test_case(Input{source: "foo.txt", destination: "/foo/bar::/data/"},
                generate_directory_paths(vec!["data"]),
                Expectation{path: "data/foo.txt", data: OVER_LIMIT_FILE_DATA}; "over_channel_limit_file")]
    #[fuchsia::test]
    async fn copy_local_to_device(
        input: Input,
        foo_files: Vec<SeedPath>,
        expectation: Expectation,
    ) {
        let local_dir = create_tmp_dir(vec![]).unwrap();
        let local_path = local_dir.path();

        let source_path = local_path.join(&input.source);
        write(&source_path, expectation.data.to_owned().into_bytes()).unwrap();
        let (realm_query, foo_path, _) = create_realm_query_simple(foo_files, vec![]);

        copy_cmd(
            &realm_query,
            vec![source_path.display().to_string(), input.destination.to_string()],
            /*verbose=*/ false,
            std::io::stdout(),
        )
        .await
        .unwrap();

        let actual_path = foo_path.join(expectation.path);
        let actual_data = read(actual_path).unwrap();
        let expected_data = expectation.data.to_owned().into_bytes();
        assert_eq!(actual_data, expected_data);
    }

    #[test_case(Input{source: "/foo/bar::/data/foo.txt", destination: "/bar/foo::/data/foo.txt"},
                generate_file_paths(vec![File{ name: "data/foo.txt", data: "Hello"}, File{ name: "data/bar.txt", data: "World"}]),
                generate_directory_paths(vec!["data"]),
                vec![Expectation{path: "data/foo.txt", data: "Hello"}]; "single_file")]
    #[test_case(Input{source: "/foo/bar::/data/foo.txt", destination: "/bar/foo::/data/nested/foo.txt"},
                generate_file_paths(vec![File{ name: "data/foo.txt", data: "Hello"}, File{ name: "data/bar.txt", data: "World"}]),
                generate_directory_paths(vec!["data", "data/nested"]),
                vec![Expectation{path: "data/nested/foo.txt", data: "Hello"}]; "nested")]
    #[test_case(Input{source: "/foo/bar::/data/foo.txt", destination: "/bar/foo::/data/bar.txt"},
                generate_file_paths(vec![File{ name: "data/foo.txt", data: "Hello"}, File{ name: "data/bar.txt", data: "World"}]),
                generate_directory_paths(vec!["data"]),
                vec![Expectation{path: "data/bar.txt", data: "Hello"}]; "different_file_name")]
    #[test_case(Input{source: "/foo/bar::/data/foo.txt", destination: "/bar/foo::/data/foo.txt"},
                generate_file_paths(vec![File{ name: "data/foo.txt", data: "Hello"}, File{ name: "data/bar.txt", data: "World"}]),
                generate_file_paths(vec![File{ name: "data/foo.txt", data: "Hello"}]),
                vec![Expectation{path: "data/foo.txt", data: "Hello"}]; "overwrite_file")]
    #[test_case(Input{source: "/foo/bar::/data/*", destination: "/bar/foo::/data"},
                generate_file_paths(vec![File{ name: "data/foo.txt", data: "Hello"}, File{ name: "data/bar.txt", data: "World"}]),
                generate_directory_paths(vec!["data"]),
                vec![Expectation{path: "data/foo.txt", data: "Hello"}, Expectation{path: "data/bar.txt", data: "World"}]; "wildcard_match_all_multi_file")]
    #[test_case(Input{source: "/foo/bar::/data/*.txt", destination: "/bar/foo::/data"},
                generate_file_paths(vec![File{ name: "data/foo.txt", data: "Hello"}, File{ name: "data/bar.txt", data: "World"}]),
                generate_directory_paths(vec!["data"]),
                vec![Expectation{path: "data/foo.txt", data: "Hello"}, Expectation{path: "data/bar.txt", data: "World"}]; "wildcard_match_files_extensions_multi_file")]
    #[test_case(Input{source: "/foo/bar::/data/*", destination: "/bar/foo::/data"},
                generate_file_paths(vec![File{ name: "data/foo.txt", data: "Hello"}, File{ name: "data/bar.txt", data: "World"}]),
                generate_file_paths(vec![File{ name: "data/foo.txt", data: "World"}, File{ name: "data/bar.txt", data: "Hello"}]),
                vec![Expectation{path: "data/foo.txt", data: "Hello"}, Expectation{path: "data/bar.txt", data: "World"}]; "wildcard_match_all_multi_file_overwrite")]
    #[fuchsia::test]
    async fn copy_device_to_device(
        input: Input,
        foo_files: Vec<SeedPath>,
        bar_files: Vec<SeedPath>,
        expectation: Vec<Expectation>,
    ) {
        let (realm_query, _, bar_path) = create_realm_query_simple(foo_files, bar_files);

        copy_cmd(
            &realm_query,
            vec![input.source.to_string(), input.destination.to_string()],
            /*verbose=*/ false,
            std::io::stdout(),
        )
        .await
        .unwrap();

        for expected in expectation {
            let destination_path = bar_path.join(expected.path);
            let actual_data = read(destination_path).unwrap();
            let expected_data = expected.data.to_owned().into_bytes();
            assert_eq!(actual_data, expected_data);
        }
    }

    #[test_case(Input{source: "/foo/bar::/data/cat.txt", destination: "/bar/foo::/data/foo.txt"}; "bad_file")]
    #[test_case(Input{source: "/foo/bar::/foo.txt", destination: "/bar/foo::/data/foo.txt"}; "bad_source_folder")]
    #[test_case(Input{source: "/hello/world::/data/foo.txt", destination: "/bar/foo::/data/file.txt"}; "bad_source_moniker")]
    #[test_case(Input{source: "/foo/bar::/data/foo.txt", destination: "/hello/world::/data/file.txt"}; "bad_destination_moniker")]
    #[fuchsia::test]
    async fn copy_device_to_device_fails(input: Input) {
        let (realm_query, _, _) = create_realm_query_simple(
            generate_file_paths(vec![
                File { name: "data/foo.txt", data: "Hello" },
                File { name: "data/bar.txt", data: "World" },
            ]),
            generate_directory_paths(vec!["data"]),
        );

        let result = copy_cmd(
            &realm_query,
            vec![input.source.to_string(), input.destination.to_string()],
            /*verbose=*/ false,
            std::io::stdout(),
        )
        .await;

        assert!(result.is_err());
    }

    #[test_case(Inputs{sources: vec!["foo.txt"], destination: "/foo/bar::/data/"},
                generate_directory_paths(vec!["data"]),
                vec![Expectation{path: "data/foo.txt", data: "Hello"}]; "single_file_wildcard")]
    #[test_case(Inputs{sources: vec!["foo.txt"], destination: "/foo/bar::/data/"},
                generate_file_paths(vec![File{ name: "data/foo.txt", data: "World"}]),
                vec![Expectation{path: "data/foo.txt", data: "Hello"}]; "single_file_wildcard_overwrite")]
    #[test_case(Inputs{sources: vec!["foo.txt", "bar.txt"], destination: "/foo/bar::/data/"},
                generate_directory_paths(vec!["data"]),
                vec![Expectation{path: "data/foo.txt", data: "Hello"}, Expectation{path: "data/bar.txt", data: "World"}]; "multi_file_wildcard")]
    #[test_case(Inputs{sources: vec!["foo.txt", "bar.txt"], destination: "/foo/bar::/data/"},
                generate_file_paths(vec![File{ name: "data/foo.txt", data: "World"}, File{ name: "data/bar.txt", data: "World"}]),
                vec![Expectation{path: "data/foo.txt", data: "Hello"}, Expectation{path: "data/bar.txt", data: "World"}]; "multi_wildcard_file_overwrite")]
    #[fuchsia::test]
    async fn copy_local_to_device_wildcard(
        input: Inputs,
        foo_files: Vec<SeedPath>,
        expectation: Vec<Expectation>,
    ) {
        let local_dir = create_tmp_dir(vec![]).unwrap();
        let local_path = local_dir.path();

        for (path, expected) in zip(input.sources.clone(), expectation.clone()) {
            let source_path = local_path.join(path);
            write(&source_path, expected.data).unwrap();
        }

        let (realm_query, foo_path, _) = create_realm_query_simple(foo_files, vec![]);
        let mut paths: Vec<String> = input
            .sources
            .into_iter()
            .map(|path| local_path.join(path).display().to_string())
            .collect();
        paths.push(input.destination.to_string());

        copy_cmd(&realm_query, paths, /*verbose=*/ false, std::io::stdout()).await.unwrap();

        for expected in expectation {
            let actual_path = foo_path.join(expected.path);
            let actual_data = read(actual_path).unwrap();
            let expected_data = expected.data.to_owned().into_bytes();
            assert_eq!(actual_data, expected_data);
        }
    }

    #[test_case(Input{source: "foo.txt", destination: "wrong_moniker/foo/bar::/data/foo.txt"}; "bad_moniker")]
    #[test_case(Input{source: "foo.txt", destination: "/foo/bar:://bar/foo.txt"}; "bad_directory")]
    #[fuchsia::test]
    async fn copy_local_to_device_fails(input: Input) {
        let local_dir = create_tmp_dir(vec![]).unwrap();
        let local_path = local_dir.path();

        let source_path = local_path.join(input.source);
        write(&source_path, "Hello".to_owned().into_bytes()).unwrap();

        let (realm_query, _, _) =
            create_realm_query_simple(generate_directory_paths(vec!["data"]), vec![]);

        let result = copy_cmd(
            &realm_query,
            vec![source_path.display().to_string(), input.destination.to_string()],
            /*verbose=*/ false,
            std::io::stdout(),
        )
        .await;

        assert!(result.is_err());
    }

    #[test_case(vec![]; "no_wildcard_matches")]
    #[test_case(vec!["foo.txt"]; "not_enough_args")]
    #[test_case(vec!["/foo/bar::/data/*", "/foo/bar::/data/*"]; "remote_wildcard_destination")]
    #[test_case(vec!["/foo/bar::/data/*", "/foo/bar::/data/*", "/"]; "multi_wildcards_remote")]
    #[test_case(vec!["*", "*"]; "local_wildcard_destination")]
    #[fuchsia::test]
    async fn copy_wildcard_fails(paths: Vec<&str>) {
        let (realm_query, _, _) = create_realm_query_simple(
            generate_file_paths(vec![File { name: "data/foo.txt", data: "Hello" }]),
            vec![],
        );
        let paths = paths.into_iter().map(|s| s.to_string()).collect();
        let result = copy_cmd(&realm_query, paths, /*verbose=*/ false, std::io::stdout()).await;

        assert!(result.is_err());
    }

    #[test_case(Inputs{sources: vec!["/foo/bar::/data/foo.txt", "bar.txt"], destination: "/bar/foo::/data/"},
                generate_file_paths(vec![File{ name: "bar.txt", data: "World"}]),
                generate_file_paths(vec![File{ name: "data/foo.txt", data: "Hello"}, File{ name: "data/bar.txt", data: "World"}]),
                generate_directory_paths(vec!["data"]),
                vec![Expectation{path: "data/foo.txt", data: "Hello"}, Expectation{path: "data/bar.txt", data: "World"}]; "no_wildcard_mix")]
    #[test_case(Inputs{sources: vec!["/foo/bar::/data/foo.txt", "/foo/bar::/data/*", "foobar.txt"], destination: "/bar/foo::/data/"},
                generate_file_paths(vec![File{ name: "foobar.txt", data: "World"}]),
                generate_file_paths(vec![File{ name: "data/foo.txt", data: "Hello"}, File{ name: "data/bar.txt", data: "World"}]),
                generate_directory_paths(vec!["data"]),
                vec![Expectation{path: "data/foo.txt", data: "Hello"}, Expectation{path: "data/bar.txt", data: "World"}, Expectation{path: "data/foobar.txt", data: "World"}]; "wildcard_mix")]
    #[test_case(Inputs{sources: vec!["/foo/bar::/data/*", "/foo/bar::/data/*", "foobar.txt"], destination: "/bar/foo::/data/"},
                generate_file_paths(vec![File{ name: "foobar.txt", data: "World"}]),
                generate_file_paths(vec![File{ name: "data/foo.txt", data: "Hello"}, File{ name: "data/bar.txt", data: "World"}]),
                generate_directory_paths(vec!["data"]),
                vec![Expectation{path: "data/foo.txt", data: "Hello"}, Expectation{path: "data/bar.txt", data: "World"}, Expectation{path: "data/foobar.txt", data: "World"}]; "double_wildcard")]
    #[fuchsia::test]
    async fn copy_mixed_tests_remote_destination(
        input: Inputs,
        local_files: Vec<SeedPath>,
        foo_files: Vec<SeedPath>,
        bar_files: Vec<SeedPath>,
        expectation: Vec<Expectation>,
    ) {
        let local_dir = create_tmp_dir(local_files).unwrap();
        let local_path = local_dir.path();

        let (realm_query, _, bar_path) = create_realm_query_simple(foo_files, bar_files);
        let mut paths: Vec<String> = input
            .sources
            .clone()
            .into_iter()
            .map(|path| match LocalOrRemoteDirectoryPath::parse(&path) {
                LocalOrRemoteDirectoryPath::Remote(_) => path.to_string(),
                LocalOrRemoteDirectoryPath::Local(_) => local_path.join(path).display().to_string(),
            })
            .collect();
        paths.push(input.destination.to_owned());

        copy_cmd(&realm_query, paths, /*verbose=*/ false, std::io::stdout()).await.unwrap();

        for expected in expectation {
            let actual_path = bar_path.join(expected.path);
            let actual_data = read(actual_path).unwrap();
            let expected_data = expected.data.to_owned().into_bytes();
            assert_eq!(actual_data, expected_data);
        }
    }
}