util/
sys.rs

1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8use std::borrow::Cow;
9
10use anyhow::Context;
11use anyhow::Result;
12
13pub fn hostname() -> String {
14    if std::env::var_os("TESTTMP").is_some() || cfg!(test) {
15        // Doesn't seem like we want to use the real hostname in tests.
16        // Also, this may fix some debugruntest issues on mac due to whoami issues.
17        "test-hostname".to_owned()
18    } else {
19        std::env::var_os(if cfg!(windows) {
20            "COMPUTERNAME"
21        } else if cfg!(target_os = "macos") {
22            "HOST"
23        } else {
24            "HOSTNAME"
25        })
26        .and_then(|h| h.to_str().map(|s| s.to_string()))
27        .unwrap_or("".to_owned())
28    }
29}
30
31pub fn username() -> Result<String> {
32    if std::env::var_os("TESTTMP").is_some() || cfg!(test) {
33        Ok("test".to_owned())
34    } else {
35        std::env::var_os(if cfg!(windows) { "USERNAME" } else { "USER" })
36            .context("to get username")
37            .map(|k| k.to_string_lossy().to_string())
38    }
39}
40
41pub fn shell_escape(args: &[String]) -> String {
42    args.iter()
43        .map(|a| shell_escape::escape(Cow::Borrowed(a.as_str())))
44        .collect::<Vec<_>>()
45        .join(" ")
46}