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
use nu_errors::ShellError;
use nu_protocol::{CallInfo, Value};
use nu_source::{Tag, Tagged, TaggedItem};
use std::path::Path;

#[cfg(not(target_os = "windows"))]
use std::process::{Command, Stdio};

#[derive(Default)]
pub struct Start {
    pub tag: Tag,
    pub filenames: Vec<Tagged<String>>,
    pub application: Option<String>,
}

impl Start {
    pub fn new() -> Start {
        Start {
            tag: Tag::unknown(),
            filenames: vec![],
            application: None,
        }
    }

    pub fn parse(&mut self, call_info: CallInfo) -> Result<(), ShellError> {
        self.tag = call_info.name_tag.clone();
        self.parse_filenames(&call_info)?;
        self.parse_application(&call_info);
        Ok(())
    }

    fn add_filename(&mut self, filename: Tagged<String>) -> Result<(), ShellError> {
        if Path::new(&filename.item).exists() || url::Url::parse(&filename.item).is_ok() {
            self.filenames.push(filename);
            Ok(())
        } else {
            Err(ShellError::labeled_error(
                format!("The file '{}' does not exist", filename.item),
                "doesn't exist",
                filename.tag,
            ))
        }
    }

    fn glob_to_values(&self, value: &Value) -> Result<Vec<Tagged<String>>, ShellError> {
        let mut result = vec![];
        match glob::glob(&value.as_string()?) {
            Ok(paths) => {
                for path_result in paths {
                    match path_result {
                        Ok(path) => result
                            .push(path.to_string_lossy().to_string().tagged(value.tag.clone())),
                        Err(glob_error) => {
                            return Err(ShellError::labeled_error(
                                format!("{}", glob_error),
                                "glob error",
                                value.tag.clone(),
                            ));
                        }
                    }
                }
            }
            Err(pattern_error) => {
                return Err(ShellError::labeled_error(
                    format!("{}", pattern_error),
                    "invalid pattern",
                    value.tag.clone(),
                ))
            }
        }

        Ok(result)
    }

    fn parse_filenames(&mut self, call_info: &CallInfo) -> Result<(), ShellError> {
        let candidates = match &call_info.args.positional {
            Some(values) => {
                let mut result = vec![];

                for value in values.iter() {
                    let res = self.glob_to_values(value)?;
                    result.extend(res);
                }

                if result.is_empty() {
                    return Err(ShellError::labeled_error(
                        "No filename(s) given",
                        "no filename(s) given",
                        self.tag.span,
                    ));
                }
                result
            }
            None => {
                return Err(ShellError::labeled_error(
                    "No filename(s) given",
                    "no filename(s) given",
                    self.tag.span,
                ))
            }
        };

        for candidate in candidates {
            self.add_filename(candidate)?;
        }

        Ok(())
    }

    fn parse_application(&mut self, call_info: &CallInfo) {
        self.application = if let Some(app) = call_info.args.get("application") {
            match app.as_string() {
                Ok(name) => Some(name),
                Err(_) => None,
            }
        } else {
            None
        };
    }

    #[cfg(target_os = "macos")]
    pub fn exec(&mut self) -> Result<(), ShellError> {
        let mut args = vec![];
        args.append(
            &mut self
                .filenames
                .iter()
                .map(|x| x.item.clone())
                .collect::<Vec<_>>(),
        );

        if let Some(app_name) = &self.application {
            args.append(&mut vec![String::from("-a"), app_name.to_string()]);
        }
        exec_cmd("open", &args, self.tag.clone())
    }

    #[cfg(target_os = "windows")]
    pub fn exec(&mut self) -> Result<(), ShellError> {
        if let Some(app_name) = &self.application {
            for file in &self.filenames {
                match open::with(&file.item, app_name) {
                    Ok(_) => continue,
                    Err(_) => {
                        return Err(ShellError::labeled_error(
                            "Failed to open file with specified application",
                            "can't open with specified application",
                            file.tag.span,
                        ))
                    }
                }
            }
        } else {
            for file in &self.filenames {
                match open::that(&file.item) {
                    Ok(_) => continue,
                    Err(_) => {
                        return Err(ShellError::labeled_error(
                            "Failed to open file with default application",
                            "can't open with default application",
                            file.tag.span,
                        ))
                    }
                }
            }
        }
        Ok(())
    }

    #[cfg(not(any(target_os = "windows", target_os = "macos")))]
    pub fn exec(&mut self) -> Result<(), ShellError> {
        let mut args = vec![];
        args.append(
            &mut self
                .filenames
                .iter()
                .map(|x| x.item.clone())
                .collect::<Vec<_>>(),
        );

        if let Some(app_name) = &self.application {
            exec_cmd(&app_name, &args, self.tag.clone())
        } else {
            for cmd in &["xdg-open", "gnome-open", "kde-open", "wslview"] {
                if exec_cmd(cmd, &args, self.tag.clone()).is_err() {
                    continue;
                } else {
                    return Ok(());
                }
            }
            Err(ShellError::labeled_error(
                "Failed to open file(s) with xdg-open. gnome-open, kde-open, and wslview",
                "failed to open xdg-open. gnome-open, kde-open, and wslview",
                self.tag.span,
            ))
        }
    }
}

#[cfg(not(target_os = "windows"))]
fn exec_cmd(cmd: &str, args: &[String], tag: Tag) -> Result<(), ShellError> {
    if args.is_empty() {
        return Err(ShellError::labeled_error(
            "No file(s) or application provided",
            "no file(s) or application provided",
            tag,
        ));
    }
    let status = match Command::new(cmd)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .args(args)
        .status()
    {
        Ok(exit_code) => exit_code,
        Err(_) => {
            return Err(ShellError::labeled_error(
                "Failed to run native open syscall",
                "failed to run native open call",
                tag,
            ))
        }
    };
    if status.success() {
        Ok(())
    } else {
        Err(ShellError::labeled_error(
            "Failed to run start. Hint: The file(s)/application may not exist",
            "failed to run",
            tag,
        ))
    }
}