summaryrefslogtreecommitdiffstats
path: root/testing/mozbase/rust/mozrunner/src/firefox_args.rs
blob: 49f873f9dc82d402860ba76e04c5f0370cd0bd1f (plain)
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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

//! Argument string parsing and matching functions for Firefox.
//!
//! Which arguments Firefox accepts and in what style depends on the platform.
//! On Windows only, arguments can be prefixed with `/` (slash), such as
//! `/screenshot`.  Elsewhere, including Windows, arguments may be prefixed
//! with both single (`-screenshot`) and double (`--screenshot`) dashes.
//!
//! An argument's name is determined by a space or an assignment operator (`=`)
//! so that for the string `-foo=bar`, `foo` is considered the argument's
//! basename.

use crate::runner::platform;
use std::ffi::{OsStr, OsString};
use std::fmt;

/// Parse an argument string into a name and value
///
/// Given an argument like `"--arg=value"` this will split it into
/// `(Some("arg"), Some("value")). For a case like `"--arg"` it will
/// return `(Some("arg"), None)` and where the input doesn't look like
/// an argument e.g. `"value"` it will return `(None, Some("value"))`
fn parse_arg_name_value<T>(arg: T) -> (Option<String>, Option<String>)
where
    T: AsRef<OsStr>,
{
    let arg_os_str: &OsStr = arg.as_ref();
    let arg_str = arg_os_str.to_string_lossy();

    let mut name_start = 0;
    let mut name_end = 0;

    // Look for an argument name at the start of the
    // string
    for (i, c) in arg_str.chars().enumerate() {
        if i == 0 {
            if !platform::arg_prefix_char(c) {
                break;
            }
        } else if i == 1 {
            if name_end_char(c) {
                break;
            } else if c != '-' {
                name_start = i;
                name_end = name_start + 1;
            } else {
                name_start = i + 1;
                name_end = name_start;
            }
        } else {
            name_end += 1;
            if name_end_char(c) {
                name_end -= 1;
                break;
            }
        }
    }

    let name = if name_start > 0 && name_end > name_start {
        Some(arg_str[name_start..name_end].into())
    } else {
        None
    };

    // If there are characters in the string after the argument, read
    // them as the value, excluding the seperator (e.g. "=") if
    // present.
    let mut value_start = name_end;
    let value_end = arg_str.len();
    let value = if value_start < value_end {
        if let Some(c) = arg_str[value_start..value_end].chars().next() {
            if name_end_char(c) {
                value_start += 1;
            }
        }
        Some(arg_str[value_start..value_end].into())
    } else {
        None
    };
    (name, value)
}

fn name_end_char(c: char) -> bool {
    c == ' ' || c == '='
}

/// Represents a Firefox command-line argument.
#[derive(Debug, PartialEq)]
pub enum Arg {
    /// `-foreground` ensures application window gets focus, which is not the
    /// default on macOS. As such Firefox only supports it on MacOS.
    Foreground,

    /// --marionette enables Marionette in the application which is used
    /// by WebDriver HTTP.
    Marionette,

    /// `-no-remote` prevents remote commands to this instance of Firefox, and
    /// ensure we always start a new instance.
    NoRemote,

    /// `-P NAME` starts Firefox with a profile with a given name.
    NamedProfile,

    /// `-profile PATH` starts Firefox with the profile at the specified path.
    Profile,

    /// `-ProfileManager` starts Firefox with the profile chooser dialogue.
    ProfileManager,

    /// All other arguments.
    Other(String),

    /// --remote-allow-hosts contains comma-separated values of the Host header
    /// to allow for incoming WebSocket requests of the Remote Agent.
    RemoteAllowHosts,

    /// --remote-allow-origins contains comma-separated values of the Origin header
    /// to allow for incoming WebSocket requests of the Remote Agent.
    RemoteAllowOrigins,

    /// --remote-debugging-port enables the Remote Agent in the application
    /// which is used for the WebDriver BiDi and CDP remote debugging protocols.
    RemoteDebuggingPort,

    /// Not an argument.
    None,
}

impl Arg {
    pub fn new(name: &str) -> Arg {
        match name {
            "foreground" => Arg::Foreground,
            "marionette" => Arg::Marionette,
            "no-remote" => Arg::NoRemote,
            "profile" => Arg::Profile,
            "P" => Arg::NamedProfile,
            "ProfileManager" => Arg::ProfileManager,
            "remote-allow-hosts" => Arg::RemoteAllowHosts,
            "remote-allow-origins" => Arg::RemoteAllowOrigins,
            "remote-debugging-port" => Arg::RemoteDebuggingPort,
            _ => Arg::Other(name.into()),
        }
    }
}

impl<'a> From<&'a OsString> for Arg {
    fn from(arg_str: &OsString) -> Arg {
        if let (Some(name), _) = parse_arg_name_value(arg_str) {
            Arg::new(&name)
        } else {
            Arg::None
        }
    }
}

impl fmt::Display for Arg {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&match self {
            Arg::Foreground => "--foreground".to_string(),
            Arg::Marionette => "--marionette".to_string(),
            Arg::NamedProfile => "-P".to_string(),
            Arg::None => "".to_string(),
            Arg::NoRemote => "--no-remote".to_string(),
            Arg::Other(x) => format!("--{}", x),
            Arg::Profile => "--profile".to_string(),
            Arg::ProfileManager => "--ProfileManager".to_string(),
            Arg::RemoteAllowHosts => "--remote-allow-hosts".to_string(),
            Arg::RemoteAllowOrigins => "--remote-allow-origins".to_string(),
            Arg::RemoteDebuggingPort => "--remote-debugging-port".to_string(),
        })
    }
}

/// Parse an iterator over arguments into an vector of (name, value)
/// tuples
///
/// Each entry in the input argument will produce a single item in the
/// output. Because we don't know anything about the specific
/// arguments, something that doesn't parse as a named argument may
/// either be the value of a previous named argument, or may be a
/// positional argument.
pub fn parse_args<'a>(
    args: impl Iterator<Item = &'a OsString>,
) -> Vec<(Option<Arg>, Option<String>)> {
    args.map(parse_arg_name_value)
        .map(|(name, value)| {
            if let Some(arg_name) = name {
                (Some(Arg::new(&arg_name)), value)
            } else {
                (None, value)
            }
        })
        .collect()
}

/// Given an iterator over all arguments, get the value of an argument
///
/// This assumes that the argument takes a single value and that is
/// either provided as a single argument entry
/// (e.g. `["--name=value"]`) or as the following argument
/// (e.g. `["--name", "value"])
pub fn get_arg_value<'a>(
    mut parsed_args: impl Iterator<Item = &'a (Option<Arg>, Option<String>)>,
    arg: Arg,
) -> Option<String> {
    let mut found_value = None;
    for (arg_name, arg_value) in &mut parsed_args {
        if let (Some(name), value) = (arg_name, arg_value) {
            if *name == arg {
                found_value = value.clone();
                break;
            }
        }
    }
    if found_value.is_none() {
        // If there wasn't a value, check if the following argument is a value
        if let Some((None, value)) = parsed_args.next() {
            found_value = value.clone();
        }
    }
    found_value
}

#[cfg(test)]
mod tests {
    use super::{get_arg_value, parse_arg_name_value, parse_args, Arg};
    use std::ffi::OsString;

    fn parse(arg: &str, name: Option<&str>) {
        let (result, _) = parse_arg_name_value(arg);
        assert_eq!(result, name.map(|x| x.to_string()));
    }

    #[test]
    fn test_parse_arg_name_value() {
        parse("-p", Some("p"));
        parse("--p", Some("p"));
        parse("--profile foo", Some("profile"));
        parse("--profile", Some("profile"));
        parse("--", None);
        parse("", None);
        parse("-=", None);
        parse("--=", None);
        parse("-- foo", None);
        parse("foo", None);
        parse("/ foo", None);
        parse("/- foo", None);
        parse("/=foo", None);
        parse("foo", None);
        parse("-profile", Some("profile"));
        parse("-profile=foo", Some("profile"));
        parse("-profile = foo", Some("profile"));
        parse("-profile abc", Some("profile"));
        parse("-profile /foo", Some("profile"));
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn test_parse_arg_name_value_windows() {
        parse("/profile", Some("profile"));
    }

    #[cfg(not(target_os = "windows"))]
    #[test]
    fn test_parse_arg_name_value_non_windows() {
        parse("/profile", None);
    }

    #[test]
    fn test_arg_from_osstring() {
        assert_eq!(Arg::from(&OsString::from("--foreground")), Arg::Foreground);
        assert_eq!(Arg::from(&OsString::from("-foreground")), Arg::Foreground);

        assert_eq!(Arg::from(&OsString::from("--marionette")), Arg::Marionette);
        assert_eq!(Arg::from(&OsString::from("-marionette")), Arg::Marionette);

        assert_eq!(Arg::from(&OsString::from("--no-remote")), Arg::NoRemote);
        assert_eq!(Arg::from(&OsString::from("-no-remote")), Arg::NoRemote);

        assert_eq!(Arg::from(&OsString::from("-- profile")), Arg::None);
        assert_eq!(Arg::from(&OsString::from("profile")), Arg::None);
        assert_eq!(Arg::from(&OsString::from("profile -P")), Arg::None);
        assert_eq!(
            Arg::from(&OsString::from("-profiled")),
            Arg::Other("profiled".into())
        );
        assert_eq!(
            Arg::from(&OsString::from("-PROFILEMANAGER")),
            Arg::Other("PROFILEMANAGER".into())
        );

        assert_eq!(Arg::from(&OsString::from("--profile")), Arg::Profile);
        assert_eq!(Arg::from(&OsString::from("-profile foo")), Arg::Profile);

        assert_eq!(
            Arg::from(&OsString::from("--ProfileManager")),
            Arg::ProfileManager
        );
        assert_eq!(
            Arg::from(&OsString::from("-ProfileManager")),
            Arg::ProfileManager
        );

        // TODO: -Ptest is valid
        //assert_eq!(Arg::from(&OsString::from("-Ptest")), Arg::NamedProfile);
        assert_eq!(Arg::from(&OsString::from("-P")), Arg::NamedProfile);
        assert_eq!(Arg::from(&OsString::from("-P test")), Arg::NamedProfile);

        assert_eq!(
            Arg::from(&OsString::from("--remote-debugging-port")),
            Arg::RemoteDebuggingPort
        );
        assert_eq!(
            Arg::from(&OsString::from("-remote-debugging-port")),
            Arg::RemoteDebuggingPort
        );
        assert_eq!(
            Arg::from(&OsString::from("--remote-debugging-port 9222")),
            Arg::RemoteDebuggingPort
        );

        assert_eq!(
            Arg::from(&OsString::from("--remote-allow-hosts")),
            Arg::RemoteAllowHosts
        );
        assert_eq!(
            Arg::from(&OsString::from("-remote-allow-hosts")),
            Arg::RemoteAllowHosts
        );
        assert_eq!(
            Arg::from(&OsString::from("--remote-allow-hosts 9222")),
            Arg::RemoteAllowHosts
        );

        assert_eq!(
            Arg::from(&OsString::from("--remote-allow-origins")),
            Arg::RemoteAllowOrigins
        );
        assert_eq!(
            Arg::from(&OsString::from("-remote-allow-origins")),
            Arg::RemoteAllowOrigins
        );
        assert_eq!(
            Arg::from(&OsString::from("--remote-allow-origins http://foo")),
            Arg::RemoteAllowOrigins
        );
    }

    #[test]
    fn test_get_arg_value() {
        let args = vec!["-P", "ProfileName", "--profile=/path/", "--no-remote"]
            .iter()
            .map(|x| OsString::from(x))
            .collect::<Vec<OsString>>();
        let parsed_args = parse_args(args.iter());
        assert_eq!(
            get_arg_value(parsed_args.iter(), Arg::NamedProfile),
            Some("ProfileName".into())
        );
        assert_eq!(
            get_arg_value(parsed_args.iter(), Arg::Profile),
            Some("/path/".into())
        );
        assert_eq!(get_arg_value(parsed_args.iter(), Arg::NoRemote), None);

        let args = vec!["--profile=", "-P test"]
            .iter()
            .map(|x| OsString::from(x))
            .collect::<Vec<OsString>>();
        let parsed_args = parse_args(args.iter());
        assert_eq!(
            get_arg_value(parsed_args.iter(), Arg::NamedProfile),
            Some("test".into())
        );
        assert_eq!(
            get_arg_value(parsed_args.iter(), Arg::Profile),
            Some("".into())
        );
    }
}