-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathcp.rs
2697 lines (2493 loc) · 92.9 KB
/
cp.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
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
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This file is part of the uutils coreutils package.
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
// spell-checker:ignore (ToDO) copydir ficlone fiemap ftruncate linkgs lstat nlink nlinks pathbuf pwrite reflink strs xattrs symlinked deduplicated advcpmv nushell IRWXG IRWXO IRWXU IRWXUGO IRWXU IRWXG IRWXO IRWXUGO
use quick_error::quick_error;
use std::cmp::Ordering;
use std::collections::{HashMap, HashSet};
use std::ffi::OsString;
use std::fs::{self, Metadata, OpenOptions, Permissions};
use std::io;
#[cfg(unix)]
use std::os::unix::fs::{FileTypeExt, PermissionsExt};
use std::path::{Path, PathBuf, StripPrefixError};
#[cfg(all(unix, not(target_os = "android")))]
use uucore::fsxattr::copy_xattrs;
use clap::{Arg, ArgAction, ArgMatches, Command, builder::ValueParser};
use filetime::FileTime;
use indicatif::{ProgressBar, ProgressStyle};
use quick_error::ResultExt;
use platform::copy_on_write;
use uucore::display::Quotable;
use uucore::error::{UClapError, UError, UResult, UUsageError, set_exit_code};
#[cfg(unix)]
use uucore::fs::make_fifo;
use uucore::fs::{
FileInformation, MissingHandling, ResolveMode, are_hardlinks_to_same_file, canonicalize,
get_filename, is_symlink_loop, normalize_path, path_ends_with_terminator,
paths_refer_to_same_file,
};
use uucore::{backup_control, update_control};
// These are exposed for projects (e.g. nushell) that want to create an `Options` value, which
// requires these enum.
pub use uucore::{backup_control::BackupMode, update_control::UpdateMode};
use uucore::{
format_usage, help_about, help_section, help_usage,
parser::shortcut_value_parser::ShortcutValueParser, prompt_yes, show_error, show_warning,
};
use crate::copydir::copy_directory;
mod copydir;
mod platform;
quick_error! {
#[derive(Debug)]
pub enum Error {
/// Simple io::Error wrapper
IoErr(err: io::Error) { from() source(err) display("{err}")}
/// Wrapper for io::Error with path context
IoErrContext(err: io::Error, path: String) {
display("{path}: {err}")
context(path: &'a str, err: io::Error) -> (err, path.to_owned())
context(context: String, err: io::Error) -> (err, context)
source(err)
}
/// General copy error
Error(err: String) {
display("{err}")
from(err: String) -> (err)
from(err: &'static str) -> (err.to_string())
}
/// Represents the state when a non-fatal error has occurred
/// and not all files were copied.
NotAllFilesCopied {}
/// Simple walkdir::Error wrapper
WalkDirErr(err: walkdir::Error) { from() display("{err}") source(err) }
/// Simple std::path::StripPrefixError wrapper
StripPrefixError(err: StripPrefixError) { from() }
/// Result of a skipped file
/// Currently happens when "no" is selected in interactive mode or when
/// `no-clobber` flag is set and destination is already present.
/// `exit with error` is used to determine which exit code should be returned.
Skipped(exit_with_error:bool) { }
/// Result of a skipped file
InvalidArgument(description: String) { display("{description}") }
/// All standard options are included as an an implementation
/// path, but those that are not implemented yet should return
/// a NotImplemented error.
NotImplemented(opt: String) { display("Option '{opt}' not yet implemented.") }
/// Invalid arguments to backup
Backup(description: String) { display("{description}\nTry '{} --help' for more information.", uucore::execution_phrase()) }
NotADirectory(path: PathBuf) { display("'{}' is not a directory", path.display()) }
}
}
impl UError for Error {
fn code(&self) -> i32 {
EXIT_ERR
}
}
pub type CopyResult<T> = Result<T, Error>;
/// Specifies how to overwrite files.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Default)]
pub enum ClobberMode {
Force,
RemoveDestination,
#[default]
Standard,
}
/// Specifies whether files should be overwritten.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum OverwriteMode {
/// [Default] Always overwrite existing files
Clobber(ClobberMode),
/// Prompt before overwriting a file
Interactive(ClobberMode),
/// Never overwrite a file
NoClobber,
}
impl Default for OverwriteMode {
fn default() -> Self {
Self::Clobber(ClobberMode::default())
}
}
/// Possible arguments for `--reflink`.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum ReflinkMode {
Always,
Auto,
Never,
}
impl Default for ReflinkMode {
#[allow(clippy::derivable_impls)]
fn default() -> Self {
#[cfg(any(target_os = "linux", target_os = "android", target_os = "macos"))]
{
ReflinkMode::Auto
}
#[cfg(not(any(target_os = "linux", target_os = "android", target_os = "macos")))]
{
ReflinkMode::Never
}
}
}
/// Possible arguments for `--sparse`.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
pub enum SparseMode {
Always,
#[default]
Auto,
Never,
}
/// The expected file type of copy target
#[derive(Copy, Clone)]
pub enum TargetType {
Directory,
File,
}
/// Copy action to perform
#[derive(Debug, Clone, Eq, PartialEq, Default)]
pub enum CopyMode {
Link,
SymLink,
#[default]
Copy,
Update,
AttrOnly,
}
/// Preservation settings for various attributes
///
/// It should be derived from options as follows:
///
/// - if there is a list of attributes to preserve (i.e. `--preserve=ATTR_LIST`) parse that list with [`Attributes::parse_iter`],
/// - if `-p` or `--preserve` is given without arguments, use [`Attributes::DEFAULT`],
/// - if `-a`/`--archive` is passed, use [`Attributes::ALL`],
/// - if `-d` is passed use [`Attributes::LINKS`],
/// - otherwise, use [`Attributes::NONE`].
///
/// For full compatibility with GNU, these options should also combine. We
/// currently only do a best effort imitation of that behavior, because it is
/// difficult to achieve in clap, especially with `--no-preserve`.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct Attributes {
#[cfg(unix)]
pub ownership: Preserve,
pub mode: Preserve,
pub timestamps: Preserve,
pub context: Preserve,
pub links: Preserve,
pub xattr: Preserve,
}
impl Default for Attributes {
fn default() -> Self {
Self::NONE
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Preserve {
// explicit means whether the --no-preserve flag is used or not to distinguish out the default value.
// e.g. --no-preserve=mode means mode = No { explicit = true }
No { explicit: bool },
Yes { required: bool },
}
impl PartialOrd for Preserve {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Preserve {
fn cmp(&self, other: &Self) -> Ordering {
match (self, other) {
(Self::No { .. }, Self::No { .. }) => Ordering::Equal,
(Self::Yes { .. }, Self::No { .. }) => Ordering::Greater,
(Self::No { .. }, Self::Yes { .. }) => Ordering::Less,
(
Self::Yes { required: req_self },
Self::Yes {
required: req_other,
},
) => req_self.cmp(req_other),
}
}
}
/// Options for the `cp` command
///
/// All options are public so that the options can be programmatically
/// constructed by other crates, such as nushell. That means that this struct
/// is part of our public API. It should therefore not be changed without good
/// reason.
///
/// The fields are documented with the arguments that determine their value.
#[allow(dead_code)]
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Options {
/// `--attributes-only`
pub attributes_only: bool,
/// `--backup[=CONTROL]`, `-b`
pub backup: BackupMode,
/// `--copy-contents`
pub copy_contents: bool,
/// `-H`
pub cli_dereference: bool,
/// Determines the type of copying that should be done
///
/// Set by the following arguments:
/// - `-l`, `--link`: [`CopyMode::Link`]
/// - `-s`, `--symbolic-link`: [`CopyMode::SymLink`]
/// - `-u`, `--update[=WHEN]`: [`CopyMode::Update`]
/// - `--attributes-only`: [`CopyMode::AttrOnly`]
/// - otherwise: [`CopyMode::Copy`]
pub copy_mode: CopyMode,
/// `-L`, `--dereference`
pub dereference: bool,
/// `-T`, `--no-target-dir`
pub no_target_dir: bool,
/// `-x`, `--one-file-system`
pub one_file_system: bool,
/// Specifies what to do with an existing destination
///
/// Set by the following arguments:
/// - `-i`, `--interactive`: [`OverwriteMode::Interactive`]
/// - `-n`, `--no-clobber`: [`OverwriteMode::NoClobber`]
/// - otherwise: [`OverwriteMode::Clobber`]
///
/// The `Interactive` and `Clobber` variants have a [`ClobberMode`] argument,
/// set by the following arguments:
/// - `-f`, `--force`: [`ClobberMode::Force`]
/// - `--remove-destination`: [`ClobberMode::RemoveDestination`]
/// - otherwise: [`ClobberMode::Standard`]
pub overwrite: OverwriteMode,
/// `--parents`
pub parents: bool,
/// `--sparse[=WHEN]`
pub sparse_mode: SparseMode,
/// `--strip-trailing-slashes`
pub strip_trailing_slashes: bool,
/// `--reflink[=WHEN]`
pub reflink_mode: ReflinkMode,
/// `--preserve=[=ATTRIBUTE_LIST]` and `--no-preserve=ATTRIBUTE_LIST`
pub attributes: Attributes,
/// `-R`, `-r`, `--recursive`
pub recursive: bool,
/// `-S`, `--suffix`
pub backup_suffix: String,
/// `-t`, `--target-directory`
pub target_dir: Option<PathBuf>,
/// `--update[=UPDATE]`
pub update: UpdateMode,
/// `--debug`
pub debug: bool,
/// `-v`, `--verbose`
pub verbose: bool,
/// `-g`, `--progress`
pub progress_bar: bool,
}
impl Default for Options {
fn default() -> Self {
Self {
attributes_only: false,
backup: BackupMode::default(),
copy_contents: false,
cli_dereference: false,
copy_mode: CopyMode::default(),
dereference: false,
no_target_dir: false,
one_file_system: false,
overwrite: OverwriteMode::default(),
parents: false,
sparse_mode: SparseMode::default(),
strip_trailing_slashes: false,
reflink_mode: ReflinkMode::default(),
attributes: Attributes::default(),
recursive: false,
backup_suffix: backup_control::DEFAULT_BACKUP_SUFFIX.to_owned(),
target_dir: None,
update: UpdateMode::default(),
debug: false,
verbose: false,
progress_bar: false,
}
}
}
/// Enum representing if a file has been skipped.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum PerformedAction {
Copied,
Skipped,
}
/// Enum representing various debug states of the offload and reflink actions.
#[derive(Debug)]
#[allow(dead_code)] // All of them are used on Linux
enum OffloadReflinkDebug {
Unknown,
No,
Yes,
Avoided,
Unsupported,
}
/// Enum representing various debug states of the sparse detection.
#[derive(Debug)]
#[allow(dead_code)] // silent for now until we use them
enum SparseDebug {
Unknown,
No,
Zeros,
SeekHole,
SeekHoleZeros,
Unsupported,
}
/// Struct that contains the debug state for each action in a file copy operation.
#[derive(Debug)]
struct CopyDebug {
offload: OffloadReflinkDebug,
reflink: OffloadReflinkDebug,
sparse_detection: SparseDebug,
}
impl OffloadReflinkDebug {
fn to_string(&self) -> &'static str {
match self {
Self::No => "no",
Self::Yes => "yes",
Self::Avoided => "avoided",
Self::Unsupported => "unsupported",
Self::Unknown => "unknown",
}
}
}
impl SparseDebug {
fn to_string(&self) -> &'static str {
match self {
Self::No => "no",
Self::Zeros => "zeros",
Self::SeekHole => "SEEK_HOLE",
Self::SeekHoleZeros => "SEEK_HOLE + zeros",
Self::Unsupported => "unsupported",
Self::Unknown => "unknown",
}
}
}
/// This function prints the debug information of a file copy operation if
/// no hard link or symbolic link is required, and data copy is required.
/// It prints the debug information of the offload, reflink, and sparse detection actions.
fn show_debug(copy_debug: &CopyDebug) {
println!(
"copy offload: {}, reflink: {}, sparse detection: {}",
copy_debug.offload.to_string(),
copy_debug.reflink.to_string(),
copy_debug.sparse_detection.to_string(),
);
}
const ABOUT: &str = help_about!("cp.md");
const USAGE: &str = help_usage!("cp.md");
const AFTER_HELP: &str = help_section!("after help", "cp.md");
static EXIT_ERR: i32 = 1;
// Argument constants
mod options {
pub const ARCHIVE: &str = "archive";
pub const ATTRIBUTES_ONLY: &str = "attributes-only";
pub const CLI_SYMBOLIC_LINKS: &str = "cli-symbolic-links";
pub const CONTEXT: &str = "context";
pub const COPY_CONTENTS: &str = "copy-contents";
pub const DEREFERENCE: &str = "dereference";
pub const FORCE: &str = "force";
pub const INTERACTIVE: &str = "interactive";
pub const LINK: &str = "link";
pub const NO_CLOBBER: &str = "no-clobber";
pub const NO_DEREFERENCE: &str = "no-dereference";
pub const NO_DEREFERENCE_PRESERVE_LINKS: &str = "no-dereference-preserve-links";
pub const NO_PRESERVE: &str = "no-preserve";
pub const NO_TARGET_DIRECTORY: &str = "no-target-directory";
pub const ONE_FILE_SYSTEM: &str = "one-file-system";
pub const PARENT: &str = "parent";
pub const PARENTS: &str = "parents";
pub const PATHS: &str = "paths";
pub const PROGRESS_BAR: &str = "progress";
pub const PRESERVE: &str = "preserve";
pub const PRESERVE_DEFAULT_ATTRIBUTES: &str = "preserve-default-attributes";
pub const RECURSIVE: &str = "recursive";
pub const REFLINK: &str = "reflink";
pub const REMOVE_DESTINATION: &str = "remove-destination";
pub const SPARSE: &str = "sparse";
pub const STRIP_TRAILING_SLASHES: &str = "strip-trailing-slashes";
pub const SYMBOLIC_LINK: &str = "symbolic-link";
pub const TARGET_DIRECTORY: &str = "target-directory";
pub const DEBUG: &str = "debug";
pub const VERBOSE: &str = "verbose";
}
#[cfg(unix)]
static PRESERVABLE_ATTRIBUTES: &[&str] = &[
"mode",
"ownership",
"timestamps",
"context",
"links",
"xattr",
"all",
];
#[cfg(not(unix))]
static PRESERVABLE_ATTRIBUTES: &[&str] =
&["mode", "timestamps", "context", "links", "xattr", "all"];
const PRESERVE_DEFAULT_VALUES: &str = if cfg!(unix) {
"mode,ownership,timestamp"
} else {
"mode,timestamp"
};
pub fn uu_app() -> Command {
const MODE_ARGS: &[&str] = &[
options::LINK,
options::REFLINK,
options::SYMBOLIC_LINK,
options::ATTRIBUTES_ONLY,
options::COPY_CONTENTS,
];
Command::new(uucore::util_name())
.version(uucore::crate_version!())
.about(ABOUT)
.override_usage(format_usage(USAGE))
.after_help(format!(
"{AFTER_HELP}\n\n{}",
backup_control::BACKUP_CONTROL_LONG_HELP
))
.infer_long_args(true)
.args_override_self(true)
.arg(
Arg::new(options::TARGET_DIRECTORY)
.short('t')
.conflicts_with(options::NO_TARGET_DIRECTORY)
.long(options::TARGET_DIRECTORY)
.value_name(options::TARGET_DIRECTORY)
.value_hint(clap::ValueHint::DirPath)
.value_parser(ValueParser::path_buf())
.help("copy all SOURCE arguments into target-directory"),
)
.arg(
Arg::new(options::NO_TARGET_DIRECTORY)
.short('T')
.long(options::NO_TARGET_DIRECTORY)
.conflicts_with(options::TARGET_DIRECTORY)
.help("Treat DEST as a regular file and not a directory")
.action(ArgAction::SetTrue),
)
.arg(
Arg::new(options::INTERACTIVE)
.short('i')
.long(options::INTERACTIVE)
.overrides_with(options::NO_CLOBBER)
.help("ask before overwriting files")
.action(ArgAction::SetTrue),
)
.arg(
Arg::new(options::LINK)
.short('l')
.long(options::LINK)
.overrides_with_all(MODE_ARGS)
.help("hard-link files instead of copying")
.action(ArgAction::SetTrue),
)
.arg(
Arg::new(options::NO_CLOBBER)
.short('n')
.long(options::NO_CLOBBER)
.overrides_with(options::INTERACTIVE)
.help("don't overwrite a file that already exists")
.action(ArgAction::SetTrue),
)
.arg(
Arg::new(options::RECURSIVE)
.short('R')
.visible_short_alias('r')
.long(options::RECURSIVE)
// --archive sets this option
.help("copy directories recursively")
.action(ArgAction::SetTrue),
)
.arg(
Arg::new(options::STRIP_TRAILING_SLASHES)
.long(options::STRIP_TRAILING_SLASHES)
.help("remove any trailing slashes from each SOURCE argument")
.action(ArgAction::SetTrue),
)
.arg(
Arg::new(options::DEBUG)
.long(options::DEBUG)
.help("explain how a file is copied. Implies -v")
.action(ArgAction::SetTrue),
)
.arg(
Arg::new(options::VERBOSE)
.short('v')
.long(options::VERBOSE)
.help("explicitly state what is being done")
.action(ArgAction::SetTrue),
)
.arg(
Arg::new(options::SYMBOLIC_LINK)
.short('s')
.long(options::SYMBOLIC_LINK)
.overrides_with_all(MODE_ARGS)
.help("make symbolic links instead of copying")
.action(ArgAction::SetTrue),
)
.arg(
Arg::new(options::FORCE)
.short('f')
.long(options::FORCE)
.help(
"if an existing destination file cannot be opened, remove it and \
try again (this option is ignored when the -n option is also used). \
Currently not implemented for Windows.",
)
.action(ArgAction::SetTrue),
)
.arg(
Arg::new(options::REMOVE_DESTINATION)
.long(options::REMOVE_DESTINATION)
.overrides_with(options::FORCE)
.help(
"remove each existing destination file before attempting to open it \
(contrast with --force). On Windows, currently only works for \
writeable files.",
)
.action(ArgAction::SetTrue),
)
.arg(backup_control::arguments::backup())
.arg(backup_control::arguments::backup_no_args())
.arg(backup_control::arguments::suffix())
.arg(update_control::arguments::update())
.arg(update_control::arguments::update_no_args())
.arg(
Arg::new(options::REFLINK)
.long(options::REFLINK)
.value_name("WHEN")
.overrides_with_all(MODE_ARGS)
.require_equals(true)
.default_missing_value("always")
.value_parser(ShortcutValueParser::new(["auto", "always", "never"]))
.num_args(0..=1)
.help("control clone/CoW copies. See below"),
)
.arg(
Arg::new(options::ATTRIBUTES_ONLY)
.long(options::ATTRIBUTES_ONLY)
.overrides_with_all(MODE_ARGS)
.help("Don't copy the file data, just the attributes")
.action(ArgAction::SetTrue),
)
.arg(
Arg::new(options::PRESERVE)
.long(options::PRESERVE)
.action(ArgAction::Append)
.use_value_delimiter(true)
.value_parser(ShortcutValueParser::new(PRESERVABLE_ATTRIBUTES))
.num_args(0..)
.require_equals(true)
.value_name("ATTR_LIST")
.default_missing_value(PRESERVE_DEFAULT_VALUES)
// -d sets this option
// --archive sets this option
.help(
"Preserve the specified attributes (default: mode, ownership (unix only), \
timestamps), if possible additional attributes: context, links, xattr, all",
),
)
.arg(
Arg::new(options::PRESERVE_DEFAULT_ATTRIBUTES)
.short('p')
.long(options::PRESERVE_DEFAULT_ATTRIBUTES)
.help("same as --preserve=mode,ownership(unix only),timestamps")
.action(ArgAction::SetTrue),
)
.arg(
Arg::new(options::NO_PRESERVE)
.long(options::NO_PRESERVE)
.action(ArgAction::Append)
.use_value_delimiter(true)
.value_parser(ShortcutValueParser::new(PRESERVABLE_ATTRIBUTES))
.num_args(0..)
.require_equals(true)
.value_name("ATTR_LIST")
.help("don't preserve the specified attributes"),
)
.arg(
Arg::new(options::PARENTS)
.long(options::PARENTS)
.alias(options::PARENT)
.help("use full source file name under DIRECTORY")
.action(ArgAction::SetTrue),
)
.arg(
Arg::new(options::NO_DEREFERENCE)
.short('P')
.long(options::NO_DEREFERENCE)
.overrides_with(options::DEREFERENCE)
// -d sets this option
.help("never follow symbolic links in SOURCE")
.action(ArgAction::SetTrue),
)
.arg(
Arg::new(options::DEREFERENCE)
.short('L')
.long(options::DEREFERENCE)
.overrides_with(options::NO_DEREFERENCE)
.help("always follow symbolic links in SOURCE")
.action(ArgAction::SetTrue),
)
.arg(
Arg::new(options::CLI_SYMBOLIC_LINKS)
.short('H')
.help("follow command-line symbolic links in SOURCE")
.action(ArgAction::SetTrue),
)
.arg(
Arg::new(options::ARCHIVE)
.short('a')
.long(options::ARCHIVE)
.help("Same as -dR --preserve=all")
.action(ArgAction::SetTrue),
)
.arg(
Arg::new(options::NO_DEREFERENCE_PRESERVE_LINKS)
.short('d')
.help("same as --no-dereference --preserve=links")
.action(ArgAction::SetTrue),
)
.arg(
Arg::new(options::ONE_FILE_SYSTEM)
.short('x')
.long(options::ONE_FILE_SYSTEM)
.help("stay on this file system")
.action(ArgAction::SetTrue),
)
.arg(
Arg::new(options::SPARSE)
.long(options::SPARSE)
.value_name("WHEN")
.value_parser(ShortcutValueParser::new(["never", "auto", "always"]))
.help("control creation of sparse files. See below"),
)
// TODO: implement the following args
.arg(
Arg::new(options::COPY_CONTENTS)
.long(options::COPY_CONTENTS)
.overrides_with(options::ATTRIBUTES_ONLY)
.help("NotImplemented: copy contents of special files when recursive")
.action(ArgAction::SetTrue),
)
.arg(
Arg::new(options::CONTEXT)
.long(options::CONTEXT)
.value_name("CTX")
.help(
"NotImplemented: set SELinux security context of destination file to \
default type",
),
)
// END TODO
.arg(
// The 'g' short flag is modeled after advcpmv
// See this repo: https://github.com/jarun/advcpmv
Arg::new(options::PROGRESS_BAR)
.long(options::PROGRESS_BAR)
.short('g')
.action(ArgAction::SetTrue)
.help(
"Display a progress bar. \n\
Note: this feature is not supported by GNU coreutils.",
),
)
.arg(
Arg::new(options::PATHS)
.action(ArgAction::Append)
.num_args(1..)
.required(true)
.value_hint(clap::ValueHint::AnyPath)
.value_parser(ValueParser::os_string()),
)
}
#[uucore::main]
pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let matches = uu_app().try_get_matches_from(args);
// The error is parsed here because we do not want version or help being printed to stderr.
if let Err(e) = matches {
let mut app = uu_app();
match e.kind() {
clap::error::ErrorKind::DisplayHelp => {
app.print_help()?;
}
clap::error::ErrorKind::DisplayVersion => print!("{}", app.render_version()),
_ => return Err(Box::new(e.with_exit_code(1))),
};
} else if let Ok(mut matches) = matches {
let options = Options::from_matches(&matches)?;
if options.overwrite == OverwriteMode::NoClobber && options.backup != BackupMode::None {
return Err(UUsageError::new(
EXIT_ERR,
"options --backup and --no-clobber are mutually exclusive",
));
}
let paths: Vec<PathBuf> = matches
.remove_many::<OsString>(options::PATHS)
.map(|v| v.map(PathBuf::from).collect())
.unwrap_or_default();
let (sources, target) = parse_path_args(paths, &options)?;
if let Err(error) = copy(&sources, &target, &options) {
match error {
// Error::NotAllFilesCopied is non-fatal, but the error
// code should still be EXIT_ERR as does GNU cp
Error::NotAllFilesCopied => {}
// Else we caught a fatal bubbled-up error, log it to stderr
_ => show_error!("{error}"),
};
set_exit_code(EXIT_ERR);
}
}
Ok(())
}
impl ClobberMode {
fn from_matches(matches: &ArgMatches) -> Self {
if matches.get_flag(options::FORCE) {
Self::Force
} else if matches.get_flag(options::REMOVE_DESTINATION) {
Self::RemoveDestination
} else {
Self::Standard
}
}
}
impl OverwriteMode {
fn from_matches(matches: &ArgMatches) -> Self {
if matches.get_flag(options::INTERACTIVE) {
Self::Interactive(ClobberMode::from_matches(matches))
} else if matches.get_flag(options::NO_CLOBBER) {
Self::NoClobber
} else {
Self::Clobber(ClobberMode::from_matches(matches))
}
}
}
impl CopyMode {
fn from_matches(matches: &ArgMatches) -> Self {
if matches.get_flag(options::LINK) {
Self::Link
} else if matches.get_flag(options::SYMBOLIC_LINK) {
Self::SymLink
} else if matches
.get_one::<String>(update_control::arguments::OPT_UPDATE)
.is_some()
|| matches.get_flag(update_control::arguments::OPT_UPDATE_NO_ARG)
{
Self::Update
} else if matches.get_flag(options::ATTRIBUTES_ONLY) {
if matches.get_flag(options::REMOVE_DESTINATION) {
Self::Copy
} else {
Self::AttrOnly
}
} else {
Self::Copy
}
}
}
impl Attributes {
pub const ALL: Self = Self {
#[cfg(unix)]
ownership: Preserve::Yes { required: true },
mode: Preserve::Yes { required: true },
timestamps: Preserve::Yes { required: true },
context: {
#[cfg(feature = "feat_selinux")]
{
Preserve::Yes { required: false }
}
#[cfg(not(feature = "feat_selinux"))]
{
Preserve::No { explicit: false }
}
},
links: Preserve::Yes { required: true },
xattr: Preserve::Yes { required: false },
};
pub const NONE: Self = Self {
#[cfg(unix)]
ownership: Preserve::No { explicit: false },
mode: Preserve::No { explicit: false },
timestamps: Preserve::No { explicit: false },
context: Preserve::No { explicit: false },
links: Preserve::No { explicit: false },
xattr: Preserve::No { explicit: false },
};
// TODO: ownership is required if the user is root, for non-root users it's not required.
pub const DEFAULT: Self = Self {
#[cfg(unix)]
ownership: Preserve::Yes { required: true },
mode: Preserve::Yes { required: true },
timestamps: Preserve::Yes { required: true },
xattr: Preserve::Yes { required: true },
..Self::NONE
};
pub const LINKS: Self = Self {
links: Preserve::Yes { required: true },
..Self::NONE
};
pub fn union(self, other: &Self) -> Self {
Self {
#[cfg(unix)]
ownership: self.ownership.max(other.ownership),
context: self.context.max(other.context),
timestamps: self.timestamps.max(other.timestamps),
mode: self.mode.max(other.mode),
links: self.links.max(other.links),
xattr: self.xattr.max(other.xattr),
}
}
/// Set the field to Preserve::NO { explicit: true } if the corresponding field
/// in other is set to Preserve::Yes { .. }.
pub fn diff(self, other: &Self) -> Self {
fn update_preserve_field(current: Preserve, other: Preserve) -> Preserve {
if matches!(other, Preserve::Yes { .. }) {
Preserve::No { explicit: true }
} else {
current
}
}
Self {
#[cfg(unix)]
ownership: update_preserve_field(self.ownership, other.ownership),
mode: update_preserve_field(self.mode, other.mode),
timestamps: update_preserve_field(self.timestamps, other.timestamps),
context: update_preserve_field(self.context, other.context),
links: update_preserve_field(self.links, other.links),
xattr: update_preserve_field(self.xattr, other.xattr),
}
}
pub fn parse_iter<T>(values: impl Iterator<Item = T>) -> Result<Self, Error>
where
T: AsRef<str>,
{
let mut new = Self::NONE;
for value in values {
new = new.union(&Self::parse_single_string(value.as_ref())?);
}
Ok(new)
}
/// Tries to match string containing a parameter to preserve with the corresponding entry in the
/// Attributes struct.
fn parse_single_string(value: &str) -> Result<Self, Error> {
let value = value.to_lowercase();
if value == "all" {
return Ok(Self::ALL);
}
let mut new = Self::NONE;
let attribute = match value.as_ref() {
"mode" => &mut new.mode,
#[cfg(unix)]
"ownership" => &mut new.ownership,
"timestamps" => &mut new.timestamps,
"context" => &mut new.context,
"link" | "links" => &mut new.links,
"xattr" => &mut new.xattr,
_ => {
return Err(Error::InvalidArgument(format!(
"invalid attribute {}",
value.quote()
)));
}
};
*attribute = Preserve::Yes { required: true };
Ok(new)
}
}
impl Options {
#[allow(clippy::cognitive_complexity)]
fn from_matches(matches: &ArgMatches) -> CopyResult<Self> {
let not_implemented_opts = vec![
#[cfg(not(any(windows, unix)))]
options::ONE_FILE_SYSTEM,
options::CONTEXT,
#[cfg(windows)]
options::FORCE,
];
for not_implemented_opt in not_implemented_opts {
if matches.contains_id(not_implemented_opt)
&& matches.value_source(not_implemented_opt)
== Some(clap::parser::ValueSource::CommandLine)
{
return Err(Error::NotImplemented(not_implemented_opt.to_string()));
}
}
let recursive = matches.get_flag(options::RECURSIVE) || matches.get_flag(options::ARCHIVE);
let backup_mode = match backup_control::determine_backup_mode(matches) {
Err(e) => return Err(Error::Backup(format!("{e}"))),
Ok(mode) => mode,
};
let update_mode = update_control::determine_update_mode(matches);
if backup_mode != BackupMode::None
&& matches
.get_one::<String>(update_control::arguments::OPT_UPDATE)
.is_some_and(|v| v == "none" || v == "none-fail")
{