util: use env vars instead of Rust crates for determining host and usernames

Summary: Using `whoami::devicename` causes issues on macOS sometimes, plus it gives us funny looking hostnames on POSIX in general, so let's drop it. Using environment variables to getting this value as well as getting the username is probably fine, so let's do that instead.

Reviewed By: mitrandir77

Differential Revision: D56724499

fbshipit-source-id: b36a08a48121cecfdb34ed33f68422d687b0346d
This commit is contained in:
Saul Gutierrez 2024-05-03 12:30:33 -07:00 committed by Facebook GitHub Bot
parent 904bf3b2c3
commit 630551a610
4 changed files with 18 additions and 9 deletions

View File

@ -141,7 +141,7 @@ impl Journal {
let command = util::sys::shell_escape(raw_args);
let timestamp = hgtime::HgTime::now()
.context("unable to determine current time when writing to journal")?;
let user = util::sys::username();
let user = util::sys::username()?;
let command = if let Some((left, _)) = command.split_once('\n') {
format!("{} ...", left)
} else {

View File

@ -16,7 +16,6 @@ rand = { version = "0.8", features = ["small_rng"] }
shell-escape = "0.1.5"
shellexpand = "2.1.2"
thiserror = "1.0.49"
whoami = "1.4"
[dev-dependencies]
memmap2 = "0.5.10"

View File

@ -70,7 +70,6 @@ rust_library(
"fbsource//third-party/rust:shell-escape",
"fbsource//third-party/rust:shellexpand",
"fbsource//third-party/rust:thiserror",
"fbsource//third-party/rust:whoami",
"//eden/scm/lib/atomicfile:atomicfile",
"//eden/scm/lib/lazystr:lazystr",
],

View File

@ -7,23 +7,34 @@
use std::borrow::Cow;
use anyhow::Context;
use anyhow::Result;
pub fn hostname() -> String {
if std::env::var_os("TESTTMP").is_some() || cfg!(test) {
// Doesn't seem like we want to use the real hostname in tests.
// Also, this may fix some debugruntest issues on mac due to whoami issues.
"test-hostname".to_owned()
} else {
// On Mac this calls system library functions, so may not be post fork safe.
// This could be one of the reasons chg doesn't work on mac anymore...
whoami::devicename()
std::env::var_os(if cfg!(windows) {
"COMPUTERNAME"
} else if cfg!(macos) {
"HOST"
} else {
"HOSTNAME"
})
.map_or(None, |h| h.to_str().map(|s| s.to_string()))
.unwrap_or("".to_owned())
}
}
pub fn username() -> String {
pub fn username() -> Result<String> {
if std::env::var_os("TESTTMP").is_some() || cfg!(test) {
"test".to_owned()
Ok("test".to_owned())
} else {
whoami::username()
std::env::var_os(if cfg!(windows) { "USERNAME" } else { "USER" })
.context("to get username")
.map(|k| k.to_string_lossy().to_string())
}
}