nu_command/filesystem/
umv.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
#[allow(deprecated)]
use nu_engine::{command_prelude::*, current_dir};
use nu_path::expand_path_with;
use nu_protocol::NuGlob;
use std::{ffi::OsString, path::PathBuf};
use uu_mv::{BackupMode, UpdateMode};

#[derive(Clone)]
pub struct UMv;

impl Command for UMv {
    fn name(&self) -> &str {
        "mv"
    }

    fn description(&self) -> &str {
        "Move files or directories using uutils/coreutils mv."
    }

    fn examples(&self) -> Vec<Example> {
        vec![
            Example {
                description: "Rename a file",
                example: "mv before.txt after.txt",
                result: None,
            },
            Example {
                description: "Move a file into a directory",
                example: "mv test.txt my/subdirectory",
                result: None,
            },
            Example {
                description: "Move only if source file is newer than target file",
                example: "mv -u new/test.txt old/",
                result: None,
            },
            Example {
                description: "Move many files into a directory",
                example: "mv *.txt my/subdirectory",
                result: None,
            },
            Example {
                description: r#"Move a file into the "my" directory two levels up in the directory tree"#,
                example: "mv test.txt .../my/",
                result: None,
            },
        ]
    }

    fn search_terms(&self) -> Vec<&str> {
        vec!["move", "file", "files", "coreutils"]
    }

    fn signature(&self) -> nu_protocol::Signature {
        Signature::build("mv")
            .input_output_types(vec![(Type::Nothing, Type::Nothing)])
            .switch("force", "do not prompt before overwriting", Some('f'))
            .switch("verbose", "explain what is being done.", Some('v'))
            .switch("progress", "display a progress bar", Some('p'))
            .switch("interactive", "prompt before overwriting", Some('i'))
            .switch(
                "update",
                "move and overwrite only when the SOURCE file is newer than the destination file or when the destination file is missing",
                Some('u')
            )
            .switch("no-clobber", "do not overwrite an existing file", Some('n'))
            .rest(
                "paths",
                SyntaxShape::OneOf(vec![SyntaxShape::GlobPattern, SyntaxShape::String]),
                "Rename SRC to DST, or move SRC to DIR.",
            )
            .allow_variants_without_examples(true)
            .category(Category::FileSystem)
    }

    fn run(
        &self,
        engine_state: &EngineState,
        stack: &mut Stack,
        call: &Call,
        _input: PipelineData,
    ) -> Result<PipelineData, ShellError> {
        let interactive = call.has_flag(engine_state, stack, "interactive")?;
        let no_clobber = call.has_flag(engine_state, stack, "no-clobber")?;
        let progress = call.has_flag(engine_state, stack, "progress")?;
        let verbose = call.has_flag(engine_state, stack, "verbose")?;
        let overwrite = if no_clobber {
            uu_mv::OverwriteMode::NoClobber
        } else if interactive {
            uu_mv::OverwriteMode::Interactive
        } else {
            uu_mv::OverwriteMode::Force
        };
        let update = if call.has_flag(engine_state, stack, "update")? {
            UpdateMode::ReplaceIfOlder
        } else {
            UpdateMode::ReplaceAll
        };

        #[allow(deprecated)]
        let cwd = current_dir(engine_state, stack)?;
        let mut paths = call.rest::<Spanned<NuGlob>>(engine_state, stack, 0)?;
        if paths.is_empty() {
            return Err(ShellError::GenericError {
                error: "Missing file operand".into(),
                msg: "Missing file operand".into(),
                span: Some(call.head),
                help: Some("Please provide source and destination paths".into()),
                inner: Vec::new(),
            });
        }
        if paths.len() == 1 {
            // expand path for better error message
            return Err(ShellError::GenericError {
                error: "Missing destination path".into(),
                msg: format!(
                    "Missing destination path operand after {}",
                    expand_path_with(paths[0].item.as_ref(), cwd, paths[0].item.is_expand())
                        .to_string_lossy()
                ),
                span: Some(paths[0].span),
                help: None,
                inner: Vec::new(),
            });
        }

        // Do not glob target
        let spanned_target = paths.pop().ok_or(ShellError::NushellFailedSpanned {
            msg: "Missing file operand".into(),
            label: "Missing file operand".into(),
            span: call.head,
        })?;
        let mut files: Vec<(Vec<PathBuf>, bool)> = Vec::new();
        for mut p in paths {
            p.item = p.item.strip_ansi_string_unlikely();
            let exp_files: Vec<Result<PathBuf, ShellError>> =
                nu_engine::glob_from(&p, &cwd, call.head, None)
                    .map(|f| f.1)?
                    .collect();
            if exp_files.is_empty() {
                return Err(ShellError::FileNotFound {
                    file: p.item.to_string(),
                    span: p.span,
                });
            };
            let mut app_vals: Vec<PathBuf> = Vec::new();
            for v in exp_files {
                match v {
                    Ok(path) => {
                        app_vals.push(path);
                    }
                    Err(e) => return Err(e),
                }
            }
            files.push((app_vals, p.item.is_expand()));
        }

        // Make sure to send absolute paths to avoid uu_cp looking for cwd in std::env which is not
        // supported in Nushell
        for (files, need_expand_tilde) in files.iter_mut() {
            for src in files.iter_mut() {
                if !src.is_absolute() {
                    *src = nu_path::expand_path_with(&*src, &cwd, *need_expand_tilde);
                }
            }
        }
        let mut files: Vec<PathBuf> = files.into_iter().flat_map(|x| x.0).collect();

        // Add back the target after globbing
        let abs_target_path = expand_path_with(
            nu_utils::strip_ansi_string_unlikely(spanned_target.item.to_string()),
            &cwd,
            matches!(spanned_target.item, NuGlob::Expand(..)),
        );
        files.push(abs_target_path.clone());
        let files = files
            .into_iter()
            .map(|p| p.into_os_string())
            .collect::<Vec<OsString>>();
        let options = uu_mv::Options {
            overwrite,
            progress_bar: progress,
            verbose,
            suffix: String::from("~"),
            backup: BackupMode::NoBackup,
            update,
            target_dir: None,
            no_target_dir: false,
            strip_slashes: false,
            debug: false,
        };
        if let Err(error) = uu_mv::mv(&files, &options) {
            return Err(ShellError::GenericError {
                error: format!("{}", error),
                msg: format!("{}", error),
                span: None,
                help: None,
                inner: Vec::new(),
            });
        }
        Ok(PipelineData::empty())
    }
}